SlideShare a Scribd company logo
1 of 12
Transact-SQL ProjectSQL Server 2008 Management Studio SetFocus Business Intelligence Master’s Program Jeff Jacob, MBA P: (312) 772-6142 E1: Jeffrey.K.Jacob@gmail.com E2: Jeffrey.Jacob@SetFocus.com
Query 1 – Wildcard Search(CI Collation)A summary of order detail-linetotal by product – for products that contain ‘Washer’ in their name; 2003 data only. USE [AdventureWorks2008]; GO SELECT Name, SUM(LineTotal) AS TotDollars     FROM Purchasing.PurchaseOrderDetail pod           INNER JOIN Purchasing.PurchaseOrderHeader poh           ON poh.PurchaseOrderID = pod.PurchaseOrderID           INNER JOIN Production.Productprd           ON prd.ProductID  = pod.ProductID                WHERE Name LIKE '%washer%‘                AND YEAR(OrderDate) = 2003                      GROUP BY Name 	ORDER BY TotDollars DESC 2
Query 2 – HAVING clauseA count of orders by product subcategory– for those with at least 10 orders; 2004 data only. USE [AdventureWorks2008]; GO SELECT psc.Name, COUNT(poh.PurchaseOrderID) AS NumOrders      FROM Purchasing.PurchaseOrderHeader poh      INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.PurchaseOrderID = poh.PurchaseOrderID      INNER JOIN Production.ProductprdON prd.ProductID = pod.ProductID      INNER JOIN Production.ProductSubcategorypscON prd.ProductSubcategoryID= psc.ProductSubcategoryID           WHERE YEAR(OrderDate) = 2004 GROUP BY psc.Name      HAVING COUNT(poh.PurchaseOrderID) >=10 	          ORDER BY NumOrdersDESC 3
Query 3 – Correlated Subquery of exclusionA list of the vendors for which there were no orders in 2003. USE [AdventureWorks2008]; GO SELECT Name      FROM Purchasing.Vendor           WHERE NOT EXISTS 					(SELECT * FROM Purchasing.PurchaseOrderHeader        WHERE YEAR(OrderDate) = 2003 	       AND Vendor.BusinessEntityID =  PurchaseOrderHeader.VendorID) 4
Query 4 – OUTER JOIN syntaxA summary of freight charges by shipper for all shippers; Q1 of 2003 data only. USE [AdventureWorks2008]; GO SELECT Name, SUM(Freight) AS TotFreight     FROM Purchasing.ShipMethodsm      LEFT OUTER JOIN Purchasing.PurchaseOrderHeader poh      ON poh.ShipMethodID = sm.ShipMethodID      AND YEAR(OrderDate) = 2003       AND DATEPART(q,OrderDate) = 1           GROUP BY Name                ORDER BY TotFreightDESC 5
Query 5 – Chronological Sort A summary of total charges due by specific employee national ID numbers, sorted chronologically within each employee; 2003 data only. USE [AdventureWorks2008]; GO SELECT NationalIDNumber, LoginID, DATENAME(MONTH, OrderDate) AS  MonthName, YEAR(OrderDate) as YearName, SUM(TotalDue) AS  SumTotalDue      FROM Purchasing.PurchaseOrderHeaderpoh      INNER JOIN HumanResources.Employeeemp ON emp.BusinessEntityID 			                    = poh.EmployeeID           WHERE NationalIDNumber IN (792847334, 407505660, 482810518,  			         466142721, 367453993)           AND YEAR(OrderDate) = 2003                GROUP BY NationalIDNumber, LoginID, DATENAME(MONTH,  OrderDate),DATEPART(MONTH, OrderDate) ,YEAR(OrderDate)                     ORDER BY NationalIDNumber, DATEPART(MONTH, OrderDate)  6
Query 6 – UNION queryA union of two view-based queries to obtain  contact information of both vendors and employees, sorted first by postal code and then by name. USE [AdventureWorks2008]; GO SELECT 'Vendor' AS RecordType, Name, AddressLine1, ISNULL(AddressLine2,'') AS AddressLine2, City,  StateProvinceName, PostalCode      FROM Purchasing.vVendorWithAddresses UNIONALL SELECT 'Employee' AS RecordType, LastName + ', ‘ + FirstName + ' ‘ + ISNULL(MiddleName, ''), AddressLine1, ISNULL (AddressLine2,''), City, StateProvinceName, PostalCode      FROM HumanResources.vEmployee           ORDER BY PostalCode, Name 7
Query 7 – Stored ProcedureA stored procedure designed to summarize freight, tax amount and subtotal  by  vendor and shipper based on supplied account number and date parameters; with example usage. USE [AdventureWorks2008]; GO CREATEPROCEDUREdbo.usp_GetVendorOrders @AcctNonvarchar(15), @StartDatedatetime, @EndDatedatetime AS SET NOCOUNT ON; SELECT Ven.Name AS VendorName, Ship.Name AS ShipperName, SUM(Freight) as TotFreight, SUM(TaxAmt) AS TotTaxAmt, SUM(SubTotal) AS TotSubTot      FROM Purchasing.PurchaseOrderHeaderpoh      JOIN Purchasing.VendorVen ON poh.VendorID = Ven.BusinessEntityID      JOIN Purchasing.ShipMethod ship ON ship.ShipMethodID = poh.ShipMethodID           WHERE OrderDate >= @StartDate and OrderDate <= @EndDate           AND AccountNumber = @AcctNo 	GROUP BY Ven.Name, Ship.Name GO EXEC dbo.usp_GetVendorOrders N'ADVANCED0001', '1-1-2003', '12-31-2003' 8
Query 8 – PIVOT tableA pivot table of shipper data for total charges due in 2003 summarized by Saturdays with a summary rank of the Top 5 based on grand total. ;WITH ShipperTotDueCTE AS ( SELECT sm.Name,  dbo.SatDatesConverter(OrderDate) AS WeekEnding, TotalDue      FROM Purchasing.PurchaseOrderHeaderpoh      INNER JOIN Purchasing.ShipMethodsm ON sm.ShipMethodID  = poh.ShipMethodID           WHERE YEAR(OrderDate) = 2003           ), SumByWeekEndCTE AS  ( SELECT Name AS Shipper, WeekEnding, SUM(TotalDue) AS GrandTot      FROM ShipperTotDueCTE           GROUP BY Name, WeekEnding	), PivCTE AS    ( SELECT WeekEnding, [XRQ - Truck Ground] AS XRQ, [Cargo Transport 5] AS Cargo,  [Overnight J-Fast] AS Overnight, [ZY - Express] AS ZY, [Overseas - Deluxe] AS Overseas, ISNULL([XRQ - Truck Ground],0) + ISNULL([Cargo Transport 5],0) + ISNULL([Overnight J-Fast],0) + ISNULL([ZY - Express],0) + ISNULL([Overseas - Deluxe],0)  AS GrandTot      FROM SumByWeekEndCTE PIVOT (  SUM(GrandTot) FOR Shipper IN ([XRQ - Truck Ground],[Cargo Transport 5], [Overnight J-Fast],[ZY - Express], [Overseas - Deluxe])	   ) AS P  ) SELECT TOP 5 WeekEnding, GrandTot, RANK() OVER (ORDER BY GrandTot DESC)  AS WeekRank, XRQ, ZY, Overseas, Overnight, Cargo      FROM PivCTE ORDER BY WeekRank; USE [AdventureWorks2008]; GO CREATEFUNCTION [dbo].[SatDatesConverter] (@orderdatedatetime) RETURNS datetime AS BEGIN DECLARE @satdatedatetime SET @satdate =  (SELECT DateAdd(d, 7- datepart(dw, @OrderDate), @OrderDate))  RETURN @satdate END; GO 9
USE [AdventureWorks2008]; GO CREATEPROCEDUREdbo.usp_VendorProductRank @TopNint, @TopYint, @BeginDatedatetime, @EndDatedatetime AS  SET NOCOUNT ON; ;WITH VendCTE AS ( SELECT Ven.BusinessEntityID, Ven.Name AS VendorName, SUM(TotalDue) AS TotalDue, DENSE_RANK () OVER (ORDER BY  SUM(TotalDue) DESC ) AS VendorRank      FROM Purchasing.VendorVen      INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON poh.VendorID = Ven.BusinessEntityID           WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate                GROUP BY BusinessEntityID, Name ), ProdCTEAS ( SELECT Ven.BusinessEntityID, prd.Name AS ProductName, SUM(LineTotal) AS ProductTotalDue, DENSE_RANK() OVER (PARTITION BY Ven.BusinessEntityID ORDER BY SUM(LineTotal) DESC) AS ProductRank FROM Purchasing.Vendorven INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON poh.VendorID = ven.BusinessEntityID INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.PurchaseOrderID = poh.PurchaseOrderID INNER JOIN Production.Productprd ON prd.ProductID = pod.ProductID WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate GROUP BY Ven.BusinessEntityID, prd.Name) SELECT VC.VendorName, VC.VendorRank, CAST(VC.TotalDue AS NUMERIC (14,2)) AS TotalDue, PC.ProductName, PC.ProductRank, CAST(PC.ProductTotalDue AS NUMERIC (14,2) ) AS ProductTotalDue FROM VendCTE VC INNER JOIN ProdCTE PC ON PC.BusinessEntityID = VC.BusinessEntityID WHERE VendorRank <= @TopN AND ProductRank <= @TopY ORDER BY VendorRank, ProductRank GO EXECdbo.usp_VendorProductRank    5,5,'2003-01-01', '2004-06-30' Query 9 – SP, CTE-only approachA stored procedure for a ranking of Top N vendors by Total Due amount; and, within each vendor, the Top N products based on Line Total (Due) for specified start/end dates.   10
Query 9 – SP, CTE/Function approach A stored procedure for a ranking of Top N vendors by Total Due amount; and, within each vendor, the Top N products based on Line Total (Due) for specified start/end dates.   CREATEPROCEDURE dbo.usp_TestProc1 @TopNint, @TopYint, @BeginDatedatetime, @EndDatedatetime AS SET NOCOUNT ON; ;WITHxCTEas (     SELECT TOP (@TopN) WITH TIES poh.VendorID, ven.Name AS VendorName, SUM(poh.TotalDue) AS TotalDue, DENSE_RANK() OVER (ORDER BY SUM(poh.TotalDue) DESC) AS VendorRank           FROM Purchasing.PurchaseOrderHeaderpoh            INNER JOIN Purchasing.Vendorven ON ven.BusinessEntityID = poh.VendorID               WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate                     GROUP BY poh.VendorID, ven.Name            )  SELECT xCTE.VendorName, xCTE.VendorRank, CAST(xCTE.TotalDue AS NUMERIC (14,2)) AS TotalDue, C.ProductName, C.ProductRank, CAST(C.ProductLineTotal AS NUMERIC (14,2) ) AS ProductLineTotal     FROM xCTE     CROSS APPLY dbo.TestFn1 (xCTE.VendorID, @TopY, @BeginDate, @EndDate) AS C   GO EXEC dbo.usp_TestProc1    5, 5,'2003-01-01', '2004-06-30' USE [AdventureWorks2008]; GO CREATEFUNCTION dbo.TestFn1 (@VendorIDint, @TopYint, @StartDatedatetime, @EndingDatedatetime) RETURNS TABLE AS  RETURN    SELECT TOP (@TopY) WITH TIES poh.vendorid, prd.Name AS ProductName,       DENSE_RANK() OVER (PARTITION BY poh.vendorID ORDER BY      SUM(pod.LineTotal) DESC) AS ProductRank,      SUM(pod.LineTotal) AS ProductLineTotal                 FROM Production.Productprd                 INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.productid = prd.productid                 INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON pod.PurchaseOrderid = poh.purchaseorderid                      WHERE poh.VendorID = @VendorID AND OrderDate >= @StartDate       AND OrderDate <= @EndingDate                           GROUP BY poh.vendorID, prd.Name                                ORDER BY ProductLineTotal DESC GO 11
Query 10 – Effective (‘As of’) Dates: Scalar UDF A function which provides the commensurate standardproductcost based on a specified productIDnumber and a desired  ‘effective date.’ Example included. USE [AdventureWorks2008]; GO CREATEFUNCTIONdbo.ProdStdCostAsOfDate (@ProductIDint, @AsOfDatedatetime ) RETURNS MONEY AS BEGIN DECLARE @StndCost money SET @StndCost =       ( SELECT StandardCost           FROM Production.ProductCostHistorypch                WHERE ProductID = @ProductID                AND StartDate =                                 (SELECT MAX(StartDate)                                       FROM Production.ProductCostHistory 	    WHERE ProductID = @Productid 	     AND StartDate <= @AsOfDate    )     ) RETURN @StndCost END; GO ;WITH ProdStdCostCTE AS ( SELECT ProductNumber, Name,   CAST( dbo.ProdStdCostAsOfDate (Product.ProductID, '2002-01-01') AS NUMERIC (14,2) ) AS StandardCost FROM Production.Product INNER JOIN Production.ProductCostHistorypch ON pch.ProductID = Product.ProductID  ) SELECT ProductNumber, Name, StandardCost FROM ProdStdCostCTE  WHERE StandardCost IS NOT NULL   AND StandardCost > 700 ORDER BY StandardCost DESC; 12

More Related Content

What's hot

The Ring programming language version 1.5.4 book - Part 45 of 185
The Ring programming language version 1.5.4 book - Part 45 of 185The Ring programming language version 1.5.4 book - Part 45 of 185
The Ring programming language version 1.5.4 book - Part 45 of 185Mahmoud Samir Fayed
 
Lazy beats Smart and Fast
Lazy beats Smart and FastLazy beats Smart and Fast
Lazy beats Smart and FastJulian Hyde
 
SQL Database Design & Querying
SQL Database Design & QueryingSQL Database Design & Querying
SQL Database Design & QueryingCobain Schofield
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLJerry Yang
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Charles Givre
 
Adaptive Query Processing on RAW Data
Adaptive Query Processing on RAW DataAdaptive Query Processing on RAW Data
Adaptive Query Processing on RAW DataManos Karpathiotakis
 
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...Altinity Ltd
 
Flexible Indexing with Postgres
Flexible Indexing with PostgresFlexible Indexing with Postgres
Flexible Indexing with PostgresEDB
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Davide Rossi
 
PostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analyticsPostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analyticsHans-Jürgen Schönig
 

What's hot (19)

The Ring programming language version 1.5.4 book - Part 45 of 185
The Ring programming language version 1.5.4 book - Part 45 of 185The Ring programming language version 1.5.4 book - Part 45 of 185
The Ring programming language version 1.5.4 book - Part 45 of 185
 
Lazy beats Smart and Fast
Lazy beats Smart and FastLazy beats Smart and Fast
Lazy beats Smart and Fast
 
SQL Database Design & Querying
SQL Database Design & QueryingSQL Database Design & Querying
SQL Database Design & Querying
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
 
Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2Data Exploration with Apache Drill: Day 2
Data Exploration with Apache Drill: Day 2
 
Explain this!
Explain this!Explain this!
Explain this!
 
Groovy kind of test
Groovy kind of testGroovy kind of test
Groovy kind of test
 
GORM
GORMGORM
GORM
 
Adaptive Query Processing on RAW Data
Adaptive Query Processing on RAW DataAdaptive Query Processing on RAW Data
Adaptive Query Processing on RAW Data
 
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
 
Programação c#- Criar um documento no Word
Programação c#- Criar um documento no WordProgramação c#- Criar um documento no Word
Programação c#- Criar um documento no Word
 
Advanced Relevancy Ranking
Advanced Relevancy RankingAdvanced Relevancy Ranking
Advanced Relevancy Ranking
 
Full Text Search in PostgreSQL
Full Text Search in PostgreSQLFull Text Search in PostgreSQL
Full Text Search in PostgreSQL
 
Flexible Indexing with Postgres
Flexible Indexing with PostgresFlexible Indexing with Postgres
Flexible Indexing with Postgres
 
Grails: a quick tutorial (1)
Grails: a quick tutorial (1)Grails: a quick tutorial (1)
Grails: a quick tutorial (1)
 
Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0Rmarkdown cheatsheet-2.0
Rmarkdown cheatsheet-2.0
 
SQL introduction
SQL introductionSQL introduction
SQL introduction
 
PostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analyticsPostgreSQL: Data analysis and analytics
PostgreSQL: Data analysis and analytics
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
 

Viewers also liked

Backa pita ku_varijacije
Backa pita ku_varijacijeBacka pita ku_varijacije
Backa pita ku_varijacijePACE Kiprovska
 
Elr rad waste article werner
Elr rad waste article wernerElr rad waste article werner
Elr rad waste article wernerJim Werner
 
I miss my best friends !
I miss my best friends !I miss my best friends !
I miss my best friends !miistyxoxo
 
Ci vuole cultura (informatica)
Ci vuole cultura (informatica)Ci vuole cultura (informatica)
Ci vuole cultura (informatica)Paolo Coppola
 
Melokalisasi dan mengisolasi daerah permasalahan
Melokalisasi dan mengisolasi daerah permasalahanMelokalisasi dan mengisolasi daerah permasalahan
Melokalisasi dan mengisolasi daerah permasalahanSuryono Adi
 
File server by CLOUDIAN HyperStore
File server by CLOUDIAN HyperStoreFile server by CLOUDIAN HyperStore
File server by CLOUDIAN HyperStoreCLOUDIAN KK
 
"erlang, webmail and hibari" at Rakuten tech talk
"erlang, webmail and hibari" at Rakuten tech talk"erlang, webmail and hibari" at Rakuten tech talk
"erlang, webmail and hibari" at Rakuten tech talkCLOUDIAN KK
 
Hibari at TEW5 (japanese)
Hibari at TEW5 (japanese)Hibari at TEW5 (japanese)
Hibari at TEW5 (japanese)CLOUDIAN KK
 
WavuNet: Outsourced ISV Channel Sales and Business Development
WavuNet: Outsourced ISV Channel Sales and Business DevelopmentWavuNet: Outsourced ISV Channel Sales and Business Development
WavuNet: Outsourced ISV Channel Sales and Business DevelopmentWavuNet
 
Opening remarks at cloudian seminar 2013
Opening remarks at cloudian seminar 2013Opening remarks at cloudian seminar 2013
Opening remarks at cloudian seminar 2013CLOUDIAN KK
 
AWS SDK for Python and CLOUDIAN HyperStore
AWS SDK for Python and CLOUDIAN HyperStoreAWS SDK for Python and CLOUDIAN HyperStore
AWS SDK for Python and CLOUDIAN HyperStoreCLOUDIAN KK
 
Democamp Munich 2013: Are you still manually coding UIs?
Democamp Munich 2013: Are you still manually coding UIs?Democamp Munich 2013: Are you still manually coding UIs?
Democamp Munich 2013: Are you still manually coding UIs?Maximilian Kögel
 

Viewers also liked (16)

Backa pita ku_varijacije
Backa pita ku_varijacijeBacka pita ku_varijacije
Backa pita ku_varijacije
 
Elr rad waste article werner
Elr rad waste article wernerElr rad waste article werner
Elr rad waste article werner
 
I miss my best friends !
I miss my best friends !I miss my best friends !
I miss my best friends !
 
Forum marat
Forum maratForum marat
Forum marat
 
Ci vuole cultura (informatica)
Ci vuole cultura (informatica)Ci vuole cultura (informatica)
Ci vuole cultura (informatica)
 
Melokalisasi dan mengisolasi daerah permasalahan
Melokalisasi dan mengisolasi daerah permasalahanMelokalisasi dan mengisolasi daerah permasalahan
Melokalisasi dan mengisolasi daerah permasalahan
 
Mengenal software geogebra
Mengenal software geogebraMengenal software geogebra
Mengenal software geogebra
 
File server by CLOUDIAN HyperStore
File server by CLOUDIAN HyperStoreFile server by CLOUDIAN HyperStore
File server by CLOUDIAN HyperStore
 
"erlang, webmail and hibari" at Rakuten tech talk
"erlang, webmail and hibari" at Rakuten tech talk"erlang, webmail and hibari" at Rakuten tech talk
"erlang, webmail and hibari" at Rakuten tech talk
 
Hibari at TEW5 (japanese)
Hibari at TEW5 (japanese)Hibari at TEW5 (japanese)
Hibari at TEW5 (japanese)
 
WavuNet: Outsourced ISV Channel Sales and Business Development
WavuNet: Outsourced ISV Channel Sales and Business DevelopmentWavuNet: Outsourced ISV Channel Sales and Business Development
WavuNet: Outsourced ISV Channel Sales and Business Development
 
Opening remarks at cloudian seminar 2013
Opening remarks at cloudian seminar 2013Opening remarks at cloudian seminar 2013
Opening remarks at cloudian seminar 2013
 
A3.unit trang
A3.unit trangA3.unit trang
A3.unit trang
 
AWS SDK for Python and CLOUDIAN HyperStore
AWS SDK for Python and CLOUDIAN HyperStoreAWS SDK for Python and CLOUDIAN HyperStore
AWS SDK for Python and CLOUDIAN HyperStore
 
Democamp Munich 2013: Are you still manually coding UIs?
Democamp Munich 2013: Are you still manually coding UIs?Democamp Munich 2013: Are you still manually coding UIs?
Democamp Munich 2013: Are you still manually coding UIs?
 
New jersey
New jerseyNew jersey
New jersey
 

Similar to JKJ_T SQL project code samples

Jeff Jacob MSBI Training portfolio
Jeff Jacob MSBI Training portfolioJeff Jacob MSBI Training portfolio
Jeff Jacob MSBI Training portfolioJeff Jacob
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioBob Litsinger
 
J. Adcock Bi Portfolio
J. Adcock   Bi PortfolioJ. Adcock   Bi Portfolio
J. Adcock Bi PortfolioJerry Adcock
 
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docx
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docxRELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docx
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docxsodhi3
 
Chris Mc Glothen Sql Portfolio
Chris Mc Glothen Sql PortfolioChris Mc Glothen Sql Portfolio
Chris Mc Glothen Sql Portfolioclmcglothen
 
William Berth Bi Portfolio
William Berth Bi PortfolioWilliam Berth Bi Portfolio
William Berth Bi Portfolionewberth
 
Weather scraper for your data warehouse
Weather scraper for your data warehouseWeather scraper for your data warehouse
Weather scraper for your data warehouseFru Louis
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 
Intro To PostGIS
Intro To PostGISIntro To PostGIS
Intro To PostGISmleslie
 
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...djkucera
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...djkucera
 
Avro, la puissance du binaire, la souplesse du JSON
Avro, la puissance du binaire, la souplesse du JSONAvro, la puissance du binaire, la souplesse du JSON
Avro, la puissance du binaire, la souplesse du JSONAlexandre Victoor
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfoliogregmlewis
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfoliolilredlokita
 
T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .NetKathiK58
 
Kevin Bengtson Portfolio
Kevin Bengtson PortfolioKevin Bengtson Portfolio
Kevin Bengtson PortfolioKbengt521
 

Similar to JKJ_T SQL project code samples (20)

Jeff Jacob MSBI Training portfolio
Jeff Jacob MSBI Training portfolioJeff Jacob MSBI Training portfolio
Jeff Jacob MSBI Training portfolio
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
J. Adcock Bi Portfolio
J. Adcock   Bi PortfolioJ. Adcock   Bi Portfolio
J. Adcock Bi Portfolio
 
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docx
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docxRELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docx
RELATIONAL DATABASES & Database designCIS276EmployeeNumFir.docx
 
Chris Mc Glothen Sql Portfolio
Chris Mc Glothen Sql PortfolioChris Mc Glothen Sql Portfolio
Chris Mc Glothen Sql Portfolio
 
William Berth Bi Portfolio
William Berth Bi PortfolioWilliam Berth Bi Portfolio
William Berth Bi Portfolio
 
Weather scraper for your data warehouse
Weather scraper for your data warehouseWeather scraper for your data warehouse
Weather scraper for your data warehouse
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Intro To PostGIS
Intro To PostGISIntro To PostGIS
Intro To PostGIS
 
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
Oracle OpenWorld 2010 - Consolidating Microsoft SQL Server Databases into an ...
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
Collaborate 2009 - Migrating a Data Warehouse from Microsoft SQL Server to Or...
 
70433 Dumps DB
70433 Dumps DB70433 Dumps DB
70433 Dumps DB
 
Avro, la puissance du binaire, la souplesse du JSON
Avro, la puissance du binaire, la souplesse du JSONAvro, la puissance du binaire, la souplesse du JSON
Avro, la puissance du binaire, la souplesse du JSON
 
Greg Lewis SQL Portfolio
Greg Lewis SQL PortfolioGreg Lewis SQL Portfolio
Greg Lewis SQL Portfolio
 
SQL Server 2008 Portfolio
SQL Server 2008 PortfolioSQL Server 2008 Portfolio
SQL Server 2008 Portfolio
 
T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .Net
 
Kevin Bengtson Portfolio
Kevin Bengtson PortfolioKevin Bengtson Portfolio
Kevin Bengtson Portfolio
 

JKJ_T SQL project code samples

  • 1. Transact-SQL ProjectSQL Server 2008 Management Studio SetFocus Business Intelligence Master’s Program Jeff Jacob, MBA P: (312) 772-6142 E1: Jeffrey.K.Jacob@gmail.com E2: Jeffrey.Jacob@SetFocus.com
  • 2. Query 1 – Wildcard Search(CI Collation)A summary of order detail-linetotal by product – for products that contain ‘Washer’ in their name; 2003 data only. USE [AdventureWorks2008]; GO SELECT Name, SUM(LineTotal) AS TotDollars FROM Purchasing.PurchaseOrderDetail pod INNER JOIN Purchasing.PurchaseOrderHeader poh ON poh.PurchaseOrderID = pod.PurchaseOrderID INNER JOIN Production.Productprd ON prd.ProductID = pod.ProductID WHERE Name LIKE '%washer%‘ AND YEAR(OrderDate) = 2003 GROUP BY Name ORDER BY TotDollars DESC 2
  • 3. Query 2 – HAVING clauseA count of orders by product subcategory– for those with at least 10 orders; 2004 data only. USE [AdventureWorks2008]; GO SELECT psc.Name, COUNT(poh.PurchaseOrderID) AS NumOrders FROM Purchasing.PurchaseOrderHeader poh INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.PurchaseOrderID = poh.PurchaseOrderID INNER JOIN Production.ProductprdON prd.ProductID = pod.ProductID INNER JOIN Production.ProductSubcategorypscON prd.ProductSubcategoryID= psc.ProductSubcategoryID WHERE YEAR(OrderDate) = 2004 GROUP BY psc.Name HAVING COUNT(poh.PurchaseOrderID) >=10 ORDER BY NumOrdersDESC 3
  • 4. Query 3 – Correlated Subquery of exclusionA list of the vendors for which there were no orders in 2003. USE [AdventureWorks2008]; GO SELECT Name FROM Purchasing.Vendor WHERE NOT EXISTS (SELECT * FROM Purchasing.PurchaseOrderHeader WHERE YEAR(OrderDate) = 2003 AND Vendor.BusinessEntityID = PurchaseOrderHeader.VendorID) 4
  • 5. Query 4 – OUTER JOIN syntaxA summary of freight charges by shipper for all shippers; Q1 of 2003 data only. USE [AdventureWorks2008]; GO SELECT Name, SUM(Freight) AS TotFreight FROM Purchasing.ShipMethodsm LEFT OUTER JOIN Purchasing.PurchaseOrderHeader poh ON poh.ShipMethodID = sm.ShipMethodID AND YEAR(OrderDate) = 2003 AND DATEPART(q,OrderDate) = 1 GROUP BY Name ORDER BY TotFreightDESC 5
  • 6. Query 5 – Chronological Sort A summary of total charges due by specific employee national ID numbers, sorted chronologically within each employee; 2003 data only. USE [AdventureWorks2008]; GO SELECT NationalIDNumber, LoginID, DATENAME(MONTH, OrderDate) AS MonthName, YEAR(OrderDate) as YearName, SUM(TotalDue) AS SumTotalDue FROM Purchasing.PurchaseOrderHeaderpoh INNER JOIN HumanResources.Employeeemp ON emp.BusinessEntityID = poh.EmployeeID WHERE NationalIDNumber IN (792847334, 407505660, 482810518, 466142721, 367453993) AND YEAR(OrderDate) = 2003 GROUP BY NationalIDNumber, LoginID, DATENAME(MONTH, OrderDate),DATEPART(MONTH, OrderDate) ,YEAR(OrderDate) ORDER BY NationalIDNumber, DATEPART(MONTH, OrderDate) 6
  • 7. Query 6 – UNION queryA union of two view-based queries to obtain contact information of both vendors and employees, sorted first by postal code and then by name. USE [AdventureWorks2008]; GO SELECT 'Vendor' AS RecordType, Name, AddressLine1, ISNULL(AddressLine2,'') AS AddressLine2, City, StateProvinceName, PostalCode FROM Purchasing.vVendorWithAddresses UNIONALL SELECT 'Employee' AS RecordType, LastName + ', ‘ + FirstName + ' ‘ + ISNULL(MiddleName, ''), AddressLine1, ISNULL (AddressLine2,''), City, StateProvinceName, PostalCode FROM HumanResources.vEmployee ORDER BY PostalCode, Name 7
  • 8. Query 7 – Stored ProcedureA stored procedure designed to summarize freight, tax amount and subtotal by vendor and shipper based on supplied account number and date parameters; with example usage. USE [AdventureWorks2008]; GO CREATEPROCEDUREdbo.usp_GetVendorOrders @AcctNonvarchar(15), @StartDatedatetime, @EndDatedatetime AS SET NOCOUNT ON; SELECT Ven.Name AS VendorName, Ship.Name AS ShipperName, SUM(Freight) as TotFreight, SUM(TaxAmt) AS TotTaxAmt, SUM(SubTotal) AS TotSubTot FROM Purchasing.PurchaseOrderHeaderpoh JOIN Purchasing.VendorVen ON poh.VendorID = Ven.BusinessEntityID JOIN Purchasing.ShipMethod ship ON ship.ShipMethodID = poh.ShipMethodID WHERE OrderDate >= @StartDate and OrderDate <= @EndDate AND AccountNumber = @AcctNo GROUP BY Ven.Name, Ship.Name GO EXEC dbo.usp_GetVendorOrders N'ADVANCED0001', '1-1-2003', '12-31-2003' 8
  • 9. Query 8 – PIVOT tableA pivot table of shipper data for total charges due in 2003 summarized by Saturdays with a summary rank of the Top 5 based on grand total. ;WITH ShipperTotDueCTE AS ( SELECT sm.Name, dbo.SatDatesConverter(OrderDate) AS WeekEnding, TotalDue FROM Purchasing.PurchaseOrderHeaderpoh INNER JOIN Purchasing.ShipMethodsm ON sm.ShipMethodID = poh.ShipMethodID WHERE YEAR(OrderDate) = 2003 ), SumByWeekEndCTE AS ( SELECT Name AS Shipper, WeekEnding, SUM(TotalDue) AS GrandTot FROM ShipperTotDueCTE GROUP BY Name, WeekEnding ), PivCTE AS ( SELECT WeekEnding, [XRQ - Truck Ground] AS XRQ, [Cargo Transport 5] AS Cargo, [Overnight J-Fast] AS Overnight, [ZY - Express] AS ZY, [Overseas - Deluxe] AS Overseas, ISNULL([XRQ - Truck Ground],0) + ISNULL([Cargo Transport 5],0) + ISNULL([Overnight J-Fast],0) + ISNULL([ZY - Express],0) + ISNULL([Overseas - Deluxe],0) AS GrandTot FROM SumByWeekEndCTE PIVOT ( SUM(GrandTot) FOR Shipper IN ([XRQ - Truck Ground],[Cargo Transport 5], [Overnight J-Fast],[ZY - Express], [Overseas - Deluxe]) ) AS P ) SELECT TOP 5 WeekEnding, GrandTot, RANK() OVER (ORDER BY GrandTot DESC) AS WeekRank, XRQ, ZY, Overseas, Overnight, Cargo FROM PivCTE ORDER BY WeekRank; USE [AdventureWorks2008]; GO CREATEFUNCTION [dbo].[SatDatesConverter] (@orderdatedatetime) RETURNS datetime AS BEGIN DECLARE @satdatedatetime SET @satdate = (SELECT DateAdd(d, 7- datepart(dw, @OrderDate), @OrderDate)) RETURN @satdate END; GO 9
  • 10. USE [AdventureWorks2008]; GO CREATEPROCEDUREdbo.usp_VendorProductRank @TopNint, @TopYint, @BeginDatedatetime, @EndDatedatetime AS SET NOCOUNT ON; ;WITH VendCTE AS ( SELECT Ven.BusinessEntityID, Ven.Name AS VendorName, SUM(TotalDue) AS TotalDue, DENSE_RANK () OVER (ORDER BY SUM(TotalDue) DESC ) AS VendorRank FROM Purchasing.VendorVen INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON poh.VendorID = Ven.BusinessEntityID WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate GROUP BY BusinessEntityID, Name ), ProdCTEAS ( SELECT Ven.BusinessEntityID, prd.Name AS ProductName, SUM(LineTotal) AS ProductTotalDue, DENSE_RANK() OVER (PARTITION BY Ven.BusinessEntityID ORDER BY SUM(LineTotal) DESC) AS ProductRank FROM Purchasing.Vendorven INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON poh.VendorID = ven.BusinessEntityID INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.PurchaseOrderID = poh.PurchaseOrderID INNER JOIN Production.Productprd ON prd.ProductID = pod.ProductID WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate GROUP BY Ven.BusinessEntityID, prd.Name) SELECT VC.VendorName, VC.VendorRank, CAST(VC.TotalDue AS NUMERIC (14,2)) AS TotalDue, PC.ProductName, PC.ProductRank, CAST(PC.ProductTotalDue AS NUMERIC (14,2) ) AS ProductTotalDue FROM VendCTE VC INNER JOIN ProdCTE PC ON PC.BusinessEntityID = VC.BusinessEntityID WHERE VendorRank <= @TopN AND ProductRank <= @TopY ORDER BY VendorRank, ProductRank GO EXECdbo.usp_VendorProductRank 5,5,'2003-01-01', '2004-06-30' Query 9 – SP, CTE-only approachA stored procedure for a ranking of Top N vendors by Total Due amount; and, within each vendor, the Top N products based on Line Total (Due) for specified start/end dates. 10
  • 11. Query 9 – SP, CTE/Function approach A stored procedure for a ranking of Top N vendors by Total Due amount; and, within each vendor, the Top N products based on Line Total (Due) for specified start/end dates. CREATEPROCEDURE dbo.usp_TestProc1 @TopNint, @TopYint, @BeginDatedatetime, @EndDatedatetime AS SET NOCOUNT ON; ;WITHxCTEas ( SELECT TOP (@TopN) WITH TIES poh.VendorID, ven.Name AS VendorName, SUM(poh.TotalDue) AS TotalDue, DENSE_RANK() OVER (ORDER BY SUM(poh.TotalDue) DESC) AS VendorRank FROM Purchasing.PurchaseOrderHeaderpoh INNER JOIN Purchasing.Vendorven ON ven.BusinessEntityID = poh.VendorID WHERE OrderDate >= @BeginDate AND OrderDate <= @EndDate GROUP BY poh.VendorID, ven.Name ) SELECT xCTE.VendorName, xCTE.VendorRank, CAST(xCTE.TotalDue AS NUMERIC (14,2)) AS TotalDue, C.ProductName, C.ProductRank, CAST(C.ProductLineTotal AS NUMERIC (14,2) ) AS ProductLineTotal FROM xCTE CROSS APPLY dbo.TestFn1 (xCTE.VendorID, @TopY, @BeginDate, @EndDate) AS C GO EXEC dbo.usp_TestProc1 5, 5,'2003-01-01', '2004-06-30' USE [AdventureWorks2008]; GO CREATEFUNCTION dbo.TestFn1 (@VendorIDint, @TopYint, @StartDatedatetime, @EndingDatedatetime) RETURNS TABLE AS RETURN SELECT TOP (@TopY) WITH TIES poh.vendorid, prd.Name AS ProductName, DENSE_RANK() OVER (PARTITION BY poh.vendorID ORDER BY SUM(pod.LineTotal) DESC) AS ProductRank, SUM(pod.LineTotal) AS ProductLineTotal FROM Production.Productprd INNER JOIN Purchasing.PurchaseOrderDetail pod ON pod.productid = prd.productid INNER JOIN Purchasing.PurchaseOrderHeaderpoh ON pod.PurchaseOrderid = poh.purchaseorderid WHERE poh.VendorID = @VendorID AND OrderDate >= @StartDate AND OrderDate <= @EndingDate GROUP BY poh.vendorID, prd.Name ORDER BY ProductLineTotal DESC GO 11
  • 12. Query 10 – Effective (‘As of’) Dates: Scalar UDF A function which provides the commensurate standardproductcost based on a specified productIDnumber and a desired ‘effective date.’ Example included. USE [AdventureWorks2008]; GO CREATEFUNCTIONdbo.ProdStdCostAsOfDate (@ProductIDint, @AsOfDatedatetime ) RETURNS MONEY AS BEGIN DECLARE @StndCost money SET @StndCost = ( SELECT StandardCost FROM Production.ProductCostHistorypch WHERE ProductID = @ProductID AND StartDate = (SELECT MAX(StartDate) FROM Production.ProductCostHistory WHERE ProductID = @Productid AND StartDate <= @AsOfDate ) ) RETURN @StndCost END; GO ;WITH ProdStdCostCTE AS ( SELECT ProductNumber, Name, CAST( dbo.ProdStdCostAsOfDate (Product.ProductID, '2002-01-01') AS NUMERIC (14,2) ) AS StandardCost FROM Production.Product INNER JOIN Production.ProductCostHistorypch ON pch.ProductID = Product.ProductID ) SELECT ProductNumber, Name, StandardCost FROM ProdStdCostCTE WHERE StandardCost IS NOT NULL AND StandardCost > 700 ORDER BY StandardCost DESC; 12