-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101 SQL PRACTICE QUESTIONS.txt
More file actions
1732 lines (1573 loc) · 49.1 KB
/
101 SQL PRACTICE QUESTIONS.txt
File metadata and controls
1732 lines (1573 loc) · 49.1 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
--Question 1--
SELECT type_desc, Count(*) as CNT
FROM sys.objects
GROUP BY type_desc
ORDER BY 2 desc
--Question 2--
SELECT * FROM sys.tables
SELECT * FROM sys.schemas
SELECT * FROM sys.columns
--2A--
SELECT
count(distinct t.name) AS tables_count,
count(distinct s.schema_id) AS schema_count,
count(distinct c.name) AS columns_count
FROM sys.tables t
LEFT JOIN sys.schemas s
ON t.schema_id = s.schema_id
LEFT JOIN sys.columns c
ON t.object_id = c.object_id
--2B--
SELECT
t.name as TableName,
s.schema_id,
c.name as ColumnName
FROM sys.tables t
LEFT JOIN sys.schemas s
ON t.schema_id = s.schema_id
LEFT JOIN sys.columns c
ON t.object_id = c.object_id
ORDER BY s.schema_id, t.name, c.name
--Question 3--
--3A--
CREATE DATABASE Edited_AdventureWorks2019
USE Edited_AdventureWorks2019
--3B--
SELECT DISTINCT
T.name as TableName,
C.name as ColumnName,
CC.name as CheckConstraint,
CC.definition as ConstraintDefinition
FROM sys.check_constraints CC
INNER JOIN sys.tables T
ON T.object_id = CC.parent_object_id
LEFT JOIN sys.columns C
ON C.column_id = CC.parent_column_id AND C.object_id = CC.parent_object_id
--Question 4--
SELECT
O.name as FK_Name,
S1.name as SchemaName,
T1.name as TableName,
C1.name as ColumnName,
S2.name as ReferencedSchemaName,
T2.name as ReferencedTableName,
C2.name as ReferencedColumnName
FROM sys.foreign_key_columns FKC
INNER JOIN sys.objects O ON O.object_id = FKC.constraint_object_id
INNER JOIN sys.tables T1 ON T1.object_id = FKC.parent_object_id
INNER JOIN sys.tables T2 ON T2.object_id = FKC.referenced_object_id
INNER JOIN sys.columns C1 ON C1.column_id = parent_column_id
AND C1.object_id = T1.object_id
INNER JOIN sys.columns C2 ON C2.column_id = referenced_column_id
AND C2.object_id = T2.object_id
INNER JOIN sys.schemas S1 ON T1.schema_id = S1.schema_id
INNER JOIN sys.schemas S2 ON T2.schema_id = S2.schema_id
--Question 6--
SELECT
s.name as SchemaName,
t.name as TableName,
c.name as ColumnName,
dc.name as DefaultConstraint,
dc.definition as DefaultDefinition
FROM sys.default_constraints dc
INNER JOIN sys.tables t on t.object_id = dc.parent_object_id
INNER JOIN sys.schemas s on s.schema_id = dc.schema_id
INNER JOIN sys.columns c on c.column_id = dc.parent_column_id
AND c.object_id = dc.parent_object_id
--Question 7--
--7A--
SELECT
t.name as TableName,
s.name as SchemaName,
c.name as ColumnName
FROM sys.tables t
LEFT JOIN sys.schemas s
ON t.schema_id = s.schema_id
LEFT JOIN sys.columns c
ON t.object_id = c.object_id
WHERE c.name LIKE '%rate%'
--7B--
SELECT
t.name as TableName,
s.name as SchemaName,
c.name as ColumnName
FROM sys.tables t
LEFT JOIN sys.schemas s
ON t.schema_id = s.schema_id
LEFT JOIN sys.columns c
ON t.object_id = c.object_id
WHERE t.name LIKE '%History%'
--Question 8--
--8A--
SELECT DISTINCT
DATA_TYPE,
count(DATA_TYPE) AS CNT
FROM information_schema.columns
GROUP BY DATA_TYPE
ORDER BY CNT DESC
--8B--
select * FROM information_schema.columns
SELECT
CASE WHEN Character_Maximum_Length is not null THEN 'Character' --how to group with case when and have the titles you want in the column--
WHEN Numeric_Precision is not null THEN 'Numeric'
WHEN Datetime_Precision is not null THEN 'Date'
ELSE null
END AS 'DataTypeGroup',
Count(*) as CNT
FROM Information_Schema.Columns
GROUP BY
CASE WHEN Character_Maximum_Length is not null THEN 'Character'
WHEN Numeric_Precision is not null THEN 'Numeric'
WHEN Datetime_Precision is not null THEN 'Date'
ELSE null
END
ORDER BY count(*) desc
--Question 9--
select * from information_schema.view_column_usage
SELECT
VIEW_NAME,
COUNT(DISTINCT TABLE_NAME) AS TABLES_INVOLVED,
COUNT(DISTINCT COLUMN_NAME) AS COLUMNS_INVOLVED
FROM information_schema.view_column_usage
GROUP BY VIEW_NAME
--Question 10--
Select * From sys.extended_properties
select * from sys.tables
select * from sys.columns
SELECT
t.name AS TableName,
c.name AS ColumnName,
value
FROM sys.extended_properties ext
INNER JOIN sys.tables t
ON t.object_id = ext.major_id
INNER JOIN sys.columns c
ON c.column_id = ext.minor_id AND c.object_id = ext.major_id
WHERE class = 1
--Question 11--
SELECT * FROM HumanResources.Employee
SELECT * FROM Person.Person
--1A--
SELECT COUNT(*) FROM HumanResources.Employee AS EMPLOYEE_COUNT
--1B--
SELECT COUNT(*) FROM HumanResources.Employee AS ACTIVE_EMPLOYEES
WHERE CurrentFlag = 1
--1C--
SELECT FirstName, LastName, JobTitle, PersonType
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
WHERE PersonType = 'SP'
--1D--
SELECT FirstName, LastName, JobTitle, PersonType
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
WHERE PersonType = 'SP' AND JobTitle LIKE '%Sales%'
--Question 12--
--12A--
SELECT FirstName + ' ' + LastName AS FullName, JobTitle, HireDate --concatenate in microsoft sql--
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
WHERE JobTitle = 'Chief Executive Officer'
--12B--
Select
CONCAT(p.FirstName,' ',p.LastName) as FullName
,JobTitle
From HumanResources.Employee e
INNER JOIN Person.Person p
on p.BusinessEntityID = e.BusinessEntityID
Where OrganizationLevel = '1' --who reports to CEO?--
--Question 13--
select * from HumanResources.EmployeeDepartmentHistory
select * from HumanResources.Employee
select * from HumanResources.Department
SELECT FirstName, LastName, JobTitle, HireDate, D.Name, D.GroupName
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
LEFT JOIN HumanResources.EmployeeDepartmentHistory ED
ON E.BusinessEntityID = ED.BusinessEntityID
LEFT JOIN HumanResources.Department D
ON ED.DepartmentID = D.DepartmentID
WHERE FirstName = 'John' AND LastName = 'Evans'
--Question 14--
select * from Purchasing.Vendor
select * from Purchasing.ProductVendor
--14A--
SELECT Name, CreditRating
FROM Purchasing.Vendor
WHERE CreditRating = 1
ORDER BY Name ASC
--14B--
SELECT
CASE WHEN PreferredVendorStatus = 1 THEN 'Preferred' ELSE 'Not Preferred' END AS VendorStatus, --case when for grouping(!)--
COUNT(*) AS VENDOR_COUNT
FROM Purchasing.Vendor
GROUP BY CASE WHEN PreferredVendorStatus = 1 THEN 'Preferred' ELSE 'Not Preferred' END
--14C--
SELECT
CASE WHEN PreferredVendorStatus = '1' THEN 'Preferred' ELSE 'Not Preferred' END AS PreferredStatus,
AVG(CAST(CreditRating as decimal)) AS AvgRating
FROM Purchasing.Vendor
WHERE ActiveFlag = 1
GROUP BY CASE WHEN PreferredVendorStatus = '1' THEN 'Preferred' ELSE 'Not Preferred' END
--14D--
SELECT
COUNT(*) AS VENDORS_ACTIVE_NOTPREFERRED
FROM Purchasing.Vendor
WHERE PreferredVendorStatus = 0 AND ActiveFlag = 1
--Question 15--
--15A--
SELECT
FirstName, LastName, JobTitle, BirthDate, DATEDIFF(YEAR, BirthDate, GETDATE()) AS AGE --calculate age--
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
ORDER BY 5 DESC
--15B--
SELECT
OrganizationLevel, AVG(DATEDIFF(YEAR, BirthDate, GETDATE())) AS AVG_AGE --calculate age--
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
WHERE OrganizationLevel IS NOT NULL
GROUP BY OrganizationLevel
--15C--
Select
OrganizationLevel
,Format(Avg(cast(DATEDIFF(Year,BirthDate,'2014-08-15') as decimal)),'N1') as Age --format: for one decimal place--
,Ceiling(Avg(cast(DATEDIFF(Year,BirthDate,'2014-08-15') as decimal))) as Age --ceiling: to round up--
From HumanResources.Employee
Group by OrganizationLevel
Order by 2 desc
--Question 16--
SELECT * FROM Production.Product
SELECT
Count(*) as ProductCNT,
Count(CASE WHEN MakeFlag = 0 THEN ProductID ELSE null END) AS PurchasedProduct,
Count(CASE WHEN MakeFlag = 1 THEN ProductID ELSE null END) AS MadeInHouse
FROM Production.Product
WHERE FinishedGoodsFlag = 1 AND SellEndDate IS NULL
--Question 17--
select * from Sales.SalesOrderDetail
--17A--
SELECT
CASE WHEN P.MakeFlag = 1 Then 'Manufactured' ELSE 'Purchased' END AS MakeFlag,
format(sum(LineTotal), 'C0') AS LineTotal, --CO: Currency with 0 decimal--
count(distinct SalesOrderID) AS SALES_ORDER_COUNT
FROM Sales.SalesOrderDetail S
LEFT JOIN Production.Product P
ON S.ProductID = P.ProductID
GROUP BY MakeFlag
--17B--
SELECT
SalesOrderID,
format(avg(LineTotal), 'C0') AS LineTotal
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID
ORDER BY SalesOrderID
--Question 18--
select * from Production.TransactionHistory
select * from Production.TransactionHistoryArchive
--18A--
Select
t.name as TableName
,c.name as ColumnName
,ep.value as Definitions
From sys.extended_properties ep
INNER JOIN sys.tables t on t.object_id = ep.major_id
INNER JOIN sys.columns c on c.object_id = ep.major_id
and c.column_id = ep.minor_id
Where class = 1
and t.name in ('TransactionHistory')
--18B--
SELECT * FROM Production.TransactionHistory
UNION
SELECT * FROM Production.TransactionHistoryArchive
--18C--
SELECT
Cast(MIN(TransactionDate) as Date) as FirstDate,
Convert(date,MAX(TransactionDate)) as LastDate
FROM (
SELECT * FROM Production.TransactionHistoryArchive
UNION
SELECT * FROM Production.TransactionHistory) a --subquery in FROM statement(!)--
--18D--
SELECT
TransactionType,
Cast(MIN(TransactionDate) as Date) as FirstDate,
Convert(date,MAX(TransactionDate)) as LastDate
FROM (
SELECT * FROM Production.TransactionHistoryArchive
UNION
SELECT * FROM Production.TransactionHistory) a
GROUP BY TransactionType
--Question 19--
Select
Convert(Date,Min(OrderDate)) as FirstDate
,Convert(Date,Max(OrderDate)) as LastDate
--,Format(Max(OrderDate),'D') as LastDate
from Sales.SalesOrderHeader
--Question 20--
Select
Status
,Convert(date,Min(OrderDate)) as FirstDate --matches the pending status
,Convert(date,Max(OrderDate)) as LastDate
from Purchasing.PurchaseOrderHeader
Group by Status
Select
Convert(date,Min(DueDate)) as FirstDate
,Convert(date,Max(DueDate)) as LastDate
,Convert(date,Min(StartDate)) as FirstStartDate --matches TransactionHistory
,Convert(date,Max(StartDate)) as LastStartDate --matches TransactionHistory
,Convert(date,Min(EndDate)) as FirstEndDate
,Convert(date,Max(EndDate)) as LastEndDate
from Production.WorkOrder
--Question 21--
select * from Person.CountryRegion
select * from Person.StateProvince
select * from Sales.SalesTaxRate
--21A--
SELECT StateProvinceCode, S.Name AS StateName, S.CountryRegionCode, C.Name AS CountryName, TaxRate
FROM Person.StateProvince S
LEFT JOIN Person.CountryRegion C
ON S.CountryRegionCode = C.CountryRegionCode
LEFT JOIN Sales.SalesTaxRate Tax
ON S.StateProvinceID = Tax.StateProvinceID
ORDER BY TaxRate DESC
--21B--
Select * from Sales.SalesTaxRate
Where StateProvinceID in (
Select
sp.StateProvinceID
From Person.StateProvince sp
Inner Join Person.CountryRegion cr on cr.CountryRegionCode = sp.CountryRegionCode
Left Join Sales.SalesTaxRate tr on tr.StateProvinceID = sp.StateProvinceID
Group by sp.StateProvinceID
Having count(*) > 1) --HAVING FUNCTION--
--Question 22--
--22A--
select * from Person.Address
select * from Person.CountryRegion
select * from Person.StateProvince
select * from Person.Person
select * from Person.BusinessEntityAddress
Select
Format(count(p.BusinessEntityID),'N0') as CNT
from Person.Person p
Where PersonType = 'IN'
--22B--
Select
CR.Name as Country
,count(p.BusinessEntityID) as Sort
,Format(count(p.BusinessEntityID),'N0') as CNT
from Person.Person p
Inner Join Person.BusinessEntityAddress bea on bea.BusinessEntityID = p.BusinessEntityID
Inner Join Person.Address a on a.AddressID = bea.AddressID
Inner Join Person.StateProvince sp on sp.StateProvinceID = a.StateProvinceID
Inner Join Person.CountryRegion cr on cr.CountryRegionCode = sp.CountryRegionCode
Where PersonType = 'IN'
Group by cr.Name
Order by 2 desc
--22C SOS--
Select
cr.Name as Country
,Format(count(Distinct p.BusinessEntityID),'N0') as CNT
,Format(Cast(count(Distinct p.BusinessEntityID) as float)
/(Select count(BusinessEntityID) --you need a subquery to take the count of all customers and not by country--
from Person.Person
Where PersonType = 'IN'),'P') as '%ofTotal'
from Person.Person p
Inner Join Person.BusinessEntityAddress bea on bea.BusinessEntityID = p.BusinessEntityID
Inner Join Person.Address a on a.AddressID = bea.AddressID
Inner Join Person.StateProvince sp on sp.StateProvinceID = a.StateProvinceID
Inner Join Person.CountryRegion cr on cr.CountryRegionCode = sp.CountryRegionCode
Where PersonType = 'IN'
Group by cr.Name
Order by 2 desc
--Question 23--
--DECLARE: to store a value in a variable to make use of it later on--
Declare @TotalRetailCustomers Float =
(Select count(BusinessEntityID)
From Person.Person
Where PersonType = 'IN')
Select
cr.Name as Country
,count(Distinct p.BusinessEntityID) as Sort
,Format(count(Distinct p.BusinessEntityID),'N0') as CNT
,Format(Cast(count(Distinct p.BusinessEntityID) as float)
/
@TotalRetailCustomers,'P') as '%ofTotal'
from Person.Person p
Inner Join Person.BusinessEntityAddress bea on bea.BusinessEntityID = p.BusinessEntityID
Inner Join Person.Address a on a.AddressID = bea.AddressID
Inner Join Person.StateProvince sp on sp.StateProvinceID = a.StateProvinceID
Inner Join Person.CountryRegion cr on cr.CountryRegionCode = sp.CountryRegionCode
Where PersonType = 'IN'
Group by cr.Name
Order by 2 desc
--Question 25--
SELECT * FROM Production.Product
SELECT
Product.Name,
Format(ListPrice,'C0') as ListPrice,
Format(StandardCost,'C0') as StandardCost,
Format((ListPrice - StandardCost),'C0') as ProductMargins,
(ListPrice - StandardCost) as Sort
FROM Production.Product
ORDER BY 5 desc
--Question 26--
select * from Sales.SpecialOfferProduct
Select
so.StartDate
,so.EndDate
,so.Type
,so.Category
,so.Description
,so.DiscountPct
,Count(Distinct p.name) as CNT
From Production.Product p
Inner Join Sales.SpecialOfferProduct sop on sop.ProductID = p.ProductID
Inner Join Sales.SpecialOffer so on so.SpecialOfferID = sop.SpecialOfferID
Where ProductModelID = '19'
Group by
so.StartDate
,so.EndDate
,so.Type
,so.Category
,so.Description
,so.DiscountPct
--Question 27--
select I.ProductID, P.Name, sum(Quantity) AS Inventory, ProductModelID
from Production.ProductInventory I
left join Production.Product P
on I.ProductID = P.ProductID
where ProductModelID = '19'
group by I.ProductID, ProductModelID, P.Name
--Question 28--
select * from Sales.SalesReason
select * from Sales.SalesOrderDetail
select * from Sales.SalesOrderHeaderSalesReason
select R.Name, count(D.SalesOrderId) as Count_of_Reason
from Sales.SalesOrderDetail D
left join Sales.SalesOrderHeaderSalesReason H
on D.SalesOrderID = H.SalesOrderID
left join Sales.SalesReason R
on H.SalesReasonID = R.SalesReasonID
group by R.Name
order by 2 DESC
--correct answer:--
Select
sr.Name as Reason
,Count(sohsr.SalesOrderID) as Sort
,Format(Count(sohsr.SalesOrderID),'#,#') as CNT
From Sales.SalesOrderHeaderSalesReason sohsr
Inner Join Sales.SalesReason sr
on sr.SalesReasonID = sohsr.SalesReasonID
Group by
sr.Name
Order by 2 desc
--Question 29--
With CTE as(
Select
soh.SalesOrderID
,count(hsr.SalesOrderID) as CNT
From Sales.SalesOrderHeader soh
LEFT JOIN Sales.SalesOrderHeaderSalesReason hsr on hsr.SalesOrderID = soh.SalesOrderID
Group by soh.SalesOrderID)
Select
CNT
,Count(CNT) as CNTofSalesOrderIDS
From CTE
Group by CNT
--Question 31--
--31A--
select E.BusinessEntityID, E.JobTitle, E.MaritalStatus, E.Gender, E.HireDate, P.EmailAddress
from HumanResources.Employee E
inner join Person.EmailAddress P
on E.BusinessEntityID = P.BusinessEntityID
where JobTitle = 'Chief Executive Officer'
--31B: How to update information(!)--
select * from Person.EmailAddress
UPDATE Person.EmailAddress
SET EmailAddress = 'Ken.Sánchez@adventure-works.com'
WHERE EmailAddress = 'ken0@adventure-works.com'
--Question 34--
SELECT
FirstName,
LastName,
JobTitle,
HireDate,
RANK() OVER (ORDER BY HireDate) AS Seniority, --RANK(!)--
DATEDIFF(DAY, HireDate, '2014-03-03') AS DaysEmployed, --DATEDIFF to subtract 2 dates--
DATEDIFF(MONTH, HireDate, '2014-03-03') AS MonthsEmployed,
DATEDIFF(YEAR, HireDate, '2014-03-03') AS YearsEmployed
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
--Question 35--
--35A--
SELECT
FirstName,
LastName,
JobTitle,
E.BusinessEntityID,
HireDate,
RANK() OVER (ORDER BY HireDate) AS Seniority, --RANK(!)--
DATEDIFF(DAY, HireDate, '2014-03-03') AS DaysEmployed, --DATEDIFF to subtract 2 dates--
DATEDIFF(MONTH, HireDate, '2014-03-03') AS MonthsEmployed,
DATEDIFF(YEAR, HireDate, '2014-03-03') AS YearsEmployed
INTO #Temp1 --put it into a temporary table--
FROM HumanResources.Employee E
LEFT JOIN Person.Person P
ON E.BusinessEntityID = P.BusinessEntityID
--35B--
Select *
From #Temp1
Where BusinessEntityID in ('288','286')
UPDATE #Temp1
SET YearsEmployed = 0
WHERE BusinessEntityID in ('288','286')
--35C--
SELECT
COUNT(*) AS TOTAL_EMP
FROM #Temp1
WHERE MonthsEmployed >= 66
--35D--
SELECT
CASE WHEN YearsEmployed <= 1 THEN 'Employed Less Than 1 Year'
WHEN YearsEmployed <= 3 THEN 'Employed 1-3 Years'
WHEN YearsEmployed <= 6 THEN 'Employed 4-6'
ELSE 'Employed Over 6 Years'
END AS EmploymentCategory, --dont forget to END AS--
COUNT(*) AS EMP_COUNT --add this column to have the counts--
FROM #Temp1
GROUP BY (CASE WHEN YearsEmployed <= 1 THEN 'Employed Less Than 1 Year' --dont forget to group by--
WHEN YearsEmployed <= 3 THEN 'Employed 1-3 Years'
WHEN YearsEmployed <= 6 THEN 'Employed 4-6'
ELSE 'Employed Over 6 Years'
END)
--Question 36--
--36A--
SELECT
DISTINCT [Group]
FROM Sales.SalesTerritory
--36B--
SELECT
T.[Group], --you need to use the [] because Group is a reserved keyword--
FORMAT(SUM(TotalDue), 'C0') AS Total_Due
FROM Sales.SalesTerritory T
LEFT JOIN Sales.SalesOrderHeader H
ON T.TerritoryID = H.TerritoryID
GROUP BY T.[Group]
--36C--
Select
distinct st.Name as RegionName
,Concat(p.FirstName,' ',p.LastName) as CustomerName
,Format(Sum(TotalDue),'C0') as TotalDue
From Sales.SalesTerritory st
Inner Join Sales.SalesOrderHeader soh on soh.TerritoryID = st.TerritoryID
Inner Join Sales.Customer c on c.CustomerID = soh.CustomerID
Inner Join Person.Person p on p.BusinessEntityID = c.PersonID
Group by
st.Name
,Concat(p.FirstName,' ',p.LastName)
--36D--
Select
distinct st.Name as RegionName,
Concat(p.FirstName,' ',p.LastName) as CustomerName,
Format(Sum(TotalDue),'C0') as TotalDue,
ROW_NUMBER () OVER(PARTITION BY st.Name ORDER BY Sum(TotalDue) DESC) AS RowNum
From Sales.SalesTerritory st
Inner Join Sales.SalesOrderHeader soh on soh.TerritoryID = st.TerritoryID
Inner Join Sales.Customer c on c.CustomerID = soh.CustomerID
Inner Join Person.Person p on p.BusinessEntityID = c.PersonID
Group by
st.Name,
Concat(p.FirstName,' ',p.LastName)
--Question 37--
--USING CTE--
WITH RankedCustomers AS (
SELECT
st.Name AS RegionName,
CONCAT(p.FirstName, ' ', p.LastName) AS CustomerName,
FORMAT(SUM(TotalDue), 'C0') AS TotalDue,
ROW_NUMBER() OVER (PARTITION BY st.Name ORDER BY SUM(TotalDue) DESC) AS RowNum
FROM Sales.SalesTerritory st
INNER JOIN Sales.SalesOrderHeader soh ON soh.TerritoryID = st.TerritoryID
INNER JOIN Sales.Customer c ON c.CustomerID = soh.CustomerID
INNER JOIN Person.Person p ON p.BusinessEntityID = c.PersonID
GROUP BY
st.Name,
CONCAT(p.FirstName, ' ', p.LastName)
)
SELECT
RegionName,
CustomerName,
TotalDue,
RowNum
FROM RankedCustomers
WHERE RowNum <= 25
ORDER BY RegionName, RowNum
--USING SUBQUERY--
SELECT *
FROM (
SELECT
st.Name AS RegionName,
CONCAT(p.FirstName, ' ', p.LastName) AS CustomerName,
FORMAT(SUM(TotalDue), 'C0') AS TotalDue,
ROW_NUMBER() OVER (PARTITION BY st.Name ORDER BY SUM(TotalDue) DESC) AS RowNum
FROM Sales.SalesTerritory st
INNER JOIN Sales.SalesOrderHeader soh ON soh.TerritoryID = st.TerritoryID
INNER JOIN Sales.Customer c ON c.CustomerID = soh.CustomerID
INNER JOIN Person.Person p ON p.BusinessEntityID = c.PersonID
GROUP BY
st.Name,
CONCAT(p.FirstName, ' ', p.LastName)
) AS RankedCustomers
WHERE RowNum <= 25
ORDER BY RegionName, RowNum;
--37B--
Select
RegionName,
Format(AVG(TotalDue),'C0') as AvgTotalDue
From (
Select
distinct st.Name as RegionName
,Concat(p.FirstName,' ',p.LastName) as CustomerName
,Sum(TotalDue) as TotalDue
,ROW_NUMBER() Over(Partition by st.Name Order by Sum(TotalDue) desc) as RowNum
From Sales.SalesTerritory st
Inner Join Sales.SalesOrderHeader soh on soh.TerritoryID = st.TerritoryID
Inner Join Sales.Customer c on c.CustomerID = soh.CustomerID
Inner Join Person.Person p on p.BusinessEntityID = c.PersonID
Group by
st.Name
,Concat(p.FirstName,' ',p.LastName))a
Group by
RegionName
Order by 2 desc
--Question 38--
select * from Sales.SalesOrderHeader
--38A--
select
format(sum(Freight), 'N0') as total_freight
from Sales.SalesOrderHeader
--38B--
select
YEAR(ShipDate) as ShipYear,
format(sum(Freight), 'N0') as total_freight
from Sales.SalesOrderHeader
group by YEAR(ShipDate)
order by YEAR(ShipDate), total_freight DESC
--38C--
select
YEAR(ShipDate) as ShipYear,
SalesOrderID,
format(avg(Freight), 'N0') as avg_freight
from Sales.SalesOrderHeader
group by YEAR(ShipDate), SalesOrderID
order by YEAR(ShipDate), avg_freight DESC
--Question 40--
--40A--
select
YEAR(ShipDate) as ShipYear,
MONTH(ShipDate) as ShipMonth,
DateName(month,ShipDate) as ShipMonthName,
format(sum(Freight), 'N0') as total_freight,
format(avg(Freight), 'N0') as avg_freight
from Sales.SalesOrderHeader
group by YEAR(ShipDate), MONTH(ShipDate), DateName(month,ShipDate)
order by YEAR(ShipDate), MONTH(ShipDate), DateName(month,ShipDate), total_freight DESC
--40b--
Select *
,Format(Sum(TotalFreight) Over (Order by ShipYear,ShipMonth),'C0') as RunningTotal
From(
Select
Year(ShipDate) as ShipYear
,Month(ShipDate) as ShipMonth
,DateName(month,ShipDate) as 'MonthName'
,Sum(Freight) as TotalFreight
,Avg(Freight) as AvgFreight
From Sales.SalesOrderHeader
Group by
Year(ShipDate)
,Month(ShipDate)
,DateName(month,ShipDate))a
--Question 41--
Select
soh.SalesOrderID
,CONCAT(cp.FirstName,' ',cp.LastName) as 'CustomerName'
,Case When cp.PersonType = 'IN' Then 'Inividual Customer'
When cp.PersonType = 'SC' Then 'Store Contact'
Else Null End as 'PersonType'
,Case When CONCAT(sp.FirstName,' ',sp.LastName) = ' '
Then 'No Sales Person'
Else CONCAT(sp.FirstName,' ',sp.LastName) End as 'SalesPerson'
,OrderDate
,Sum(OrderQTY) as ProductQty
From Sales.SalesOrderHeader soh
Inner Join Sales.SalesOrderDetail sod on soh.SalesOrderID = sod.SalesOrderID
Inner Join Sales.Customer c on c.CustomerID = soh.CustomerID
Inner Join Person.Person cp on cp.BusinessEntityID = c.PersonID
Left Join Person.Person sp on sp.BusinessEntityID = soh.SalesPersonID
Group by
soh.SalesOrderID
,CONCAT(cp.FirstName,' ',cp.LastName)
,cp.PersonType
,OrderDate
,CONCAT(sp.FirstName,' ',sp.LastName)
--Question 42--
WITH CTE AS (
SELECT
soh.SalesOrderID,
CONCAT(
cp.FirstName, ' ', cp.LastName, ' is a(n) ',
CASE
WHEN cp.PersonType = 'IN' THEN 'Individual Customer'
WHEN cp.PersonType = 'SC' THEN 'Store Contact'
ELSE 'Unknown'
END,
' and purchased ',
CAST(SUM(OrderQTY) AS VARCHAR(10)), ' Product(s) from ',
CASE
WHEN CONCAT(sp.FirstName, ' ', sp.LastName) = ' ' THEN 'No Sales Person'
ELSE CONCAT(sp.FirstName, ' ', sp.LastName)
END,
' on ',
CONVERT(VARCHAR(10), OrderDate, 120)
) AS Comment
FROM Sales.SalesOrderHeader soh
INNER JOIN Sales.SalesOrderDetail sod ON soh.SalesOrderID = sod.SalesOrderID
INNER JOIN Sales.Customer c ON c.CustomerID = soh.CustomerID
INNER JOIN Person.Person cp ON cp.BusinessEntityID = c.PersonID
LEFT JOIN Person.Person sp ON sp.BusinessEntityID = soh.SalesPersonID
GROUP BY
soh.SalesOrderID,
cp.FirstName,
cp.LastName,
cp.PersonType,
OrderDate,
sp.FirstName,
sp.LastName )
--Question 43--
select * from Sales.SalesPersonQuotaHistory
select * from Sales.SalesPerson
--43A--
select
count(*) as count
from
(select
BusinessEntityID
from
Sales.SalesPerson
where SalesYTD>SalesQuota) as t
--43B--
select
count(*) as count
from
Sales.SalesPerson
where
SalesYTD>
(select format(avg(SalesYTD), 'N0') from Sales.SalesPerson)
--Question 44--
CREATE PROCEDURE StoredProcedure
AS
BEGIN
SELECT
BusinessEntityID,
Format(CommissionPct,'p') as CommissionPct,
Format(SalesYTD,'$#,#') as SalesYTD,
Format((CommissionPct * SalesYTD),'$#,#') as Commission,
Format(Bonus,'$#,#') as Bonus
FROM Sales.SalesPerson
END
EXEC StoredProcedure
Drop Procedure StoredProcedure
--Question 45--
Create Procedure Sales_Report_YTD
@BusinessEntityID int
as (
Select
BusinessEntityID
,Format(CommissionPct,'p') as CommissionPct
,Format(SalesYTD,'$#,#') as SalesYTD
,Format((CommissionPct * SalesYTD),'$#,#') as Commission
,Format(Bonus,'$#,#') as Bonus
From Sales.SalesPerson
Where BusinessEntityID = @BusinessEntityID)
Exec Sales_Report_YTD @BusinessEntityID = '279'
Drop Procedure Sales_Report_YTD
--Question 46--
select * from Purchasing.Vendor
--46A&B--
Select
CASE WHEN CreditRating = 1 THEN 'Superior'
WHEN CreditRating = 2 THEN 'Excellent'
WHEN CreditRating = 3 THEN 'Above Average'
WHEN CreditRating = 4 THEN 'Average'
ELSE 'Below Average'
END AS CreditRatingCategory,
Count(name) as CNT
From Purchasing.Vendor
Group by CreditRating
--46C--
--CHOOSE FUNCTION: The CHOOSE function in SQL Server returns an item from a list, based on its position (index). It s useful for mapping numeric values to descriptive labels.--
Select
Choose(CreditRating
,'Superior'
,'Excellent'
,'Above Average'
,'Average'
,'Below Average') as CreditRating
,Count(name) as CNT
From Purchasing.Vendor
Group by CreditRating
--Question 47--
--CASE WHEN--
Select
CASE WHEN CreditRating = 1 THEN 'Approved'
ELSE 'Not Approved'
END AS CreditRatingApprovals,
Count(name) as CNT
From Purchasing.Vendor
Group by (CASE WHEN CreditRating = 1 THEN 'Approved' ELSE 'Not Approved' END)
--CHOOSE--
Select
CHOOSE(CreditRating,
'Approved',
'Not Approved',
'Not Approved',
'Not Approved',
'Not Approved') AS CreditRatingApprovals,
Count(name) as CNT
From Purchasing.Vendor
Group by (CHOOSE(CreditRating,
'Approved',
'Not Approved',
'Not Approved',
'Not Approved',
'Not Approved'))
--IIF--
Select
IIF(CreditRating = 1
,'Approved'
,'Not Approved') as CreditRating
,Count(name) as CNT
From Purchasing.Vendor
Group by
IIF(CreditRating = 1
,'Approved'
,'Not Approved')
--Question 51--
Select
t.name as TableName
,Max(p.rows) as RowCNT
,Sum(u.total_pages * 8) as TotalAllocated_kb
,Sum(u.used_pages * 8) as Used_kb
,(Sum(u.total_pages * 8) - Sum(u.used_pages * 8)) as Unused_kb
From sys.allocation_units u
Inner Join sys.partitions p on p.hobt_id = u.container_id
Inner Join sys.tables t on t.object_id = p.object_id
Group by t.name
--Question 52--
Create View vDatabaseAllocation
As
(SELECT
t.name as TableName
,Max(p.rows) as RowCNT
,Sum(u.total_pages) * 8 as TotalAllocated_kb
,Sum(u.used_pages) * 8 as Used_kb
,(Sum(u.total_pages) * 8) - (Sum(u.used_pages) * 8) as Unused_kb
,Case When Cast((Sum(u.total_pages) * 8) - (Sum(u.used_pages) * 8) as decimal)
/nullif(Sum(u.total_pages)*8,0) < .10
Then 1 Else 0 End as Flg
FROM sys.allocation_units AS u
Inner Join sys.partitions AS p ON u.container_id = p.hobt_id
Inner Join sys.tables AS t ON p.object_id = t.object_id
GROUP BY t.name)
select * from vDatabaseAllocation
--Question 54--
Select
Format(Sum(TotalDue)
/ Count(Distinct OrderDate),'C0') as AvgTotalDue
From Sales.SalesOrderHeader
Where (DATEPART(MM, OrderDate) = 7)
AND (DATEPART(DD, OrderDate) = 4)
--Quetion 55--
SELECT
YEAR(DueDate) AS Year_Date,
DATENAME(weekday, DueDate) AS DayOfWeek_Date,
FORMAT(SUM(TotalDue)/ COUNT(DISTINCT OrderDate),'C0') AS AvgTotalDue
INTO #Temp1
FROM Sales.SalesOrderHeader
WHERE (DATEPART(MM, OrderDate) = 7)
AND (DATEPART(DD, OrderDate) = 4)
GROUP BY YEAR(DueDate), DATENAME(weekday, DueDate)
SELECT * FROM #Temp1;
--56--
SELECT