rush:sql;">
CREATE TABLE [dbo].[Itemmasters](
[Item_Code] [varchar](20) NOT NULL,[Item_Name] [varchar](100) NOT NULL,[Price] Int NOT NULL,[TAX1] Int NOT NULL,[discount] Int NOT NULL,[Description] [varchar](200) NOT NULL,[IN_DATE] [datetime] NOT NULL,[IN_USR_ID] [varchar](20) NOT NULL,[UP_DATE] [datetime] NOT NULL,[UP_USR_ID] [varchar](20) NOT NULL,CONSTRAINT [PK_Itemmasters] PRIMARY KEY CLUSTERED
(
[Item_Code] ASC
)WITH (PAD_INDEX = OFF,STATISTICS_norECOmpuTE = OFF,IGnorE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
向Item Master表插入数据:
<div class="jb51code">
<pre class="brush:sql;">
INSERT INTO [Itemmasters] ([Item_Code],[Item_Name],[Price],[TAX1],[discount],[Description],[IN_DATE],[IN_USR_ID],[UP_DATE],[UP_USR_ID])
VALUES
('Item001','Coke',55,1,'Coke which need to be cold',GETDATE(),'SHANU','SHANU')
INSERT INTO [Itemmasters] ([Item_Code],[UP_USR_ID])
VALUES
('Item002','Coffee',40,2,'Coffe Might be Hot or Cold user choice',[UP_USR_ID])
VALUES
('Item003','Chiken Burger',125,5,'Spicy',[UP_USR_ID])
VALUES
('Item004','Potato Fry',15,'No Comments','SHANU')
创建Order Master表:
rush:sql;">
CREATE TABLE [dbo].[OrderMasters](
[Order_No] [varchar](20) NOT NULL,[Table_ID] [varchar](20) NOT NULL,CONSTRAINT [PK_OrderMasters] PRIMARY KEY CLUSTERED
(
[Order_No] ASC
)WITH (PAD_INDEX = OFF,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
向Order Master表插入数据:
rush:sql;">
INSERT INTO [OrderMasters]
([Order_No],[Table_ID],[UP_USR_ID])
VALUES
('Ord_001','T1','','SHANU')
INSERT INTO [OrderMasters]
([Order_No],[UP_USR_ID])
VALUES
('Ord_002','T2','Mak','MAK')
INSERT INTO [OrderMasters]
([Order_No],[UP_USR_ID])
VALUES
('Ord_003','T3','RAJ','RAJ')
创建Order Detail表:
<div class="jb51code">
<pre class="brush:sql;">
CREATE TABLE [dbo].[OrderDetails](
[Order_Detail_No] varchar NOT NULL,[Order_No] varchar CONSTRAINT fk_OrderMasters FOREIGN KEY REFERENCES OrderMasters(Order_No),[Item_Code] varchar CONSTRAINT fk_Itemmasters FOREIGN KEY REFERENCES Itemmasters(Item_Code),[Notes] varchar NOT NULL,[QTY] INT NOT NULL,CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED
(
[Order_Detail_No] ASC
)WITH (PAD_INDEX = OFF,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--Now let’s insert the 3 items for the above Order No 'Ord_001'.
INSERT INTO [OrderDetails]
([Order_Detail_No],[Order_No],[Item_Code],[Notes],[QTY],[UP_USR_ID])
VALUES
('OR_Dt_001','Ord_001','Item001','Need very Cold',3,'SHANU')
INSERT INTO [OrderDetails]
([Order_Detail_No],[UP_USR_ID])
VALUES
('OR_Dt_002','Item004','very Hot ',[UP_USR_ID])
VALUES
('OR_Dt_003','Item003','Very Spicy',4,'SHANU')
向Order Detail表插入数据:
rush:sql;">
INSERT INTO [OrderDetails]
([Order_Detail_No],[UP_USR_ID])
VALUES
('OR_Dt_004','Ord_002','Item002','Need very Hot',[UP_USR_ID])
VALUES
('OR_Dt_005',[UP_USR_ID])
VALUES
('OR_Dt_006','Ord_003','SHANU')
rush:sql;">
SELECT 'My Name Is SYED SHANU'
-- With Column Name using 'AS'
SELECT 'My Name Is SYED SHANU' as 'MY NAME'
-- With more then the one Column
SELECT 'My Name' as 'Column1','Is' as 'Column2','SYED SHANU' as 'Column3'
rush:sql;">
-- To display all the columns from the table we use * operator in select Statement.
Select * from Itemmasters
-- If we need to select only few fields from a table we can use the Column Name in Select Statement.
Select Item_Code,Item_name as Item,Price,Description,In_DATE
FROM
Itemmasters
returns the Total no of records from table,AVG() returns the Average Value from Colum,MAX() Returns MaX Value from Column
--,MIN() returns Min Value from Column,SUM() sum of total from Column
Select Count(*) TotalRows,AVG(Price) AVGPrice,MAX(Price) MAXPrice,MIN(Price) MinPrice,Sum(price) Pricetotal
FROM Itemmasters
-- Scalar
-- UCASE() -> Convert to Upper Case,LCASE() -> Convert to Lower Case,-- SUBSTRING() ->display selected char from column ->SUBSTRING(ColumnName,StartIndex,LenthofChartodisplay)
--,LEN() -> lenth of column date,-- ROUND() -> Which will round the value
SELECT UPPER(Item_NAME) Uppers,LOWER(Item_NAME) Lowers,SUBSTRING(Item_NAME,3) MidValue,LEN(Item_NAME) Lenths,LEN(Item_NAME)) MidValuewithLenFunction,ROUND(Price,0) as Rounded
FROM Itemmasters
to display the Current Date and Time
-- Format() -> used to display our date in our requested format
Select GETDATE() CurrentDateTime,FORMAT(GETDATE(),'yyyy-MM-dd') AS DateFormats,'HH-mm-ss')TimeFormats,CONVERT(VARCHAR(10),10) Converts1,CONVERT(VARCHAR(24),113),CONVERT(NVARCHAR,getdate(),106) Converts2,-- here we used Convert Function
REPLACE(convert(NVARCHAR,106),' ','/') Formats-- Here we used replace and --convert functions.
--first we convert the date to nvarchar and then we replace the '' with '/'
<div class="jb51code">
<pre class="brush:sql;">
--Datepart DATEPART(dateparttype,yourDate)
SELECT DATEPART(yyyy,getdate()) AS YEARs,DATEPART(mm,getdate()) AS MONTHS,DATEPART(dd,getdate()) AS Days,DATEPART(week,getdate()) AS weeks,DATEPART(hour,getdate()) AS hours
--Days Add to add or subdtract date from a selected date.
SELECT GetDate()CurrentDate,DATEADD(day,12,getdate()) AS AddDays,-4,getdate()) AS FourDaysBeforeDate
-- DATEDIFF() -> to display the Days between 2 dates
select DATEDIFF(year,'2003-08-05',getdate()) yearDifferance,DATEDIFF(day,-24,getdate()),getdate()) daysDifferent,DATEDIFF(month,DATEADD(Month,6,getdate())) MonthDifferance
First display top 2 Records
Select TOP 2 Item_Code,In_DATE
FROM Itemmasters
--> to display the Last to Records we need to use the Order By Clause
-- order By to display Records in assending or desending order by the columns
Select TOP 2 Item_Code,In_DATE
FROM Itemmasters
ORDER BY Item_Code DESC
To avoid the Duplicate records we use the distinct in select statement
-- for example in this table we can see here we have the duplicate record 'Chiken Burger'
-- but with different Item_Code when i use the below select statement see what happen
Select Item_name as Item,IN_USR_ID
FROM Itemmasters
-- 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.
select distinct Item_name as Item,IN_USR_ID
FROM Itemmasters
To display the data with certain conditions
-- Now below example which will display all the records which has Item_Name='Coke'
select * FROM Itemmasters WHERE ITEM_NAME='COKE'
-- If we want display all the records Iten_Name which Starts with 'C' then we use like in where clause.
SELECT * FROM Itemmasters WHERE ITEM_NAME Like 'C%'
--> here we display the Itemmasters where the price will be greater then or equal to 40.
--> to use more then one condition we can Use And or Or operator.
--If we want to check the data between to date range then we can use Between Operator in Where Clause.
select Item_name as Item,IN_USR_ID
FROM Itemmasters
WHERE
ITEM_NAME Like 'C%'
AND
price >=40
--> here we display the OrderDetails where the Qty will be greater 3
Select * FROM OrderDetails WHERE qty>3
Where – In 子句
used to display the data which is in the condition
select *
FROM Itemmasters
WHERE
Item_name IN ('Coffee','Chiken Burger')
-- In clause with Order By - Here we display the in descending order.
select *
FROM Itemmasters
WHERE
Item_name IN ('Coffee','Chiken Burger')
ORDER BY Item_Code Desc
Where – Between子句
Now if we want to display the data between to date range then we use betweeen keyword
select * FROM Itemmasters
select * FROM Itemmasters
WHERE
In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'
select * FROM Itemmasters
WHERE
ITEM_NAME Like 'C%'
AND
In_Date BETWEEN '2014-09-22 15:59:02.853' AND '2014-09-22 15:59:02.853'
To display the data with group result.Here we can see we display all the AQggregate result by Item Name
Select ITEM_NAME,Count(*) TotalRows,Sum(price) Pricetotal
FROM
Itemmasters
GROUP BY ITEM_NAME
-- Here this group by will combine all the same Order_No result and make the total or each order_NO
Select Order_NO,Sum(QTy) as TotalQTY
FROM OrderDetails
where qty>=2
GROUP BY Order_NO
-- Here the Total will be created by order_No and Item_Code
Select Order_NO,Item_Code,Sum(QTy) as TotalQTY
FROM OrderDetails
where qty>=2
GROUP BY Order_NO,Item_Code
Order By Order_NO Desc,Item_Code
Group By & Having 子句
-- Having Clause-- This will avoid the the sum(qty) less then 4
Select Order_NO,Sum(QTy) as TotalQTY
FROM OrderDetails
GROUP BY Order_NO
HAVING Sum(QTy) >4
<div class="jb51code">
<pre class="brush:sql;">
--Sub Query -- Here we used the Sub query in where clause to get all the Item_Code where the price>40 Now this sub
--query reslut we used in our main query to filter all the records which Item_code from Subquery result
SELECT * FROM Itemmasters
WHERE Item_Code IN
(SELECT Item_Code FROM Itemmasters WHERE price > 40)
-- Sub Query with Insert Statement
INSERT INTO Itemmasters ([Item_Code],[UP_USR_ID])
Select 'Item006',Item_Name,Price+4,TAX1,discount,GetDate(),'SHANU'
from Itemmasters
where Item_code='Item002'
--After insert we can see the result as
Select * from Itemmasters
<div class="jb51code">
<pre class="brush:sql;">
--Now we have used the simple join with out any condition this will display all the
-- records with duplicate data to avaoid this we see our next example with condition
SELECT FROM Ordermasters,OrderDetails
-- 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
SELECT
FROM
Ordermasters as M,OrderDetails as D
where M.Order_NO=D.Order_NO
and M.Order_NO='Ord_001'
-- Now to make more better understanding we need to select the need fields from both
--table insted of displaying all column.
SELECT M.order_NO,M.Table_ID,D.Order_detail_no,Item_code,Notes,Qty
FROM
Ordermasters as M,OrderDetails as D
where M.Order_NO=D.Order_NO
-- Now lets Join 3 table
SELECT M.order_NO,I.Item_Name,D.Notes,D.Qty,I.Price,I.Price*D.Qty as TotalPrice
FROM
Ordermasters as M,OrderDetails as D,Itemmasters as I
where
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
<div class="jb51code">
<pre class="brush:sql;">
--INNER JOIN
--This will display the records which in both table Satisfy here i have used like in where class which display the
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M Inner JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO
INNER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code
WHERE
M.Table_ID like 'T%'
--LEFT OUTER JOIN
--This will display the records which Left side table Satisfy
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M LEFT OUTER JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO
LEFT OUTER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code
WHERE
M.Table_ID like 'T%'
--RIGHT OUTER JOIN
--This will display the records which Left side table Satisfy
SELECT M.order_NO,I.Price*D.Qty as TotalPrice
FROM
Ordermasters as M RIGHT OUTER JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO
RIGHT OUTER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code
WHERE
M.Table_ID like 'T%'
--FULL OUTER JOIN
--This will display the records which Left side table Satisfy
SELECT M.order_NO,I.Price*D.Qty as TotalPrice
FROM
Ordermasters as M FULL OUTER JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO
FULL OUTER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code
WHERE
M.Table_ID like 'T%'
<div class="jb51code">
<pre class="brush:sql;">
Select column1,Colum2 from Table1
Union
Select Column1,Column2 from Table2
Select column1,Colum2 from Table1
Union All
Select Column1,Column2 from Table2
具体的例子如下:
<div class="jb51code">
<pre class="brush:sql;">
--Select with different where condition which display the result as 2 Table result
select Item_Code,Description FROM Itemmasters where price <=44
select Item_Code,Description FROM ItemMasters where price >44
-- Union with same table but with different where condition Now which result as one table which combine both the result.
select Item_Code,Description FROM Itemmasters where price <=44
UNION
select Item_Code,Description FROM ItemMasters where price >44
-- Union ALL with Join sample
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M (NOLOCK) Inner JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO INNER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code WHERE I.Price <=44
Union ALL
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M (NOLOCK) Inner JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
ON D.Item_Code=I.Item_Code WHERE I.Price>44
select @sDate = getdate()-5,@eDate = getdate()+16;
--select @sDate StartDate,@eDate EndDate
;with cte as
(
select @sDate StartDate,'W'+convert(varchar(2),DATEPART( wk,@sDate))+'('+convert(varchar(2),@sDate,106)+')' as 'SDT'
union all
select dateadd(DAY,StartDate),StartDate))+'('+convert(varchar(2),dateadd(DAY,106)+')' as 'SDT'
FROM cte
WHERE dateadd(DAY,StartDate)<= @eDate
)
select * from cte
option (maxrecursion 0)
<div class="jb51code">
<pre class="brush:sql;">
CREATE
VIEW viewname
AS
Select ColumNames from yourTable
Example :
-- Here we create view for our Union ALL example
Create
VIEW myUnionVIEW
AS
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M Inner JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO INNER JOIN Itemmasters as I
ON D.Item_Code=I.Item_Code WHERE I.Price <=44
Union ALL
SELECT M.order_NO,I.PriceD.Qty as TotalPrice
FROM
Ordermasters as M Inner JOIN OrderDetails as D
ON M.Order_NO=D.Order_NO INNER JOIN ItemMasters as I
ON D.Item_Code=I.Item_Code WHERE I.Price>44
-- View Select query
Select * from myUnionVIEW
-- We can also use the View to display with where condition and with selected fields
Select order_Detail_NO,Table_ID,Price from myUnionVIEW where price >40
<div class="jb51code">
<pre class="brush:sql;">
-- =============================================
-- Author : Shanu
-- Create date : 2014-09-15
-- Description : To display Pivot Data
-- Latest
-- Modifier : Shanu
-- Modify date : 2014-09-15
-- =============================================
-- exec USP_SelectPivot
-- =============================================
Create PROCEDURE [dbo].[USP_SelectPivot]
AS
BEGIN
DECLARE @MyColumns AS NVARCHAR(MAX),@sqlquery AS NVARCHAR(MAX)
-- here first we get all the ItemName which should be display in Columns we use this in our necxt pivot query
select @MyColumns = STUFF((SELECT ',' + QUOTENAME(Item_NAME)
FROM Itemmasters
GROUP BY Item_NAME
ORDER BY Item_NAME
FOR XML PATH(''),TYPE
).value('.','NVARCHAR(MAX)'),'')
-- here we use the above all Item name to disoplay its price as column and row display
set @sqlquery = N'SELECT ' + @MyColumns + N' from
(
SELECT
ITEM_NAME,price as TotAmount
FROM Itemmasters
) x
pivot
(
SUM(TotAmount)
for ITEM_NAME in (' + @MyColumns + N')
) p '
rush:sql;">
ALTER FUNCTION [dbo].[ufn_LastDayOfMonth]
(
@DATE NVARCHAR(10)
)
RETURNS NVARCHAR(10)
AS
BEGIN
RETURN CONVERT(NVARCHAR(10),DATEADD(D,-1,DATEADD(M,CAST(SUBSTRING(@DATE,7) + '-01' AS DATETIME))),120)
END
SELECT dbo.ufn_LastDayOfMonth('2014-09-01')AS LastDay