-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql challenge.Rmd
More file actions
1188 lines (970 loc) · 34.4 KB
/
sql challenge.Rmd
File metadata and controls
1188 lines (970 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "R Notebook"
output: html_notebook
---
```{r setup}
#sql chunk, db connection not available
library(DBI)
db = dbConnect(RSQLite::SQLite(), dbname = "sql.sqlite")
knitr::opts_chunk$set(connection = "db")
```
### Scenario 1
- Comparison of total sales from the fiscal quarters of 2008 to the fiscal quarters of 2007
- Fiscal year is from June to July
**Test Example**
```{sql}
SELECT
a.SalesPersonID,
c.LastName,
/*add 6 months to orderdate to get fiscal year from July to June*/
YEAR(DATEADD(MONTH,6,a.OrderDate)) as FY, /*result is a year*/
DATEPART(QUARTER,DATEADD(MONTH,6,a.OrderDate)) as FQ, /*result is a number of quarter*/
SUM(a.SubTotal) as FQSales, /*sum of sales*/
SUM(b.SubTotal) as SameSalesFQLast, /*sum of sales*/
SUM(a.SubTotal)-SUM(b.SubTotal) as Change, /*difference between sum of sales*/
((SUM(a.SubTotal)-SUM(b.SubTotal)) /SUM(b.SubTotal)) * 100 as pct_change /*percentage*/
/*2018-2017/2017*/
/*join two same tables to itself and specify dates in tables*/
FROM [Sales].[SalesOrderHeader] a left join [Sales].[SalesOrderHeader] b
ON a.SalesPersonID=b.SalesPersonID
/*quarters in both tables are same*/
AND DATEPART(QUARTER,DATEADD(MONTH,6,b.OrderDate))=DATEPART(QUARTER,DATEADD(MONTH,6,a.OrderDate))
/*table b is in 2008 and table a is in 2007*/
AND DATEPART(YEAR,DATEADD(MONTH,6,b.OrderDate))=DATEPART(YEAR,DATEADD(MONTH,6,a.OrderDate))-1
INNER JOIN Person.[Person] c
ON c.BusinessEntityID=a.SalesPersonID
WHERE DATEPART(YEAR,DATEADD(MONTH,6,a.OrderDate))=2008
GROUP BY 1,2,3,4
```
**Real Example**
```{sql}
SELECT
DATEPART(YEAR,DATEADD(MONTH,6,a.impression_dt)) as FY, /*result is a year*/
DATEPART(QUARTER,DATEADD(MONTH,6,a.impression_dt)) as FQ, /*result is a number of quarter*/
COUNT(a.sudid) as FQSales, /*sum of sales*/
COUNT(b.sudid) as SameSalesFQLast, /*sum of sales*/
COUNT(a.sudid)-COUNT(b.sudid) as Change, /*difference between sum of sales*/
((COUNT(a.sudid)-COUNT(b.sudid))/COUNT(b.sudid))*100 as pct_change /*percentage*/
FROM fact_impressions a left join fact_impressions b
ON a.sudid = b.sudid
AND DATEPART(QUARTER,DATEADD(MONTH,6,b.impression_dt))=DATEPART(QUARTER,DATEADD(MONTH,6,a.impression_dt))
AND DATEPART(YEAR,DATEADD(MONTH,6,b.impression_dt))=DATEPART(YEAR,DATEADD(MONTH,6,a.impression_dt))-1
WHERE DATEPART(YEAR,DATEADD(MONTH,6,a.impression_dt))=2018
AND DATEPART(QUARTER, DATEADD(MONTH,6,a.impression_dt)) = 4
GROUP BY 1,2
```
### Scenario 2
2/22 promotion, orders subtotaling at least $\$2,000$ ship for $\$0.22$. The strategy assumes that freight losses will be offset by gains from higher value orders. Orders between $1,700 and $\$2,000$ will likely boost to $\$2,000$ as customers feel compelled to take advantage of bargain freight pricing
- Potential Promotional Effect
- Potential order gains
- Potential freight losses
- Overall net gain/loss
**Test Example**
```{sql}
SELECT
a.SalesOrderID, --Order ID
a.OrderDate, -- Date
d.Name AS Ship_to_State, -- State
a.SubTotal AS Historical_Order_Total, -- Prior to discount
a.Freight AS Historical_Freight, -- Prior to discount
CASE
WHEN a.SubTotal>=1700 and a.SubTotal<2000 THEN 'Increase order to 2000 and pay 22 cents as Freight'
WHEN a.SubTotal>=2000 THEN 'No Order Change but pay 22 cents as Freight'
ELSE 'No order change and pay historical freight'
END as Promo_Effect,
CASE
WHEN a.SubTotal>=1700 and a.SubTotal<2000 THEN 2000 - a.SubTotal
ELSE 0
END as Potential_Order_Gain,
CASE
WHEN a.SubTotal>=1700 THEN 0.22 else a.Freight END - a.Freight as PotentialFreightoss,
(CASE
WHEN a.SubTotal>=1700 and a.SubTotal<2000 then 2000 -a.SubTotal
ELSE 0
END +
CASE
WHEN a.SubTotal>=1700 THEN 0.22 ELSE a.Freight
END )-
a.Freight AS PromoNetGain_Loss
FROM [Sales].[SalesOrderHeader] a
JOIN Person.BusinessEntityAddress b ON a.ShipToAddressID=b.AddressID
JOIN Person.[Address] c ON b.AddressID = c.AddressID
JOIN Person.StateProvince d ON c.StateProvinceID=d.StateProvinceID
WHERE d.Name = 'California'
AND DATEPART (YEAR, DATEADD (MONTH, 6,a.OrderDate)) = 2008
```
### Scenario 12
You are asked to provide frequent updates about the product inventory.
**Test Example**
```{sql}
-- final table includes quantity of each product and total of all products
SELECT
b.name,
count(distinct a.ProductID) AS ProductCount,
sum(a.Quantity) as ProductQty
FROM [Production].[ProductInventory] a
JOIN [Production].[Location] b ON a.LocationID=b.LocationID
GROUP BY (b.name)
UNION
SELECT
'Total' ,
count(distinct a.ProductID) AS ProductCount,
SUM(a.Quantity) as ProductQty
FROM [Production].[ProductInventory] a
```
### Scenario 13
Identify the employee or group of employees with the greatest number of vacation hours. Since many HR files are indexed by National ID Number, include the last four digits with your output.
**Test Example**
```{sql}
WITH MaxVacHrs AS
(SELECT MaxVacHrs = MAX (VacationHours) FROM HumanResources.Employee)
SELECT
RIGHT (N1.NationalIDNumber, 4) AS NationalID,
N2.FirstName,
N2.LastName,
N1.JobTitle,
N1.VacationHours
FROM HumanResources.Employee N1
INNER JOIN Person.Person N2 ON N1.BusinessEntityID = N2.BusinessEntityID
INNER JOIN MaxVacHrs N3 ON N1.VacationHours = N3.MaxVacHrs
```
### Scenario 14
For each product ordered by the Purchasing Department in 2007, indicate the quantity ordered by order date.
```{sql}
SELECT
b.ProductID,
c.Name,
a.OrderDate,
sum(b.OrderQty) as QTY
FROM [Purchasing].[PurchaseOrderHeader] a
JOIN [Purchasing].[PurchaseOrderDetail] b ON a.PurchaseOrderID=b.PurchaseOrderID
JOIN [Production].[Product] c ON b.ProductID=c.ProductID
WHERE DATEPART(YEAR, a.OrderDate)=2007
GROUP BY 1,2,3
ORDER BY sum(b.OrderQty) DESC
```
### Scenario 15
List of all product descriptions written in languages other than English.
```{sql}
SELECT
a.ProductModelID,
a.Name,
c.Description,
b.CultureID
FROM [Production].[ProductModel] a
JOIN [Production].[ProductModelProductDescriptionCulture] b ON a.ProductModelID=b.ProductModelID
JOIN [Production].[ProductDescription] c ON b.ProductDescriptionID=c.ProductDescriptionID
WHERE b.CultureID != 'en'
```
### Scenario 20
Provide address data about stores with main offices located in Toronto.
```{sql}
SELECT
d.Name AS StoreName,
a.AddressLine1,
a.AddressLine2,
a.City,c.Name,
a.PostalCode
FROM [Person].[Address] a JOIN [Person].[BusinessEntityAddress] b ON a.AddressID=b.AddressID
JOIN [Person].[StateProvince] c ON a.StateProvinceID=c.StateProvinceID
JOIN [Sales].[Store] d ON d.BusinessEntityID=b.BusinessEntityID
WHERE b.AddressTypeID=3 -- or d.name = 'Main Office'
AND a.City='Toronto'
```
### Scenario 21
List of employees who are currently in the Marketing department and were hired prior to 2002 or later than 2004.
```{sql}
SELECT
d.FirstName,
d.LastName,
c.JobTitle,
c.BirthDate,
c.MaritalStatus,
a.StartDate AS Hire_Date
FROM [HumanResources].[EmployeeDepartmentHistory] a
JOIN [HumanResources].[Department] b ON a.DepartmentID=b.DepartmentID
JOIN [HumanResources].[Employee] c ON c.BusinessEntityID=a.BusinessEntityID
JOIN [Person].[Person] d ON d.BusinessEntityID=a.BusinessEntityID
WHERE
(DATEPART(YEAR, a.StartDate)<2002
OR DATEPART(YEAR, a.StartDate)>2004)
AND b.Name='Marketing'
AND a.EndDate IS NULL
```
### Scenario 22
Who left that review?
```{sql}
SELECT
a.ProductReviewID,
a.ProductID,
b.Name,
a.ReviewerName,
a.Rating,
a.EmailAddress,
c.BusinessEntityID -- will be returned as 0
FROM [Production].[ProductReview] a
JOIN [Production].[Product] b ON a.ProductID=b.ProductID
LEFT JOIN [Person].[EmailAddress] c ON a.EmailAddress=c.EmailAddress
```
### Scenario 23
List of customers with phone numbers for all orders for shorts placed online after July 7, 2008.
```{sql}
SELECT
a.SalesOrderID,
a.OrderDate,
c.Name,
f.FirstName,
f.LastName,
g.PhoneNumber
FROM [Sales].[SalesOrderHeader] a
INNER JOIN [Sales].[SalesOrderDetail] b ON a.SalesOrderID=b.SalesOrderID
INNER JOIN [Production].[Product] c ON b.ProductID=c.ProductID
INNER JOIN [Sales].[Customer] e ON e.CustomerID=a.CustomerID
INNER JOIN [Person].[Person] f ON e.PersonID=f.BusinessEntityID
INNER JOIN [Person].[PersonPhone] g ON g.BusinessEntityID=f.BusinessEntityID
WHERE a.OrderDate>'2008-07-07'
AND a.OnlineOrderFlag=1
AND LOWER(c.Name) LIKE '%shorts%'
ORDER BY a.SalesOrderID
```
### Scenario 19
Display the most common reasons why products were scrapped through the manufacturing process.
```{sql}
WITH Temp AS
(SELECT
ROW_NUMBER () OVER (PARTITION BY N1.ProductID
ORDER BY COUNT (N2.Name) DESC) AS rank, --name is the reason why it was scrapped
N1.ProductID
ProductName AS N2.Name
COUNT (N2.Name) AS WorkOrderCount
N3.Name AS ScrapReason
FROM Production.WorkOrder N1
INNER JOIN Production.Product N2 ON N1.ProductID = N2.ProductID
INNER JOIN Production.ScrapReason N3 ON N1.ScrapReasonID = N3.ScrapReasonID
GROUP BY N1.ProductID, N2.Name, N3.Name)
SELECT
ProductID,
ProductName,
WorkOrderCount,
ScrapReason
FROM Temp
WHERE rank = 1
ORDER BY WorkOrderCount DESC
```
### Solution 18
- minimium historical cost
- maximum historical cost
- historical cost variablity - maximum minus minimum
- ranking of all historical cost variablities - rank of 1 reflects the product ID exhibiting the greatetist historical cost variability
```{sql}
-- ROW_NUMBER – Returns the sequential number of a row within a partition of a result set, without any gaps in the ranking. ... The rank of a row is one plus the number of ranks that come before the row in question.
--DENSE_RANK – Returns the rank of rows within the partition of a result set, without any gaps in the ranking
SELECT
N1.ProductID
N2.Name AS ProductName
N3.Name AS SubCategory
MIN (N1.StandardCost) AS MinCost
MAX (N1.StandardCost) AS MaxCost
MAX (N1.StandardCost) - MIN (N1.StandardCost) AS CostVar
CASE
WHEN MAX (N1.StandardCost) - MIN (N1.StandardCost) = 0 THEN 0
ELSE DENSE_RANK () OVER (ORDER BY MAX (N1.StandardCost) - MIN (N1.StandardCost) DESC)
END AS CostVarRank -- gives a number to each row based on difference in standard cost
FROM Production.ProductCostHistory N1
INNER JOIN Production.Product N2 ON N1.ProductID = N2.ProductID
INNER JOIN Production.ProductSubcategory N3 ON N2.ProductSubcategoryID = N3.ProductSubcategoryID
GROUP BY N1.ProductID, N2.[Name], N3.[Name]
ORDER BY MAX (N1.StandardCost) - MIN (N1.StandardCost) DESC
```
### Solution 17
Identify stores in which the last order date was at least 12 months ago (today's date is October 7, 2008)
```{sql}
WITH Stores AS
(SELECT
N3.BusinessEntityID,
N1.CustomerID,
N2.StoreID,
N3.Name AS StoreName
MAX (N1.OrderDate) AS LastOrderDate
DATEDIFF (MONTH, MAX (N1.OrderDate), '2008-10-07') AS MonthsSinceLastOrder
FROM Sales.SalesOrderHeader N1
INNER JOIN Sales.Customer N2 ON N1.CustomerID = N2.CustomerID
INNER JOIN Sales.Store N3 ON N2.StoreID = N3.BusinessEntityID
GROUP BY 1,2,3,4)
SELECT *
FROM Stores
WHERE MonthsSinceLastOrder > = 12
ORDER BY MonthsSinceLastOrder DESC
```
### Solution 16
summary table that shows, by territory, the percentage of orders placed online in comparison to orders not placed online
```{sql}
SELECT
TerritoryID,
COUNT(*) AS TotalOrders,
CONVERT(VARCHAR(50), -- to add % after a calculation
ROUND( -- to round the calculation to the whole number
(CONVERT(FLOAT, -- to calculate with float
SUM(CASE -- calculation itself
WHEN OnlineOrderFlag = 1
THEN 1
ELSE 0
END)) /COUNT(*))* 100
,0)
)
+ '%' AS PercOnline
CONVERT(VARCHAR(50),
ROUND(
(CONVERT(FLOAT,
SUM(CASE
WHEN OnlineOrderFlag = 0
THEN 1 ELSE 0
END)) /COUNT(*))* 100
,0)
)
+ '%' AS PercOffline
FROM Sales.SalesOrderHeader
GROUP BY TerritoryID
ORDER BY TerritoryID
```
### Solution 11
max tax rate in each country
```{sql}
SELECT
N3.Name AS Country,
MAX (N1.TaxRate) AS MaxTaxRate
FROM Sales.SalesTaxRate N1
INNER JOIN Person.StateProvince N2 ON N1.StateProvinceID = N2.StateProvinceID
INNER JOIN Person.CountryRegion N3 ON N2.CountryRegionCode = N3.CountryRegionCode
GROUP BY 1
```
### Solution 4
compare sales from Tuesday to other days of the week; calculate average reveniue per order by day of week in 2008
```{sql}
SELECT
DATENAME (WEEKDAY, OrderDate) AS DayCategory,
SUM (Subtotal) AS Revenue,
COUNT (*) AS Orders,
SUM (Subtotal) / COUNT (*) AS RevenuePerOrder
FROM Sales.SalesOrderHeader
WHERE DATEPART(YEAR, OrderDate) = 2008
AND OnlineOrderFlag = 0
GROUP BY 1
ORDER BY RevenuePerOrder DESC
```
### Scenario 24
Email preferences in table Person.Person:
- The value 0 indicates "Contact does not wish to receive e-mail promotions"
- The value 1 indicates "Contact does wish to receive e-mail promotions from Adventure Works"
- The value 2 indicates "Contact does wish to receive e-mail promotions from Adventure Works and selected partners"
Count number of email addresses per email preference
```{sql}
WITH Email AS
(SELECT
N1.BusinessEntityID,
N1.EmailAddress,
CASE
WHEN N2.EmailPromotion = 0 THEN
'Contact does not wish to receive e-mail promotions'
WHEN N2.EmailPromotion = 1 THEN
'Contact does wish to receive e-mail promotions from AdventureWorks'
WHEN N2.EmailPromotion = 2 THEN
'Contact does wish to receive e-mail promotions from AdventureWorks and selected partners'
END AS EmailPreference
FROM Person.EmailAddress N1
LEFT JOIN Person.Person N2 ON N1.BusinessEntityID = N2.BusinessEntityID
WHERE N2.PersonType = 'IN')
SELECT
EmailPref, COUNT (*)
FROM Email
GROUP BY EmailPref
ORDER BY COUNT (*) DESC
```
### Scenario 25
Which two sales territories were top performers during fiscal years 2006 and 2007
```{sql}
WITH TerritoryRank AS
(SELECT
DATEPART(YEAR, DATEADD (MONTH, 6, N1.OrderDate)) AS FY, -- adjust orderdate to fiscal years, from July to June
N2.Name AS Territery,
SUM (N1.SubTotal) AS Revenue,
DENSE_RANK () OVER (PARTITION BY YEAR (DATEADD (MONTH, 6, N1.OrderDate))
ORDER BY SUM (N1.Subtotal) DESC) AS TerritoryRank
FROM Sales.SalesOrderHeader N1
INNER JOIN Sales.SalesTerritory N2 ON N1.TerritoryID = N2.TerritoryID
GROUP BY 1,2)
SELECT *
FROM TerritoryRank
WHERE FY IN (2006, 2007) AND TerritoryRank IN (1, 2)
ORDER BY FY, Territory$Rank
```
### Scenario 26
Rank commission percentages by sales person
If commission percentages are equal among sales people, rank by Bonus in descending order
```{sql}
SELECT
BusinessEntityID,
CommissionPct,
Bonus,
DENSE_RANK () OVER (ORDER BY CommissionPct DESC, Bonus DESC) AS Rank
FROM Sales.SalesPerson
ORDER BY CommissionPct DESC
```
### Scenario 27
Part 1:
Report the number of work orders by productID, order the results from the greates number of work orders to the least
Part 2:
Report the number of work orders by product name. Order your results from the greatest number of work orders to the least.
```{sql}
-- Part I
SELECT
ProductID,
COUNT (*) AS WorkOrders
FROM Production.WorkOrder
GROUP BY ProductID
ORDER BY COUNT (*) DESC
-- Part II
SELECT
N2.Name AS ProductName,
COUNT (*) AS WorkOrders
FROM Production.WorkOrder N1
INNER JOIN Production.Product N2 ON N1.ProductID = N2.ProductID
GROUP BY 1
ORDER BY 2 DESC
```
### Scenario 28
Part 1:
Today is May 24, 2008. Using only revenue information from May 1 through May 23, estimate revenue for the whole month of May.
Output: No of days in month so far,Total Revenue in month so far,Revenue per day for month so far,Monthly Revenue trended for all of May
Part 2:
the actual revenue information
```{sql}
-- declare is not available in redshift, I can use CTE instead
DECLARE @StartDate DATE = '2008-05-01'
DECLARE @EndDate DATE = '2008-05-23'
-- Part I:
SELECT
DATEDIFF (day, @StartDate, @EndDate) + 1 AS DaysInMonthSoFar, -- difference between start and end date in days
SUM (SubTotal) AS RevenueInMonthSoFar, -- total revenue so far
SUM (SubTotal / DATEDIFF (day, @StartDate, @EndDate) + 1) AS RevPerDayforMonthSoFar, -- revenue per day
DAY (EOMONTH (@StartDate)) AS DaysInMonth -- end of month of start date, taking only day from the final format
SUM (SubTotal) / (DATEDIFF (day, @StartDate, @EndDate) + 1) -- average per day
* DAY (EOMONTH (@StartDate)) AS MonthlyRevTrended -- days in month
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN @StartDate AND @EndDate
-- Part II:
SELECT
SUM (SubTotal) / DAY (EOMONTH (@StartDate)) AS ActualPerDay
SUM (Subtotal) AS ActualRev
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN @StartDate AND EOMONTH (@EndDate)
```
### Scenario 29
Separate the names from the domains
```{sql}
-- charindex returns the position
-- LoginID (for example, adventure-works\ken0)
-- Domain (for example, adventure-works)
-- Username (for example ken0)
SELECT
BusinessEntityID,
LoginID
LEFT (LoginID, CHARINDEX ('\', LoginID, 1) - 1) AS Domain -- position of \ -1 is length to be taken from left
RIGHT (LoginID, LEN (LoginID) - CHARINDEX ('\', LoginID, 1)) AS Username
FROM HumanResources.Employee
ORDER BY BusinessEntityID
```
### Scenario 30
Management will review the current distribution of labor by shift within the Production department.
```{sql}
SELECT
N2.Name AS DepartmentName
N3.Name AS ShiftName
COUNT (*) AS Employees
FROM HumanResources.EmployeeDepartmentHistory N1
INNER JOIN HumanResources.Department N2 ON N1.DepartmentID = N2.DepartmentID
INNER JOIN HumanResources.[Shift] N3 ON N1.ShiftID = N3.ShiftID
WHERE N2.Name = 'Production'
AND N1.EndDate IS NULL
GROUP BY 1,2
ORDER BY 1,2
```
### Scenario 31
Labels S => size Small
Labels M => size Medium
Labels L => size Large
Labels XL => size Extra Large
Part 1
Determine if the variety of labels is sufficient to cover all alphasized products. For example, since 2XL labels do not exist, no label could be applied to a 2XL product. If a 2XL product existed, the variety of labels would be insufficient
Part 2
Suppose, 1000 labels are available in each size. Calculate the number of additional labels needed to cover all the relevant products in the inventory.
```{sql}
-- Part I
-- Is there a product without dedicated size?
SELECT DISTINCT Size
FROM Production.Product
WHERE ISNUMERIC (Size) = 0
AND Size IS NOT NULL
-- The variety of stickers is appropriate for assignment to the company's products.
-- Part II
SELECT
N1.Size
SUM (N2.Quantity) AS CurrentQuantity,
CASE
WHEN SUM (N2.Quantity) - 1000 < 0
THEN 0 -- not needed
ELSE SUM (N2.Quantity) - 1000 END AS AdditLabelsNeeded
FROM Production.Product N1
INNER JOIN Production.ProductInventory N2 ON N1.ProductID = N2.ProductID
WHERE ISNUMERIC (N1.Size) = 0
AND N1.Size IS NOT NULL
GROUP BY N1.Size
```
### Scenario 52
For each employee, report the latest pay rate and the pay rate prior to the latest rate
- Business ID, Previous rate, Latest rate, percent change
```{sql}
-- need to use self join as I am selecting data from one table
WITH Data AS
(SELECT
BusinessEntityID,
ROW_NUMBER () OVER (PARTITION BY BusinessEntityID
ORDER BY RateChangeDate DESC) AS PayRateNumber,
-- number 1 will show the latest rate
RateChangeDate,
Rate
FROM HumanResources.EmployeePayHistory)
SELECT
N1.BusinessEntityID,
N1.Rate AS LatestRate,
N2.Rate AS RatePrior,
CONVERT (VARCHAR (10),
(N1.Rate - N2.Rate) / N2.Rate * 100) + '%' AS PercentChange
FROM Data N1
LEFT JOIN Data N2 ON N1.BusinessEntityID = N2.BusinessEntityID
AND N2.PayRateNumber = 2 -- I need to filter only index 2 in my second table
WHERE N1.PayRateNumber = 1; -- I need to filter only index 1 in my first table
```
### Scenario 51
Part 1:
Pull a list of the previous excess inventory discounts
```{sql}
SELECT
SpecialOfferID,
Type AS DiscountType,
Description AS ,DiscountDescr,
Category,
StartDate,
EndDate,
DiscountPct
FROM Sales.SpecialOffer
WHERE Type = 'Excess Inventory'
```
Part 2:
Add an additional column to the output from Part 1j. List the number of sales orders in which the discount was utilized.
```{sql}
SELECT a.SpecialOfferID,
SpecialOfferID,
Type AS DiscountType,
Description AS ,DiscountDescr,
Category,
StartDate,
EndDate,
DiscountPct
count(distinct b.SalesOrderID) as NumOrdersDiscApplied
FROM Sales.SpecialOffer a
LEFT JOIN Sales.SalesOrderDetail b
ON a.SpecialOfferID=b.SpecialOfferID
WHERE a.Type='Excess Inventory'
```
### Scenario 50
Create a query about sales order reasons.
When a sales order has only one reason, categorize as "Exclusive Reason".
When a sales order has more than one reason, categorize as "Contributing Reason".
Create a summary count of sales orders by reason name and your newly created ReasonInfluence column (Exclusive Reason and Contributing Reason.)
```{sql}
WITH Reasons AS
(SELECT
N1.SalesOrderID
N2.Name AS ReasonName,
CASE
WHEN COUNT (N3.SalesOrderID) > 1
THEN 'Contributing Reason'
WHEN COUNT (N3.SalesOrderID) = 1
THEN 'Exclusive Reason' END AS ReasonInfluence
FROM Sales.SalesOrderHeaderSalesReason N1
INNER JOIN Sales.SalesReason N2 ON N1.SalesReasonID = N2.SalesReasonID
INNER JOIN Sales.SalesOrderHeaderSalesReason N3 ON N1.SalesOrderID = N3.SalesOrderID
GROUP BY N1.SalesOrderID, N2.Name)
SELECT
ReasonName,
ReasonInfluence,
COUNT (*) AS SalesOrderCount
FROM Reasons
GROUP BY ReasonName, ReasonInfluence
ORDER BY ReasonName, SalesOrderCount DESC
```
### Scenario 49
Display by most recent due dates the top 10% of work orders in which the scrap rate was greater than 3%, ordered by most recent due date.
```{sql}
SELECT TOP 10 PERCENT N1.WorkOrderID,
CAST (N1.DueDate AS DATE) AS DueDate,
N3.Name AS ProdName,
N2.Name AS ScrapReason,
N1.ScrappedQty,
N1.OrderQty,
ROUND (N1.ScrappedQty / CONVERT (FLOAT, N1.OrderQty)* 100, 2) AS PercScrapped
FROM Production.WorkOrder N1
INNER JOIN Production.ScrapReason N2 ON N1.ScrapReasonID = N2.ScrapReasonID
INNER JOIN Production.Product N3 ON N1.ProductID = N3.ProductID
WHERE N1.ScrappedQty / CONVERT (FLOAT, N1.OrderQty) > 0.03
ORDER BY N1.DueDate DESC
```
#Scenario 48
Review sales quota changes from 2006 through 2007. Do not include information about sales people whjo were not assigned sales quotas during the start of 2007 or the end of 2007
```{sql}
-- self join
-- self join table on start date and end date to calculate percentage
SELECT DISTINCT
N1.BusinessEntityID,
N4.LastName AS SalesRepLastName,
N2.SalesQuota AS Yr2006StartQuota, -- 2006
N3.SalesQuota AS Yr2007EndQuota, -- 2007
(N3.SalesQuota - N2.SalesQuota) / N2.SalesQuota * 100 AS %ChangeQuota
FROM Sales.SalesPersonQuotaHistory N1
INNER JOIN Sales.SalesPersonQuotaHistory N2 ON
N1.BusinessEntityID = N2.BusinessEntityID
AND N2.QuotaDate = (SELECT MIN (QuotaDate) -- start of 2006
FROM Sales.SalesPersonQuotaHistory
WHERE YEAR (QuotaDate) = 2006)
INNER JOIN Sales.SalesPersonQuotaHistory N3 ON -- end of 2007
N1.BusinessEntityID = N3.BusinessEntityID
AND N3.QuotaDate = (SELECT MAX (QuotaDate)
FROM Sales.SalesPersonQuotaHistory
WHERE YEAR (QuotaDate) = 2007)
INNER JOIN Person.Person AS N4 ON N1.BusinessEntityID = N4.BusinessEntityID
```
### Scenario 42
Find 5 most successful sale people to mentor the five least successful sales people, create a list of sales people to match with one another
- Success is measured by 2008 revenue
- Dates are based on OrderDate
- Do not consider tax and freight with revenue
- Ignore orders with no SalesPersonID
```{sql}
-- create two columns with row numbers, one desc and one asc, join data based on row number
WITH SalesGrouping AS
(SELECT
SalesPersonID,
SUM (SubTotal) AS SalesTotal,
ROW_NUMBER () OVER (ORDER BY SUM (Subtotal) DESC) AS SalesRankSubTotalDESC,
ROW_NUMBER () OVER (ORDER BY SUM (Subtotal)) AS SalesRankSubTotalASC,
FROM Sales.SalesOrderHeader
WHERE YEAR (OrderDate) = 2008 AND SalesPersonID IS NOT NULL
GROUP BY SalesPersonID)
SELECT TOP 5
N1.SalesPersonID AS SuccessSalesPersonID,
N1.SalesTotal AS SuccessRevenue,
N2.SalesPersonID AS UnsuccessSalesPersonID,
N2.SalesTotal AS UnsuccessRevenue
FROM SalesGrouping N1
INNER JOIN SalesGrouping N2 ON N1.SalesRankSubTotalDESC = N2.SalesRankSubTotalASC
ORDER BY N1.SalesRankSubTotalDESC
```
### Scenario 41
Examine the prevalence of adventure-works.com e-mail addresses throught the company's database.
- Number of e-mail addresses containing the adventure-works.com
- Number of e-mail addresses not containing the adventure-works.com domain
- Total number of e-mail addresses
```{sql}
SELECT
N2.PersonType,
SUM (CASE WHEN N1.EmailAddress LIKE '%adventure-works%' THEN 1 ELSE 0 END) AS AWEmail,
SUM (CASE WHEN N1.EmailAddress NOT LIKE '%adventure-works%' THEN 1 ELSE 0 END) AS NotAWEmail,
COUNT (*) AS Total
FROM Person.EmailAddress N1
INNER JOIN Person.Person N2 ON N1.BusinessEntityID = N2.BusinessEntityID
GROUP BY N2.PersonType
ORDER BY Total DESC
```
### Scenario 40
Calculate the number of sales orders within each of the following revenue ranges:
1. $\$0 - \$100$
2. $\$100 - \$500$
3. $\$500 - \$1000$
4. $\$1000 - \$2500$
5. $\$2500 - \$5000$
6. $\$5000 - \$100008$
7. $\$10000 - \$50000$
8. $\$50000 - \$100000$
9. $\$100000$
for year 2005
```{sql}
SELECT
CASE
WHEN TotalDue < 100 THEN 1
WHEN TotalDue < 500 THEN 2
WHEN TotalDue < 1000 THEN 3
WHEN TotalDue < 2500 THEN 4
WHEN TotalDue < 5000 THEN 5
WHEN TotalDue < 10000 THEN 6
WHEN TotalDue < 50000 THEN 7
WHEN TotalDue < 100000 THEN 8
ELSE 9
END AS SortID,
CASE
WHEN TotalDue < 100 THEN '0 - 100'
WHEN TotalDue < 500 THEN '100 - 500'
WHEN TotalDue < 1000 THEN '500 - 1,000'
WHEN TotalDue < 2500 THEN '1,000 - 2,500'
WHEN TotalDue < 5000 THEN '2,500 - 5,000'
WHEN TotalDue < 10000 THEN '5,000 - 10,000'
WHEN TotalDue < 50000 THEN '10,000 - 50,000'
WHEN TotalDue < 100000 THEN '50,000 - 100,000'
ELSE '> 100,000'
END AS SalesAmountCategory,
COUNT (*) AS Orders
FROM Sales.SalesOrderHeader
WHERE YEAR (OrderDate) = 2005
GROUP BY
CASE
WHEN TotalDue < 100 THEN 1
WHEN TotalDue < 500 THEN 2
WHEN TotalDue < 1000 THEN 3
WHEN TotalDue < 2500 THEN 4
WHEN TotalDue < 5000 THEN 5
WHEN TotalDue < 10000 THEN 6
WHEN TotalDue < 50000 THEN 7
WHEN TotalDue < 100000 THEN 8
ELSE 9
END
,CASE
WHEN TotalDue < 100 THEN '0 - 100'
WHEN TotalDue < 500 THEN '100 - 500'
WHEN TotalDue < 1000 THEN '500 - 1,000'
WHEN TotalDue < 2500 THEN '1,000 - 2,500'
WHEN TotalDue < 5000 THEN '2,500 - 5,000'
WHEN TotalDue < 10000 THEN '5,000 - 10,000'
WHEN TotalDue < 50000 THEN '10,000 - 50,000'
WHEN TotalDue < 100000 THEN '50,000 - 100,000'
ELSE '> 100,000'
END
ORDER BY SortID
```
### Scenario 39
Part 1:
Show the quota, actual sales and percent to quota for each quarter and sales person
```{sql}
WITH SalesQuotaSummary (
SELECT
N1.BusinessEntityID,
N1.QuotaDate,
N1.SalesQuota,
CONVERT (DECIMAL (10,2), SUM (N2.SubTotal)) AS ActualSales,
CONVERT (DECIMAL (10,2), CONVERT (FLOAT, SUM (N2.SubTotal)) / N1.SalesQuota) AS PercToQuota
FROM Sales.SalesPersonQuotaHistory N1
LEFT JOIN Sales.SalesOrderHeader N2 ON N1.BusinessEntityID = N2.SalesPersonID
AND N2.OrderDate >= N1.QuotaDate
AND N2.OrderDate < DATEADD (MONTH, 3, N1.QuotaDate)
GROUP BY 1,2,3
SELECT *
FROM SalesQuotaSummary
ORDER BY BusinessEntityID, QuotaDate
```
Part 2:
Summarize results from Part 1 by sales person, by year
```{sql}
WITH SalesQuotaSummary (
SELECT
N1.BusinessEntityID,
N1.QuotaDate,
N1.SalesQuota,
CONVERT (DECIMAL (10,2), SUM (N2.SubTotal)) AS ActualSales,
CONVERT (DECIMAL (10,2), CONVERT (FLOAT, SUM (N2.SubTotal)) / N1.SalesQuota) AS PercToQuota
FROM Sales.SalesPersonQuotaHistory N1
LEFT JOIN Sales.SalesOrderHeader N2 ON N1.BusinessEntityID = N2.SalesPersonID
AND N2.OrderDate >= N1.QuotaDate
AND N2.OrderDate < DATEADD (MONTH, 3, N1.QuotaDate)
GROUP BY 1,2,3
SELECT
BusinessEntityID,
YEAR (QuotaDate) AS QuotaYear,
SUM (SalesQuota) AS TotalQuota,
SUM (ActualSales) AS TotalSales,
CONVERT (DECIMAL (10,2), CONVERT (FLOAT, SUM (ActualSales)) / SUM (SalesQuota)) AS TotalPercToQuota
CONVERT (DECIMAL (10,2), AVG (PercToQuota)) AS AvgQrtlyPercToQuota
FROM SalesQuotaSummary
ORDER BY BusinessEntityID, QuotaDate
```
### Scenario 38
Calculate the profit margins of bike models
Profit margin is based on the percent difference between ListPrice and StandardCost
Only consider bike models currently sold
```{sql}
SELECT
N1.ProductModelID
N4.Name AS ProductName,
CONVERT (DECIMAL(10,2),
CONVERT (FLOAT, (N1.ListPrice - N1.StandardCost)) / N1.StandardCost) AS ProfitMargin
FROM Production.Product N1
INNER JOIN Production.ProductSubcategory N2 ON N1.ProductSubcategoryID = N2.ProductSubcategoryID
INNER JOIN Production.ProductCategory N3 ON N2.ProductCategoryID = N3.ProductCategoryID
INNER JOIN Production.ProductModel N4 ON N1.ProductModelID = N4.ProductModelID
WHERE N3.Name = 'Bikes'
AND N1.SellEndDate IS NULL
GROUP BY
N1.ProductModelID,
N4.Name,
CONVERT (DECIMAL (10,2) ,CONVERT (FLOAT, (N1.ListPrice - N1.StandardCost)) / N1.StandardCost)
ORDER BY ProfitMargin DESC
```
### Scenario 36
Part 1
Create a query about sales orders that utilized volume discounts. (Total volume discount - the sum of volume discounts applied to the order)