SQLServer中常用SQL语句整理

1. SQL语句更新一个表的字段值等于另一个表的字段值

目标:两个表分别为Table1和Table2,更新Table1中某个字段Field的值为Table2中的某个字段Field的值,并且满足Table1中字段Field1与Table2中字段Field2的值相等,对应的SQL语句如下所示:

UPDATE [Table1] SET [Table1].[Field]=(SELECT [t2].[Field] FROM [Table2] [t2] WHERE [Table1].[Field1]=[t2].[Field2])

2. 删除表

目标:删除表Table1,对应的SQL语句如下所示:

DROP TABLE [Table1]

3. 增加字段

目标:向表Table1中添加字段Field1,对应的SQL语句如下所示:

// alter   table   表名   add   列名   数据类型
ALTER TABLE [Table1] ADD [Field1] nvarchar(10)

4. 删除字段

目标:将表Table1中的字段Field1删除,对应的SQL语句如下所示:

// ALTER TABLE [table_NAME] DROP COLUMN [column_NAME]
ALTER TABLE [Table1] DROP COLUMN [Field1]

5. 从一张表查询数据并插入到另一张表中

目标:从表Table1中查询字段Field1和字段Field2的数据,并插入到表Table2相应的字段中,对应的SQL语句如下所示:

INSERT INTO [Table2]([Field1],[Field2]) SELECT [Field1],[Field2] FROM [Table1]

6. 根据某一个字段重复只取第一条数据

目标:从表Table1中查询数据,当字段Field1重复时,根据字段Field2排序取第一条记录,对应的SQL语句如下所示:

SELECT s.*
FROM (
    SELECT *, row_number() over (PARTITION BY [Field1] ORDER BY [Field2]) AS group_idx  
    FROM [Table1]
) s
WHERE s.group_idx = 1

其中,partition by 是指定按哪些字段进行分组,这些字段值相同的记录将在一起编号;ORDER BY则是指定在同一组中进行编号时是按照怎样的顺序。

7. 自定义查询结果排序

目标:从表Table1中查询数据,并根据字段Field1的不同值进行排序,对应的SQL语句如下所示:

SELECT * FROM Table1 ORDER BY (CASE Field1 WHEN 'Value1' THEN 1 WHEN 'Value2' THEN 2 WHEN 'Value3' THEN 3 WHEN 'Value4' THEN 4 ELSE '' END)

8. 一条记录返回多个COUNT值

目标:从表Table1中查询不同条件的COUNT值,并合并成一条记录,对应的SQL语句如下所示:

SELECT (SELECT COUNT(*) FROM [Table1] WHERE <Condition1>) AS C1,(SELECT COUNT(*) FROM [Table1] WHERE <Condition2>) AS C2 

9. 判断SQLServer表中某字段是否存在

目标:判断表Table1中是否存在字段Field1,对应的SQL语句如下所示,结果返回1则存在,0则不存在:

SELECT COUNT(*) FROM syscolumns WHERE id=object_id('Table1') AND name='Field1'

10. 查询表中某个字段相同,但另一个字段不相同的记录

目标:查询表Table1中字段Field1相同,但字段Field2不相同的记录,例如从下表:

Field1Field2
212
3223
121
233

查询出结果:

Field1Field2
212
233

对应的SQL语句如下所示:

SELECT DISTINCT [x].[Field1],[x].[Field2]
FROM [Table1] AS [x],[Table1] AS [y]
WHERE [x].[Field1]=[y].[Field1] AND [x].[Field2]!=[y].[Field2]
ORDER BY [Field1],[Field2]

11. 查询表中某个字段重复的记录

目标:查询表Table1中字段Field1数据重复的记录,对应的SQL语句如下所示:

SELECT * FROM [Table1] WHERE [Field1] in (SELECT [Field1] FROM [Table1] GROUP BY [Field1] HAVING COUNT([Field1])>1)

(持续更新中…)

    原文作者:冷大大_hawkleng
    原文地址: https://www.jianshu.com/p/dc314a1c9e2f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞