-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sub Query Example 2.sql
90 lines (72 loc) · 1.84 KB
/
Sub Query Example 2.sql
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
Create Table Details.ShopProducts
(
[Id] int identity primary key,
[Name] nvarchar(50),
[Description] nvarchar(250)
)
Create Table Details.ProductSales
(
Id int primary key identity,
ProductId int foreign key references Details.ShopProducts(Id),
UnitPrice int,
QuantitySold int
)
Insert into Details.ShopProducts values ('TV', '52 inch black color LCD TV')
Insert into Details.ShopProducts values ('Laptop', 'Very thin black color acer laptop')
Insert into Details.ShopProducts values ('Desktop', 'HP high performance desktop')
Insert into Details.ProductSales values(3, 450, 5)
Insert into Details.ProductSales values(2, 250, 7)
Insert into Details.ProductSales values(3, 450, 4)
Insert into Details.ProductSales values(3, 450, 9)
SELECT * FROM Details.ShopProducts
SELECT * FROM Details.ProductSales
---- Write a query to retrieve products that are not at all sold?
SELECT
[Id],
[Name],
[Description]
FROM Details.ShopProducts
where Id NOT IN (
SELECT DISTINCT ProductId
FROM Details.ProductSales
)
----- The same can be Done by Join
SELECT
SP.[Id],
[Name],
[Description]
FROM Details.ShopProducts SP
LEFT JOIN Details.ProductSales PS
ON SP.Id = PS.ProductId
WHERE PS.ProductId IS NULL
----- query to retrieve the NAME and TOTALQUANTITY sold
SELECT
[Name],
(SELECT
SUM(QuantitySold)
FROM Details.ProductSales
WHERE ProductId = ShopProducts.Id) AS TotalQuantity
FROM Details.ShopProducts
ORDER BY [Name]
--- Query with an equivalent join
SELECT
[Name],
SUM(QuantitySold) AS TotalQuantity
FROM Details.ShopProducts SP
LEFT JOIN Details.ProductSales PS
ON SP.Id = PS.ProductId
GROUP BY [Name]
ORDER BY [Name]
------ SubQuery in Insert Statement
INSERT INTO [Details].[SalesProducts]
(
ProductId,
ProductName,
Rate
)
SELECT
ProductId,
ProductName,
Rate
FROM [Details].[Products]
WHERE ProductId=1