SQL Server进阶(三)单表查询

示例数据库

  点我下载

一条完整的sql语句

select top | distinct   字段, 表达式, 函数, ...
from   表表达式
where  筛选条件
group by  分组条件
having     筛选条件
order by   排序依据;

SQL的执行顺序:

  

SELECT语句的元素

SELECT empid, YEAR(orderdate) AS orderyear, COUNT(*) AS numorders
FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)
HAVING COUNT(*) > 1
ORDER BY empid, orderyear;

FROM子句

WHERE子句

GROUP BY子句

SELECT
  empid,
  YEAR(orderdate) AS orderyear,
  SUM(freight) AS totalfreight,
  COUNT(*) AS numorders
FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate);

除了COUNT(*)之外,所有聚合函数忽略NULL标记。

DISTINCT去重

SELECT
  empid,
  YEAR(orderdate) AS orderyear,
  COUNT(DISTINCT custid) AS numcusts
FROM Sales.Orders
GROUP BY empid, YEAR(orderdate);

HAVING子句

SELECT empid, YEAR(orderdate) AS orderyear
FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)
HAVING COUNT(*) > 1;

SELECT子句

ORDER BY子句

SELECT empid, YEAR(orderdate) AS orderyear, COUNT(*) AS numorders
FROM Sales.Orders
WHERE custid = 71
GROUP BY empid, YEAR(orderdate)
HAVING COUNT(*) > 1
ORDER BY empid, orderyear;

TOP和OFFSET-FETCH筛选

PERCENT

SELECT TOP (1) PERCENT orderid, orderdate, custid, empid
FROM Sales.Orders
ORDER BY orderdate DESC;

WITH TIES

SELECT TOP (5) WITH TIES orderid, orderdate, custid, empid
FROM Sales.Orders
ORDER BY orderdate DESC;

OFFSET-FETCH筛选(跳过50取25)

SELECT orderid, orderdate, custid, empid
FROM Sales.Orders
ORDER BY orderdate, orderid
OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;

开窗函数

SELECT orderid, custid, val,
  ROW_NUMBER() OVER(PARTITION BY custid
                    ORDER BY val) AS rownum
FROM Sales.OrderValues
ORDER BY custid, val;

谓词和运算符

CASE表达式

NULL标记

同时操作

使用字符数据

SELECT SUBSTRING(‘abcde‘, 1, 3); -- ‘abc‘

SELECT RIGHT(‘abcde‘, 3); -- ‘cde‘

SELECT LEN(N‘abcde‘); -- 5

SELECT DATALENGTH(N‘abcde‘); -- 10

SELECT CHARINDEX(‘ ‘,‘Itzik Ben-Gan‘); -- 6

SELECT PATINDEX(‘%[0-9]%‘, ‘abcd123efgh‘); -- 5

SELECT REPLACE(‘1-a 2-b‘, ‘-‘, ‘:‘); -- ‘1:a 2:b‘

SELECT empid, lastname,
  LEN(lastname) - LEN(REPLACE(lastname, ‘e‘, ‘‘)) AS numoccur
FROM HR.Employees;

SELECT REPLICATE(‘abc‘, 3); -- ‘abcabcabc‘

SELECT supplierid,
  RIGHT(REPLICATE(‘0‘, 9) + CAST(supplierid AS VARCHAR(10)),
        10) AS strsupplierid
FROM Production.Suppliers;

SELECT STUFF(‘xyz‘, 2, 1, ‘abc‘); -- ‘xabcz‘

SELECT UPPER(‘Itzik Ben-Gan‘); -- ‘ITZIK BEN-GAN‘

SELECT LOWER(‘Itzik Ben-Gan‘); -- ‘itzik ben-gan‘

SELECT RTRIM(LTRIM(‘   abc   ‘)); -- ‘abc‘

SELECT FORMAT(1759, ‘0000000000‘); -- ‘0000001759‘

日期和时间

-- Current Date and Time
SELECT
  GETDATE()           AS [GETDATE],
  CURRENT_TIMESTAMP   AS [CURRENT_TIMESTAMP],
  GETUTCDATE()        AS [GETUTCDATE],
  SYSDATETIME()       AS [SYSDATETIME],
  SYSUTCDATETIME()    AS [SYSUTCDATETIME],
  SYSDATETIMEOFFSET() AS [SYSDATETIMEOFFSET];

SELECT
  CAST(SYSDATETIME() AS DATE) AS [current_date],
  CAST(SYSDATETIME() AS TIME) AS [current_time];

-- The CAST, CONVERT and PARSE Functions and their TRY_ Counterparts
SELECT CAST(‘20090212‘ AS DATE);
SELECT CAST(SYSDATETIME() AS DATE);
SELECT CAST(SYSDATETIME() AS TIME);

SELECT CONVERT(CHAR(8), CURRENT_TIMESTAMP, 112);
SELECT CAST(CONVERT(CHAR(8), CURRENT_TIMESTAMP, 112) AS DATETIME);

SELECT CONVERT(CHAR(12), CURRENT_TIMESTAMP, 114);
SELECT CAST(CONVERT(CHAR(12), CURRENT_TIMESTAMP, 114) AS DATETIME);

SELECT PARSE(‘02/12/2007‘ AS DATETIME USING ‘en-US‘);
SELECT PARSE(‘02/12/2007‘ AS DATETIME USING ‘en-GB‘);

-- SWITCHOFFSET
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), ‘-05:00‘);
SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), ‘+00:00‘);

-- TODATETIMEOFFSET
/*
UPDATE dbo.T1
  SET dto = TODATETIMEOFFSET(dt, theoffset);
*/

-- DATEADD
SELECT DATEADD(year, 1, ‘20090212‘);

-- DATEDIFF
SELECT DATEDIFF(day, ‘20080212‘, ‘20090212‘);

SELECT
  DATEADD(
    day,
    DATEDIFF(day, ‘20010101‘, CURRENT_TIMESTAMP), ‘20010101‘);

SELECT
  DATEADD(
    month,
    DATEDIFF(month, ‘20010101‘, CURRENT_TIMESTAMP), ‘20010101‘);

SELECT
  DATEADD(
    month,
    DATEDIFF(month, ‘20091231‘, CURRENT_TIMESTAMP), ‘20091231‘);

-- DATEPART

SELECT DATEPART(month, ‘20090212‘);

-- DAY, MONTH, YEAR

SELECT
  DAY(‘20090212‘) AS theday,
  MONTH(‘20090212‘) AS themonth,
  YEAR(‘20090212‘) AS theyear;

-- DATENAME
SELECT DATENAME(month, ‘20090212‘);

SELECT DATENAME(year, ‘20090212‘);

-- ISDATE
SELECT ISDATE(‘20090212‘);
SELECT ISDATE(‘20090230‘);

-- fromparts
SELECT
  DATEFROMPARTS(2012, 02, 12),
  DATETIME2FROMPARTS(2012, 02, 12, 13, 30, 5, 1, 7),
  DATETIMEFROMPARTS(2012, 02, 12, 13, 30, 5, 997),
  DATETIMEOFFSETFROMPARTS(2012, 02, 12, 13, 30, 5, 1, -8, 0, 7),
  SMALLDATETIMEFROMPARTS(2012, 02, 12, 13, 30),
  TIMEFROMPARTS(13, 30, 5, 1, 7);

-- EOMONTH
SELECT EOMONTH(SYSDATETIME());

查询元数据

-- Catalog Views
USE TSQL2012;

SELECT SCHEMA_NAME(schema_id) AS table_schema_name, name AS table_name
FROM sys.tables;

SELECT
  name AS column_name,
  TYPE_NAME(system_type_id) AS column_type,
  max_length,
  collation_name,
  is_nullable
FROM sys.columns
WHERE object_id = OBJECT_ID(N‘Sales.Orders‘);

-- Information Schema Views
SELECT TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = N‘BASE TABLE‘;

SELECT
  COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
  COLLATION_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = N‘Sales‘
  AND TABLE_NAME = N‘Orders‘;

-- System Stored Procedures and Functions
EXEC sys.sp_tables;

EXEC sys.sp_help
  @objname = N‘Sales.Orders‘;

EXEC sys.sp_columns
  @table_name = N‘Orders‘,
  @table_owner = N‘Sales‘;

EXEC sys.sp_helpconstraint
  @objname = N‘Sales.Orders‘;

SELECT
  SERVERPROPERTY(‘ProductLevel‘);

SELECT
  DATABASEPROPERTYEX(N‘TSQL2012‘, ‘Collation‘);

SELECT
  OBJECTPROPERTY(OBJECT_ID(N‘Sales.Orders‘), ‘TableHasPrimaryKey‘);

SELECT
  COLUMNPROPERTY(OBJECT_ID(N‘Sales.Orders‘), N‘shipcountry‘, ‘AllowsNull‘);

原文地址:https://www.cnblogs.com/cnki/p/9609296.html

时间: 2024-10-11 02:47:00

SQL Server进阶(三)单表查询的相关文章

Sql Server数据库之多表查询

一.连接查询 概念:根据两个表或多个表的列之间的关系,从这些表中查询数据 目的:实现多表查询操作 语法:From join_table join_type join_table[ON(join_condition)] join_table:连接的表名 join_type:连接类型 join_condition:连接条件 连接类型:内连接,外连接,交叉连接 二.内连接 1.等值连接 概念:在连接条件中使用"="运算符,其查询结果中列出被连接表中的所有列,包括其中的重复列 示例: 1 cr

SQL Server进阶(八)查询

开窗函数 透视数据 逆透视数据 分组集 小结 练习 解决方案 原文地址:https://www.cnblogs.com/cnki/p/9615056.html

【知了堂学习笔记】SQL查询基础语句(单表查询、多表查询)

SQL查询基础 1.单表查询 从数据库中查找数据 专业的称谓又称为投影 基本查询语句结构 select 列 from 表 * 所有列不是所有其他东西 查询所有数据 例:SELECT * FROM t_studen 需要执行比较细的操作  加上条件筛选:查询id为2号的学生信息 SELECT * FROM t_student WHERE id=2; 筛选的执行步骤 例:SELECT * FROM t_student WHERE id=2; SELECT *          (3) 再查询  筛选

一个MySQL 单表查询SQL,引起一次“故事”

一.描述故事的过程是这个样子的,MySQL 数据库有一张40多G的大表,开发人员执行了一个单表查询,结果我就收到了一个磁盘空间满的告警.一下子就不淡定了,谁在搞事情,脑海里各种可能行想了一遍,想到的最多的就是ibtmp1爆了,第一时间线上看一下,查到了最大的那个文件,结果和想的一样.这里我们要看SQL是怎么写的,表结构是什么样子,然后和官网对比,MySQL在查询的时候有很多可能会使用磁盘临时表,包括表连接.排序.大字段等等. 二.解决方法临时解决方法:1.临时扩一下硬盘2.直接重启 终结解决方案

python 之 Django框架(orm单表查询、orm多表查询、聚合查询、分组查询、F查询、 Q查询、事务、Django ORM执行原生SQL)

12.329 orm单表查询 import os if __name__ == '__main__': # 指定当前py脚本需要加载的Django项目配置信息 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm_demo.settings") import django django.setup() # 启动Django项目 from app01 import models #返回QuerySet对象的方法: r

用SQL server导出到oracle,查询时提示“表或视图不存在ORA-00942”错误

用SQL server2005的导出工具,将数据导出表到oracle,表名称里看到有这张表了,但查询或删除时都提示“ORA-00942表或者试图不存在”的错误,上网查了一下,是如下原因: “查询或删除名称存在的表时,却提示不存在,你看看在user_tables里这几个表名是小写吗? 那说明你建表的时候肯定带引号了,请select的时候也带上引号.例如:select * from "tableName",可以看出如果在SQLserver中,如果表名是小写的,那导入到oracle时,建表时

MySQL数据库实验二:单表查询

实验二   单表查询 一.实验目的 理解SELECT语句的操作和基本使用方法. 二.实验环境 是MS SQL SERVER 2005的中文客户端. 三.实验示例 1.查询全体学生的姓名.学号.所在系. SELECT Sname,S#,Sdept FROM S: 2.查询全体学生的详细记录. SELECT  * FROM S: 3.查全体学生的姓名及其出生年份. SELECT Sname,2011-Sage    /*假定当年的年份为2011年*/ FROM S: 4.查询选修了课程的学生学号.

SQL语句基础之 单表查找

Sql语句之 单表查询 一.一般查询 1.查看表中的所有记录 以及 所有字段(属性) 语句 : select * from student; 2.只查看某些字段 语句:select sname,sex from student; 3.把查询出来的结果的字段名显示为其它名字 语句: select sname as ‘姓名’ , sage as ‘年龄’ from student; 4.在查询结果中添加一列,这一列的值为一个常量 语句:select sname,sex,’广州’ address fr

SQL Server之 (三) 分组 类型转换函数 插入多条数据 字符串函数

SQL Server之 (三)  分组 类型转换函数  插入多条数据  字符串函数 自己学习笔记,转载请注明出处,谢谢!---酸菜 1.SQL 数据分组----Group by /Having  ①有一学生信息表:StuID/StuName/StuAge/StuGender/StuClassID; 求每个班级的ID和对应人数:select StuClassID 班级ID,count(*) 班级人数  from StuInfo group by StuClassID ; 求所有同学中男女同学对应人

SQL Server 2014 内存优化表

不同于disk-based table,内存优化表驻留在内存中,使用 Hekaton 内存数据库引擎实现.在查询时,从内存中读取数据行:在更新时,将数据的更新直接写入到内存中.内存优化表能够在disk上维护一个副本,用于持久化数据集. Memory-optimized tables reside in memory. Rows in the table are read from and written to memory. The entire table resides in memory.