当前位置:Gxlcms > mssql > 15个初学者必看的基础SQL查询语句

15个初学者必看的基础SQL查询语句

时间:2021-07-01 10:21:17 帮助过:55人阅读

本文将分享15个初学者必看的基础SQL查询语句,都很基础,但是你不一定都会,所以好好看看吧。

1、创建表和数据插入SQL

我们在开始创建数据表和向表中插入演示数据之前,我想给大家解释一下实时数据表的设计理念,这样也许能帮助大家能更好的理解SQL查询。

在数据库设计中,有一条非常重要的规则就是要正确建立主键和外键的关系。

现在我们来创建几个餐厅订单管理的数据表,一共用到3张数据表,Item Master表、Order Master表和Order Detail表。

创建表:

创建Item Master表:

  1. CREATE TABLE [dbo].[ItemMasters](
  2. [Item_Code] [varchar](20) NOT NULL,
  3. [Item_Name] [varchar](100) NOT NULL,
  4. [Price] Int NOT NULL,
  5. [TAX1] Int NOT NULL,
  6. [Discount] Int NOT NULL,
  7. [Description] [varchar](200) NOT NULL,
  8. [IN_DATE] [datetime] NOT NULL,
  9. [IN_USR_ID] [varchar](20) NOT NULL,
  10. [UP_DATE] [datetime] NOT NULL,
  11. [UP_USR_ID] [varchar](20) NOT NULL,
  12. CONSTRAINT [PK_ItemMasters] PRIMARY KEY CLUSTERED
  13. (
  14. [Item_Code] ASC
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  16. ) ON [PRIMARY]

向Item Master表插入数据:

  1. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
  2. ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  3. VALUES
  4. ('Item001','Coke',55,1,0,'Coke which need to be cold',GETDATE(),'SHANU'
  5. ,GETDATE(),'SHANU')
  6. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
  7. ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  8. VALUES
  9. ('Item002','Coffee',40,0,2,'Coffe Might be Hot or Cold user choice',GETDATE(),'SHANU'
  10. ,GETDATE(),'SHANU')
  11. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
  12. ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  13. VALUES
  14. ('Item003','Chiken Burger',125,2,5,'Spicy',GETDATE(),'SHANU'
  15. ,GETDATE(),'SHANU')
  16. INSERT INTO [ItemMasters] ([Item_Code],[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
  17. ,[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  18. VALUES
  19. ('Item004','Potato Fry',15,0,0,'No Comments',GETDATE(),'SHANU'
  20. ,GETDATE(),'SHANU')

创建Order Master表:

  1. CREATE TABLE [dbo].[OrderMasters](
  2. [Order_No] [varchar](20) NOT NULL,
  3. [Table_ID] [varchar](20) NOT NULL,
  4. [Description] [varchar](200) NOT NULL,
  5. [IN_DATE] [datetime] NOT NULL,
  6. [IN_USR_ID] [varchar](20) NOT NULL,
  7. [UP_DATE] [datetime] NOT NULL,
  8. [UP_USR_ID] [varchar](20) NOT NULL,
  9. CONSTRAINT [PK_OrderMasters] PRIMARY KEY CLUSTERED
  10. (
  11. [Order_No] ASC
  12. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  13. ) ON [PRIMARY]

向Order Master表插入数据:

  1. INSERT INTO [OrderMasters]
  2. ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  3. VALUES
  4. ('Ord_001','T1','',GETDATE(),'SHANU' ,GETDATE(),'SHANU')
  5. INSERT INTO [OrderMasters]
  6. ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  7. VALUES
  8. ('Ord_002','T2','',GETDATE(),'Mak' ,GETDATE(),'MAK')
  9. INSERT INTO [OrderMasters]
  10. ([Order_No],[Table_ID] ,[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  11. VALUES
  12. ('Ord_003','T3','',GETDATE(),'RAJ' ,GETDATE(),'RAJ')

创建Order Detail表:

  1. CREATE TABLE [dbo].[OrderDetails](
  2. [Order_Detail_No] [varchar](20) NOT NULL,
  3. [Order_No] [varchar](20) CONSTRAINT fk_OrderMasters FOREIGN KEY REFERENCES OrderMasters(Order_No),
  4. [Item_Code] [varchar](20) CONSTRAINT fk_ItemMasters FOREIGN KEY REFERENCES ItemMasters(Item_Code),
  5. [Notes] [varchar](200) NOT NULL,
  6. [QTY] INT NOT NULL,
  7. [IN_DATE] [datetime] NOT NULL,
  8. [IN_USR_ID] [varchar](20) NOT NULL,
  9. [UP_DATE] [datetime] NOT NULL,
  10. [UP_USR_ID] [varchar](20) NOT NULL,
  11. CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED
  12. (
  13. [Order_Detail_No] ASC
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  15. ) ON [PRIMARY]
  16. --Now let’s insert the 3 items for the above Order No 'Ord_001'.
  17. INSERT INTO [OrderDetails]
  18. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  19. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  20. VALUES
  21. ('OR_Dt_001','Ord_001','Item001','Need very Cold',3
  22. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
  23. INSERT INTO [OrderDetails]
  24. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  25. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  26. VALUES
  27. ('OR_Dt_002','Ord_001','Item004','very Hot ',2
  28. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
  29. INSERT INTO [OrderDetails]
  30. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  31. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  32. VALUES
  33. ('OR_Dt_003','Ord_001','Item003','Very Spicy',4
  34. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')

向Order Detail表插入数据:

  1. INSERT INTO [OrderDetails]
  2. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  3. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  4. VALUES
  5. ('OR_Dt_004','Ord_002','Item002','Need very Hot',2
  6. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
  7. INSERT INTO [OrderDetails]
  8. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  9. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  10. VALUES
  11. ('OR_Dt_005','Ord_002','Item003','very Hot ',2
  12. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')
  13. INSERT INTO [OrderDetails]
  14. ([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY]
  15. ,[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
  16. VALUES
  17. ('OR_Dt_006','Ord_003','Item003','Very Spicy',4
  18. ,GETDATE(),'SHANU' ,GETDATE(),'SHANU')

2、简单的Select查询语句

Select查询语句是SQL中最基本也是最重要的DML语句之一。那么什么是DML?DML全称Data Manipulation Language(数据操纵语言命令),它可以使用户能够查询数据库以及操作已有数据库中的数据。

下面我们在SQL Server中用select语句来查询我的姓名(Name):

  1. SELECT 'My Name Is SYED SHANU'
  2. -- With Column Name using 'AS'
  3. SELECT 'My Name Is SYED SHANU' as 'MY NAME'
  4. -- With more then the one Column
  5. SELECT 'My Name' as 'Column1', 'Is' as 'Column2', 'SYED SHANU' as 'Column3'

在数据表中使用select查询:

  1. -- To Display all the columns from the table we use * operator in select Statement.
  2. Select * from ItemMasters
  3. -- If we need to select only few fields from a table we can use the Column Name in Select Statement.
  4. Select Item_Code
  5. ,Item_name as Item
  6. ,Price
  7. ,Description
  8. ,In_DATE
  9. FROM
  10. ItemMasters

3、合计和标量函数

合计函数和标量函数都是SQL Server的内置函数,我们可以在select查询语句中使用它们,比如Count(), Max(), Sum(), Upper(), lower(), Round()等等。下面我们用SQL代码来解释这些函数的用法:

  1. select * from ItemMasters
  2. -- Aggregate
  3. -- COUNT() -> returns the Total no of records from table , AVG() returns the Average Value from Colum,MAX() Returns MaX Value from Column
  4. -- ,MIN() returns Min Value from Column,SUM() sum of total from Column
  5. Select Count(*) TotalRows,AVG(Price) AVGPrice
  6. ,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) PriceTotal
  7. FROM ItemMasters
  8. -- Scalar
  9. -- UCASE() -> Convert to Upper Case ,LCASE() -> Convert to Lower Case,
  10. -- SUBSTRING() ->Display selected char from column ->SUBSTRING(ColumnName,StartIndex,LenthofChartoDisplay)
  11. --,LEN() -> lenth of column date,
  12. -- ROUND() -> Which will round the value
  13. SELECT UPPER(Item_NAME) Uppers,LOWER(Item_NAME) Lowers,
  14. SUBSTRING(Item_NAME,2,3) MidValue,LEN(Item_NAME) Lenths
  15. ,SUBSTRING(Item_NAME,2,LEN(Item_NAME)) MidValuewithLenFunction,
  16. ROUND(Price,0) as Rounded
  17. FROM ItemMasters

4、日期函数

在我们的项目数据表中基本都会使用到日期列,因此日期函数在项目中扮演着非常重要的角色。有时候我们对日期函数要非常的小心,它随时可以给你带来巨大的麻烦。在项目中,我们要选择合适的日期函数和日期格式,下面是一些SQL日期函数的例子:

  1. -- GETDATE() -> to Display the Current Date and Time
  2. -- Format() -> used to display our date in our requested format
  3. Select GETDATE() CurrentDateTime, FORMAT(GETDATE(),'yyyy-MM-dd') AS DateFormats,
  4. FORMAT(GETDATE(),'HH-mm-ss')TimeFormats,
  5. CONVERT(VARCHAR(10),GETDATE(),10) Converts1,
  6. CONVERT(VARCHAR(24),GETDATE(),113),
  7. CONVERT(NVARCHAR, getdate(), 106) Converts2 ,-- here we used Convert Function
  8. REPLACE(convert(NVARCHAR, getdate(), 106), ' ', '/') Formats-- Here we used replace and --convert functions.
  9. --first we convert the date to nvarchar and then we replace the '' with '/'
  10. select * from Itemmasters
  11. Select ITEM_NAME,IN_DATE CurrentDateTime, FORMAT(IN_DATE,'yyyy-MM-dd') AS DateFormats,
  12. FORMAT(IN_DATE,'HH-mm-ss')TimeFormats,
  13. CONVERT(VARCHAR(10),IN_DATE,10) Converts1,
  14. CONVERT(VARCHAR(24),IN_DATE,113),
  15. convert(NVARCHAR, IN_DATE, 106) Converts2 ,-- here we used Convert Function
  16. REPLACE(convert(NVARCHAR,IN_DATE, 106), ' ', '/') Formats
  17. FROM Itemmasters

DatePart –>  该函数可以获取年、月、日的信息。

DateADD –>  该函数可以对当前的日期进行加减。

DateDiff  –>  该函数可以比较2个日期。

  1. --Datepart DATEPART(dateparttype,yourDate)
  2. SELECT DATEPART(yyyy,getdate()) AS YEARs ,
  3. DATEPART(mm,getdate()) AS MONTHS,
  4. DATEPART(dd,getdate()) AS Days,
  5. DATEPART(week,getdate()) AS weeks,
  6. DATEPART(hour,getdate()) AS hours
  7. --Days Add to add or subdtract date from a selected date.
  8. SELECT GetDate()CurrentDate,DATEADD(day,12,getdate()) AS AddDays ,
  9. DATEADD(day,-4,getdate()) AS FourDaysBeforeDate
  10. -- DATEDIFF() -> to display the Days between 2 dates
  11. select DATEDIFF(year,'2003-08-05',getdate()) yearDifferance ,
  12. DATEDIFF(day,DATEADD(day,-24,getdate()),getdate()) daysDifferent,
  13. DATEDIFF(month,getdate(),DATEADD(Month,6,getdate())) MonthDifferance

5、其他Select函数

Top —— 结合select语句,Top函数可以查询头几条和末几条的数据记录。

Order By —— 结合select语句,Order By可以让查询结果按某个字段正序和逆序输出数据记录。

  1. --Top to Select Top first and last records using Select Statement.
  2. Select * FROM ItemMasters
  3. --> First Display top 2 Records
  4. Select TOP 2 Item_Code
  5. ,Item_name as Item
  6. ,Price
  7. ,Description
  8. ,In_DATE
  9. FROM ItemMasters
  10. --> to Display the Last to Records we need to use the Order By Clause
  11. -- order By to display Records in assending or desending order by the columns
  12. Select TOP 2 Item_Code
  13. ,Item_name as Item
  14. ,Price
  15. ,Description
  16. ,In_DATE
  17. FROM ItemMasters
  18. ORDER BY Item_Code DESC

Distinct —— distinct关键字可以过滤重复的数据记录。

  1. Select * FROM ItemMasters
  2. --Distinct -> To avoid the Duplicate records we use the distinct in select statement
  3. -- for example in this table we can see here we have the duplicate record 'Chiken Burger'
  4. -- but with different Item_Code when i use the below select statement see what happen
  5. Select Item_name as Item
  6. ,Price
  7. ,Description
  8. ,IN_USR_ID
  9. FROM ItemMasters
  10. -- here we can see the Row No 3 and 5 have the duplicate record to avoid this we use the distinct Keyword in select statement.
  11. select Distinct Item_name as Item
  12. ,Price
  13. ,Description
  14. ,IN_USR_ID
  15. FROM ItemMasters

6、Where子句

Where子句在SQL Select查询语句中非常重要,为什么要使用where子句?什么时候使用where子句?where子句是利用一些条件来过滤数据结果集。

下面我们从10000条数据记录中查询Order_No为某个值或者某个区间的数据记录,另外还有其他的条件。

  1. Select * from ItemMasters
  2. Select * from OrderDetails
  3. --Where -> To display the data with certain conditions
  4. -- Now below example which will display all the records which has Item_Name='Coke'
  5. select * FROM ItemMasters WHERE ITEM_NAME='COKE'
  6. -- If we want display all the records Iten_Name which Starts with 'C' then we use Like in where clause.
  7. SELECT * FROM ItemMasters WHERE ITEM_NAME Like 'C%'
  8. --> here we display the ItemMasters where the price will be greater then or equal to 40.
  9. --> to use more then one condition we can Use And or Or operator.
  10. --If we want to check the data between to date range then we can use Between Operator in Where Clause.
  11. select Item_name as Item
  12. ,Price
  13. ,Description
  14. ,IN_USR_ID
  15. FROM ItemMasters
  16. WHERE
  17. ITEM_NAME Like 'C%'
  18. AND
  19. price >=40
  20. --> here we display the OrderDetails where the Qty will be greater 3
  21. Select * FROM OrderDetails WHERE qty>3

Where – In 子句

  1. -- In clause -> used to display the data which is in the condition
  2. select *
  3. FROM ItemMasters
  4. WHERE
  5. Item_name IN ('Coffee','Chiken Burger')
  6. -- In clause with Order By - Here we display the in descending order.
  7. select *
  8. FROM ItemMasters
  9. WHERE
  10. Item_name IN ('Coffee','Chiken Burger')
  11. ORDER BY Item_Code Desc

Where – Between子句

  1. -- between -> Now if we want to display the data between to date range then we use betweeen keyword
  2. select * FROM ItemMasters
  3. select * FROM ItemMasters
  4. WHERE
  5. In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'
  6. select * FROM ItemMasters
  7. WHERE
  8. ITEM_NAME Like 'C%'
  9. AND
  10. In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'

查询某个条件区间的数据,我们常常使用between子句。

7、Group By 子句

Group By子句可以对查询的结果集按指定字段分组:

  1. --Group By -> To display the data with group result.Here we can see we display all the AQggregate result by Item Name
  2. Select ITEM_NAME,Count(*) TotalRows,AVG(Price) AVGPrice
  3. ,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) PriceTotal
  4. FROM
  5. ItemMasters
  6. GROUP BY ITEM_NAME
  7. -- Here this group by will combine all the same Order_No result and make the total or each order_NO
  8. Select Order_NO,Sum(QTy) as TotalQTY
  9. FROM OrderDetails
  10. where qty>=2
  11. GROUP BY Order_NO
  12. -- Here the Total will be created by order_No and Item_Code
  13. Select Order_NO,Item_Code,Sum(QTy) as TotalQTY
  14. FROM OrderDetails
  15. where qty>=2
  16. GROUP BY Order_NO,Item_Code
  17. Order By Order_NO Desc,Item_Code

Group By & Having 子句

  1. --Group By Clause -- here this will display all the Order_no
  2. Select Order_NO,Sum(QTy) as TotalQTY
  3. FROM OrderDetails
  4. GROUP BY Order_NO
  5. -- Having Clause-- This will avoid the the sum(qty) less then 4
  6. Select Order_NO,Sum(QTy) as TotalQTY
  7. FROM OrderDetails
  8. GROUP BY Order_NO
  9. HAVING Sum(QTy) >4

8、子查询

子查询一般出现在where内连接查询和嵌套查询中,select、update和delete语句中均可以使用。

  1. --Sub Query -- Here we used the Sub query in where clause to get all the Item_Code where the price>40 now this sub
  2. --query reslut we used in our main query to filter all the records which Item_code from Subquery result
  3. SELECT * FROM ItemMasters
  4. WHERE Item_Code IN
  5. (SELECT Item_Code FROM ItemMasters WHERE price > 40)
  6. -- Sub Query with Insert Statement
  7. INSERT INTO ItemMasters ([Item_Code] ,[Item_Name],[Price],[TAX1],[Discount],[Description],[IN_DATE]
  8. ,[IN_USR_ID],[UP_DATE] ,[UP_USR_ID])
  9. Select 'Item006'
  10. ,Item_Name,Price+4,TAX1,Discount,Description
  11. ,GetDate(),'SHANU',GetDate(),'SHANU'
  12. from ItemMasters
  13. where Item_code='Item002'
  14. --After insert we can see the result as
  15. Select * from ItemMasters

9、连接查询

到目前为止我们接触了不少单表的查询语句,现在我们来使用连接查询获取多个表的数据。

简单的join语句:

  1. --Now we have used the simple join with out any condition this will display all the
  2. -- records with duplicate data to avaoid this we see our next example with condition
  3. SELECT * FROM Ordermasters,OrderDetails
  4. -- Simple Join with Condition now here we can see the duplicate records now has been avoided by using the where checing with both table primaryKey field
  5. SELECT *
  6. FROM
  7. Ordermasters as M, OrderDetails as D
  8. where M.Order_NO=D.Order_NO
  9. and M.Order_NO='Ord_001'
  10. -- Now to make more better understanding we need to select the need fields from both
  11. --table insted of displaying all column.
  12. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,Item_code,Notes,Qty
  13. FROM
  14. Ordermasters as M, OrderDetails as D
  15. where M.Order_NO=D.Order_NO
  16. -- Now lets Join 3 table
  17. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,
  18. I.Price*D.Qty as TotalPrice
  19. FROM
  20. Ordermasters as M, OrderDetails as D,ItemMasters as I
  21. where
  22. M.Order_NO=D.Order_NO AND D.Item_Code=I.Item_Code

Inner Join,Left Outer Join,Right Outer Join and Full outer Join

下面是各种类型的连接查询代码:

  1. --INNER JOIN
  2. --This will display the records which in both table Satisfy here i have used Like in where class which display the
  3. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  4. FROM
  5. Ordermasters as M Inner JOIN OrderDetails as D
  6. ON M.Order_NO=D.Order_NO
  7. INNER JOIN ItemMasters as I
  8. ON D.Item_Code=I.Item_Code
  9. WHERE
  10. M.Table_ID like 'T%'
  11. --LEFT OUTER JOIN
  12. --This will display the records which Left side table Satisfy
  13. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  14. FROM
  15. Ordermasters as M LEFT OUTER JOIN OrderDetails as D
  16. ON M.Order_NO=D.Order_NO
  17. LEFT OUTER JOIN ItemMasters as I
  18. ON D.Item_Code=I.Item_Code
  19. WHERE
  20. M.Table_ID like 'T%'
  21. --RIGHT OUTER JOIN
  22. --This will display the records which Left side table Satisfy
  23. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  24. FROM
  25. Ordermasters as M RIGHT OUTER JOIN OrderDetails as D
  26. ON M.Order_NO=D.Order_NO
  27. RIGHT OUTER JOIN ItemMasters as I
  28. ON D.Item_Code=I.Item_Code
  29. WHERE
  30. M.Table_ID like 'T%'
  31. --FULL OUTER JOIN
  32. --This will display the records which Left side table Satisfy
  33. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  34. FROM
  35. Ordermasters as M FULL OUTER JOIN OrderDetails as D
  36. ON M.Order_NO=D.Order_NO
  37. FULL OUTER JOIN ItemMasters as I
  38. ON D.Item_Code=I.Item_Code
  39. WHERE
  40. M.Table_ID like 'T%'

10、Union合并查询

Union查询可以把多张表的数据合并起来,Union只会把唯一的数据查询出来,而Union ALL则会把重复的数据也查询出来。

  1. Select column1,Colum2 from Table1
  2. Union
  3. Select Column1,Column2 from Table2
  4. Select column1,Colum2 from Table1
  5. Union All
  6. Select Column1,Column2 from Table2

具体的例子如下:

  1. --Select with different where condition which display the result as 2 Table result
  2. select Item_Code,Item_Name,Price,Description FROM ItemMasters where price <=44
  3. select Item_Code,Item_Name,Price,Description FROM ItemMasters where price >44
  4. -- Union with same table but with different where condition now which result as one table which combine both the result.
  5. select Item_Code,Item_Name,Price,Description FROM ItemMasters where price <=44
  6. UNION
  7. select Item_Code,Item_Name,Price,Description FROM ItemMasters where price >44
  8. -- Union ALL with Join sample
  9. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  10. FROM
  11. Ordermasters as M (NOLOCK) Inner JOIN OrderDetails as D
  12. ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
  13. ON D.Item_Code=I.Item_Code WHERE I.Price <=44
  14. Union ALL
  15. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
  16. FROM
  17. Ordermasters as M (NOLOCK) Inner JOIN OrderDetails as D
  18. ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
  19. ON D.Item_Code=I.Item_Code WHERE I.Price>44

11、公用表表达式(CTE)——With语句

CTE可以看作是一个临时的结果集,可以在接下来的一个SELECT,INSERT,UPDATE,DELETE,MERGE语句中被多次引用。使用公用表达式可以让语句更加清晰简练。

  1. declare @sDate datetime,
  2. @eDate datetime;
  3. select @sDate = getdate()-5,
  4. @eDate = getdate()+16;
  5. --select @sDate StartDate,@eDate EndDate
  6. ;with cte as
  7. (
  8. select @sDate StartDate,'W'+convert(varchar(2),
  9. DATEPART( wk, @sDate))+'('+convert(varchar(2),@sDate,106)+')' as 'SDT'
  10. union all
  11. select dateadd(DAY, 1, StartDate) ,
  12. 'W'+convert(varchar(2),DATEPART( wk, StartDate))+'('+convert(varchar(2),
  13. dateadd(DAY, 1, StartDate),106)+')' as 'SDT'
  14. FROM cte
  15. WHERE dateadd(DAY, 1, StartDate)<= @eDate
  16. )
  17. select * from cte
  18. option (maxrecursion 0)

12、视图

很多人对视图View感到很沮丧,因为它看起来跟select语句没什么区别。在视图中我们同样可以使用select查询语句,但是视图对我们来说依然非常重要。

假设我们要联合查询4张表中的20几个字段,那么这个select查询语句会非常复杂。但是这样的语句我们在很多地方都需要用到,如果将它编写成视图,那么使用起来会方便很多。利用视图查询有以下几个优点:

  • 一定程度上提高查询速度
  • 可以对一些字段根据不同的权限进行屏蔽,因此提高了安全性
  • 对多表的连接查询会非常方便

下面是一个视图的代码例子:

  1. CREATE
  2. VIEW viewname
  3. AS
  4. Select ColumNames from yourTable
  5. Example :
  6. -- Here we create view for our Union ALL example
  7. Create
  8. VIEW myUnionVIEW
  9. AS
  10. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,
  11. I.Price*D.Qty as TotalPrice
  12. FROM
  13. Ordermasters as M Inner JOIN OrderDetails as D
  14. ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
  15. ON D.Item_Code=I.Item_Code WHERE I.Price <=44
  16. Union ALL
  17. SELECT M.order_NO,M.Table_ID,D.Order_detail_no,I.Item_Name,D.Notes,D.Qty,I.Price,
  18. I.Price*D.Qty as TotalPrice
  19. FROM
  20. Ordermasters as M Inner JOIN OrderDetails as D
  21. ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
  22. ON D.Item_Code=I.Item_Code WHERE I.Price>44
  23. -- View Select query
  24. Select * from myUnionVIEW
  25. -- We can also use the View to display with where condition and with selected fields
  26. Select order_Detail_NO,Table_ID,Item_Name,Price from myUnionVIEW where price >40

13、Pivot行转列

Pivot可以帮助你实现数据行转换成数据列,具体用法如下:

  1. -- Simple Pivot Example
  2. SELECT * FROM ItemMasters
  3. PIVOT(SUM(Price)
  4. FOR ITEM_NAME IN ([Chiken Burger], Coffee,Coke)) AS PVTTable
  5. -- Pivot with detail example
  6. SELECT *
  7. FROM (
  8. SELECT
  9. ITEM_NAME,
  10. price as TotAmount
  11. FROM ItemMasters
  12. ) as s
  13. PIVOT
  14. (
  15. SUM(TotAmount)
  16. FOR [ITEM_NAME] IN ([Chiken Burger], [Coffee],[Coke])
  17. )AS MyPivot

14、存储过程

我经常看到有人提问如何在SQL Server中编写多条查询的SQL语句,然后将它们使用到C#程序中去。存储过程就可以完成这样的功能,存储过程可以将多个SQL查询聚集在一起,创建存储过程的基本结构是这样的:

  1. CREATE PROCEDURE [ProcedureName]
  2. AS
  3. BEGIN
  4. -- Select or Update or Insert query.
  5. END
  6. To execute SP we use
  7. exec ProcedureName

创建一个没有参数的存储过程:

  1. -- =============================================
  2. -- Author : Shanu
  3. -- Create date : 2014-09-15
  4. -- Description : To Display Pivot Data
  5. -- Latest
  6. -- Modifier : Shanu
  7. -- Modify date : 2014-09-15
  8. -- =============================================
  9. -- exec USP_SelectPivot
  10. -- =============================================
  11. Create PROCEDURE [dbo].[USP_SelectPivot]
  12. AS
  13. BEGIN
  14. DECLARE @MyColumns AS NVARCHAR(MAX),
  15. @SQLquery AS NVARCHAR(MAX)
  16. -- here first we get all the ItemName which should be display in Columns we use this in our necxt pivot query
  17. select @MyColumns = STUFF((SELECT ',' + QUOTENAME(Item_NAME)
  18. FROM ItemMasters
  19. GROUP BY Item_NAME
  20. ORDER BY Item_NAME
  21. FOR XML PATH(''), TYPE
  22. ).value('.', 'NVARCHAR(MAX)')
  23. ,1,1,'')
  24. -- here we use the above all Item name to disoplay its price as column and row display
  25. set @SQLquery = N'SELECT ' + @MyColumns + N' from
  26. (
  27. SELECT
  28. ITEM_NAME,
  29. price as TotAmount
  30. FROM ItemMasters
  31. ) x
  32. pivot
  33. (
  34. SUM(TotAmount)
  35. for ITEM_NAME in (' + @MyColumns + N')
  36. ) p '
  37. exec sp_executesql @SQLquery;
  38. RETURN
  39. END

15、函数Function

之前我们介绍了MAX(),SUM(), GetDate()等最基本的SQL函数,现在我们来看看如何创建自定义SQL函数。创建函数的格式如下:

  1. Create Function functionName
  2. As
  3. Begin
  4. END

下面是一个简单的函数示例:                                                 

  1. Alter FUNCTION [dbo].[ufnSelectitemMaster]()
  2. RETURNS int
  3. AS
  4. -- Returns total Row count of Item Master.
  5. BEGIN
  6. DECLARE @RowsCount AS int;
  7. Select @RowsCount= count(*)+1 from ItemMasters
  8. RETURN @RowsCount;
  9. END
  10. -- to View Function we use select and fucntion Name
  11. select [dbo].[ufnSelectitemMaster]()

下面的一个函数可以实现从给定的日期中得到当前月的最后一天:

  1. ALTER FUNCTION [dbo].[ufn_LastDayOfMonth]
  2. (
  3. @DATE NVARCHAR(10)
  4. )
  5. RETURNS NVARCHAR(10)
  6. AS
  7. BEGIN
  8. RETURN CONVERT(NVARCHAR(10), DATEADD(D, -1, DATEADD(M, 1, CAST(SUBSTRING(@DATE,1,7) + '-01' AS DATETIME))), 120)
  9. END
  10. SELECT dbo.ufn_LastDayOfMonth('2014-09-01')AS LastDay

以上就是适合初学者学习的基础SQL查询语句,希望对大家学习SQL查询语句有所帮助。

您可能感兴趣的文章:

  • SQL查询语句精华使用简要
  • SQl 跨服务器查询语句
  • SQL查询语句通配符与ACCESS模糊查询like的解决方法
  • SQL Server SQL高级查询语句小结
  • T-SQL 查询语句的执行顺序解析
  • 基于SQL中的数据查询语句汇总
  • oracle常用sql查询语句部分集合(图文)
  • MySql日期查询语句详解
  • mysql分页原理和高效率的mysql分页查询语句
  • Android中的SQL查询语句LIKE绑定参数问题解决办法(sqlite数据库)

人气教程排行