UNPIVOT example


1. Two inventory metrics for each product as rows, rather than columns, so you have a single 'MetricType' column (e.g., 'UnitsInStock', 'UnitsOnOrder') and a single 'MetricValue' column.

SQL Server Query 1

            
 SELECT  
ProductName,
MetricType, -- New column for the name of the original column (e.g., 'UnitsInStock')
MetricValue -- New column for the value from the original column (e.g., 17, 0)
FROM
(
-- Source data for UNPIVOT
SELECT
ProductID,
ProductName,
UnitsInStock,
UnitsOnOrder
FROM
Products
-- Optional: Filter products if needed
WHERE Discontinued = 0 AND UnitsInStock > 0 AND ProductID < 30
) AS SourceData
UNPIVOT
(
MetricValue FOR MetricType IN (UnitsInStock, UnitsOnOrder) -- Define what to unpivot
) AS UnpivotTable
ORDER BY
ProductName, MetricType;

Create SQL query with SqlQueryBuilder 1

            
 var (sql1, parameters1) = new SqlQueryBuilder()  
.Select()
.Columns("ProductName", "MetricType", "MetricValue")
.From(new SqlQueryBuilder().Select()
.Columns("ProductID","ProductName","UnitsInStock","UnitsOnOrder")
.From("Products")
.Where(new Where(new Column("Discontinued").Equale(0))
.AND(new Column("UnitsInStock").GreaterThan(0))
.AND(new Column("ProductID").LessThan(30))), "SourceTable"
)
.UnPivot(new UnPivot(new Column("MetricValue"))
.For(new Column("MetricType")).IN("UnitsInStock", "UnitsOnOrder")
.TableName(new Table("UnpivotTable"))
)
.OrderBy(new OrderBy().SetColumnAscending("ProductName")
.SetColumnAscending("MetricType"))
.Build();

Query build by SqlQueryBuilder 1

            
SELECT ProductName,
       MetricType,
       MetricValue
FROM (SELECT ProductID,
             ProductName,
             UnitsInStock,
             UnitsOnOrder
      FROM Products
      WHERE Discontinued = @pMAIN_2507200206539685980
            AND UnitsInStock > @pMAIN_2507200206539685981
            AND ProductID < @pMAIN_2507200206539685982) AS SourceTable UNPIVOT (MetricValue FOR MetricType IN (UnitsInStock, UnitsOnOrder)) AS UnpivotTable
ORDER BY ProductName ASC, MetricType ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200206539685980 0
@pMAIN_2507200206539685981 0
@pMAIN_2507200206539685982 30

Query Results 1:

  ProductName MetricType MetricValue
1 Aniseed Syrup UnitsInStock 13
2 Aniseed Syrup UnitsOnOrder 70
3 Carnarvon Tigers UnitsInStock 42
4 Carnarvon Tigers UnitsOnOrder 0
5 Chai UnitsInStock 39
6 Chai UnitsOnOrder 0
7 Chang UnitsInStock 17
8 Chang UnitsOnOrder 40
9 Chef Anton's Cajun Seasoning UnitsInStock 53
10 Chef Anton's Cajun Seasoning UnitsOnOrder 0
11 Genen Shouyu UnitsInStock 39
12 Genen Shouyu UnitsOnOrder 0
13 Grandma's Boysenberry Spread UnitsInStock 120
14 Grandma's Boysenberry Spread UnitsOnOrder 0
15 Gumbär Gummibärchen UnitsInStock 15
16 Gumbär Gummibärchen UnitsOnOrder 0
17 Gustaf's Knäckebröd UnitsInStock 104
18 Gustaf's Knäckebröd UnitsOnOrder 0
19 Ikura UnitsInStock 31
20 Ikura UnitsOnOrder 0
21 Konbu UnitsInStock 24
22 Konbu UnitsOnOrder 0
23 Northwoods Cranberry Sauce UnitsInStock 6
24 Northwoods Cranberry Sauce UnitsOnOrder 0
25 NuNuCa Nuß-Nougat-Creme UnitsInStock 76
26 NuNuCa Nuß-Nougat-Creme UnitsOnOrder 0
27 Pavlova UnitsInStock 29
28 Pavlova UnitsOnOrder 0
29 Queso Cabrales UnitsInStock 22
30 Queso Cabrales UnitsOnOrder 30
31 Queso Manchego La Pastora UnitsInStock 86
32 Queso Manchego La Pastora UnitsOnOrder 0
33 Schoggi Schokolade UnitsInStock 49
34 Schoggi Schokolade UnitsOnOrder 0
35 Sir Rodney's Marmalade UnitsInStock 40
36 Sir Rodney's Marmalade UnitsOnOrder 0
37 Sir Rodney's Scones UnitsInStock 3
38 Sir Rodney's Scones UnitsOnOrder 40
39 Teatime Chocolate Biscuits UnitsInStock 25
40 Teatime Chocolate Biscuits UnitsOnOrder 0
41 Tofu UnitsInStock 35
42 Tofu UnitsOnOrder 0
43 Tunnbröd UnitsInStock 61
44 Tunnbröd UnitsOnOrder 0
45 Uncle Bob's Organic Dried Pears UnitsInStock 15
46 Uncle Bob's Organic Dried Pears UnitsOnOrder 0


2. Prepare the source data with distinct columns for sales and orders

SQL Server Query 2

            
 -- Step 1: Prepare the source data with distinct columns for sales and orders  
-- This subquery generates the data *before* unpivoting.
-- The crucial part is ensuring Sales and Orders are of compatible types.
WITH ProductYearlySummary AS (
SELECT
P.ProductName,
CAST(SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) AS DECIMAL(18, 2)) AS TotalSales,
CAST(COUNT(DISTINCT O.OrderID) AS DECIMAL(18, 2)) AS TotalOrders -- FIX: CAST TotalOrders to DECIMAL
-- We cast TotalOrders to DECIMAL(18,2) to match the type of TotalSales,
-- assuming TotalSales is also a DECIMAL or MONEY type.
FROM
[Order Details] AS OD
JOIN Products AS P ON OD.ProductID = P.ProductID
JOIN Orders AS O ON OD.OrderID = O.OrderID
WHERE
YEAR(O.OrderDate) = 1997 -- Example: Focus on a single year
GROUP BY
P.ProductName
)
-- Step 2: Perform the UNPIVOT operation
SELECT
ProductName,
MetricType, -- Will contain 'TotalSales' or 'TotalOrders'
MetricValue -- Will contain the corresponding numeric value
FROM
ProductYearlySummary
UNPIVOT
(
MetricValue FOR MetricType IN (TotalSales, TotalOrders) -- These must be type-compatible
) AS UnpivotTable
ORDER BY
ProductName, MetricType;

Create SQL query with SqlQueryBuilder 2

            
 var (sql2, parameters2) = new SqlQueryBuilder()  
.WithCTETable(new Table("ProductYearlySummary"), new SqlQueryBuilder().Select()
.Column("P.ProductName")
.Column(new CAST(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")
.MULTIPLY().StartBracket(1).SUBTRACT(new Column("OD.Discount")).EndBracket()),
SqlDataType.DECIMAL, new Tuple<int, int>(18,2)), "TotalSales")
.Column(new CAST(new COUNT(new Column("O.OrderID"), true), SqlDataType.DECIMAL, new Tuple<int,int>(18,2)), "TotalOrders")
.From("[Order Details]", "OD")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("Products", "P")
.On(new Column("OD.ProductID").Equale(new Column("P.ProductID"))),
new INNERJOIN().TableName("Orders","O")
.On(new Column("OD.OrderID").Equale(new Column("O.OrderID")))
})
.Where(new Where(new YEAR(new Column("O.OrderDate")).Equale(1997)))
.GroupBy(new GroupBy("P.ProductName"))
)
.Select()
.Columns("ProductName", "MetricType", "MetricValue")
.From("ProductYearlySummary")
.UnPivot(new UnPivot(new Column("MetricValue"))
.For(new Column("MetricType"))
.IN("TotalSales","TotalOrders")
.TableName(new Table("UnpivotTable")))
.OrderBy(new OrderBy().SetColumnAscending("ProductName")
.SetColumnAscending("MetricType"))
.Build();

Query build by SqlQueryBuilder 2

            
WITH ProductYearlySummary
AS (SELECT P.ProductName,
           CAST (SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200206539776850 - OD.Discount)) AS DECIMAL (18, 2)) AS TotalSales,
           CAST (COUNT(DISTINCT O.OrderID) AS DECIMAL (18, 2)) AS TotalOrders
    FROM [Order Details] AS OD
         INNER JOIN
         Products AS P
         ON OD.ProductID = P.ProductID
         INNER JOIN
         Orders AS O
         ON OD.OrderID = O.OrderID
    WHERE YEAR(O.OrderDate) = @pMAIN_2507200206539776851
    GROUP BY P.ProductName)
SELECT ProductName,
       MetricType,
       MetricValue
FROM ProductYearlySummary UNPIVOT (MetricValue FOR MetricType IN (TotalSales, TotalOrders)) AS UnpivotTable
ORDER BY ProductName ASC, MetricType ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200206539776850 1
@pMAIN_2507200206539776851 1997

Query Results 2:

  ProductName MetricType MetricValue
1 Alice Mutton TotalOrders 18
2 Alice Mutton TotalSales 17604
3 Aniseed Syrup TotalOrders 7
4 Aniseed Syrup TotalSales 1724
5 Boston Crab Meat TotalOrders 25
6 Boston Crab Meat TotalSales 9814
7 Camembert Pierrot TotalOrders 21
8 Camembert Pierrot TotalSales 20505
9 Carnarvon Tigers TotalOrders 12
10 Carnarvon Tigers TotalSales 15950
11 Chai TotalOrders 16
12 Chai TotalSales 4887
13 Chang TotalOrders 18
14 Chang TotalSales 7038
15 Chartreuse verte TotalOrders 13
16 Chartreuse verte TotalSales 4475
17 Chef Anton's Cajun Seasoning TotalOrders 10
18 Chef Anton's Cajun Seasoning TotalSales 5214
19 Chef Anton's Gumbo Mix TotalOrders 2
20 Chef Anton's Gumbo Mix TotalSales 373
21 Chocolade TotalOrders 5
22 Chocolade TotalSales 1282
23 Côte de Blaye TotalOrders 10
24 Côte de Blaye TotalSales 49198
25 Escargots de Bourgogne TotalOrders 7
26 Escargots de Bourgogne TotalSales 2076
27 Filo Mix TotalOrders 15
28 Filo Mix TotalSales 2124
29 Flotemysost TotalOrders 21
30 Flotemysost TotalSales 8438
31 Geitost TotalOrders 16
32 Geitost TotalSales 786
33 Genen Shouyu TotalOrders 4
34 Genen Shouyu TotalSales 1474
35 Gnocchi di nonna Alice TotalOrders 33
36 Gnocchi di nonna Alice TotalSales 32604
37 Gorgonzola Telino TotalOrders 26
38 Gorgonzola Telino TotalSales 7300
39 Grandma's Boysenberry Spread TotalOrders 2
40 Grandma's Boysenberry Spread TotalSales 2500
41 Gravad lax TotalOrders 2
42 Gravad lax TotalSales 629
43 Guaraná Fantástica TotalOrders 19
44 Guaraná Fantástica TotalSales 1630
45 Gudbrandsdalsost TotalOrders 18
46 Gudbrandsdalsost TotalSales 13062
47 Gula Malacca TotalOrders 15
48 Gula Malacca TotalSales 6737
49 Gumbär Gummibärchen TotalOrders 19
50 Gumbär Gummibärchen TotalSales 10443
51 Gustaf's Knäckebröd TotalOrders 9
52 Gustaf's Knäckebröd TotalSales 4233
53 Ikura TotalOrders 19
54 Ikura TotalSales 9935
55 Inlagd Sill TotalOrders 15
56 Inlagd Sill TotalSales 6894
57 Ipoh Coffee TotalOrders 11
58 Ipoh Coffee TotalSales 11069
59 Jack's New England Clam Chowder TotalOrders 21
60 Jack's New England Clam Chowder TotalSales 4957
61 Konbu TotalOrders 11
62 Konbu TotalSales 812
63 Lakkalikööri TotalOrders 19
64 Lakkalikööri TotalSales 7379
65 Laughing Lumberjack Lager TotalOrders 4
66 Laughing Lumberjack Lager TotalSales 910
67 Longlife Tofu TotalOrders 6
68 Longlife Tofu TotalSales 1000
69 Louisiana Fiery Hot Pepper Sauce TotalOrders 18
70 Louisiana Fiery Hot Pepper Sauce TotalSales 9373
71 Louisiana Hot Spiced Okra TotalOrders 6
72 Louisiana Hot Spiced Okra TotalSales 2958
73 Manjimup Dried Apples TotalOrders 19
74 Manjimup Dried Apples TotalSales 24570
75 Mascarpone Fabioli TotalOrders 5
76 Mascarpone Fabioli TotalSales 2668
77 Maxilaku TotalOrders 9
78 Maxilaku TotalSales 3128
79 Mishi Kobe Niku TotalOrders 4
80 Mishi Kobe Niku TotalSales 6935
81 Mozzarella di Giovanni TotalOrders 16
82 Mozzarella di Giovanni TotalSales 11602
83 Nord-Ost Matjeshering TotalOrders 16
84 Nord-Ost Matjeshering TotalSales 6034
85 Northwoods Cranberry Sauce TotalOrders 5
86 Northwoods Cranberry Sauce TotalSales 4260
87 NuNuCa Nuß-Nougat-Creme TotalOrders 6
88 NuNuCa Nuß-Nougat-Creme TotalSales 1692
89 Original Frankfurter grüne Soße TotalOrders 17
90 Original Frankfurter grüne Soße TotalSales 4761
91 Outback Lager TotalOrders 17
92 Outback Lager TotalSales 5468
93 Pâté chinois TotalOrders 16
94 Pâté chinois TotalSales 7832
95 Pavlova TotalOrders 22
96 Pavlova TotalSales 8663
97 Perth Pasties TotalOrders 15
98 Perth Pasties TotalSales 10661
99 Queso Cabrales TotalOrders 21
100 Queso Cabrales TotalSales 6911
101 Queso Manchego La Pastora TotalOrders 7
102 Queso Manchego La Pastora TotalSales 8335
103 Raclette Courdavault TotalOrders 31
104 Raclette Courdavault TotalSales 35775
105 Ravioli Angelo TotalOrders 8
106 Ravioli Angelo TotalSales 2156
107 Rhönbräu Klosterbier TotalOrders 25
108 Rhönbräu Klosterbier TotalSales 4485
109 Röd Kaviar TotalOrders 11
110 Röd Kaviar TotalSales 3517
111 Rogede sild TotalOrders 9
112 Rogede sild TotalSales 3355
113 Rössle Sauerkraut TotalOrders 17
114 Rössle Sauerkraut TotalSales 13948
115 Sasquatch Ale TotalOrders 8
116 Sasquatch Ale TotalSales 2107
117 Schoggi Schokolade TotalOrders 4
118 Schoggi Schokolade TotalSales 10974
119 Scottish Longbreads TotalOrders 16
120 Scottish Longbreads TotalSales 4157
121 Singaporean Hokkien Fried Mee TotalOrders 16
122 Singaporean Hokkien Fried Mee TotalSales 5408
123 Sir Rodney's Marmalade TotalOrders 4
124 Sir Rodney's Marmalade TotalSales 7314
125 Sir Rodney's Scones TotalOrders 23
126 Sir Rodney's Scones TotalSales 5273
127 Sirop d'érable TotalOrders 13
128 Sirop d'érable TotalSales 9091
129 Spegesild TotalOrders 14
130 Spegesild TotalSales 2981
131 Steeleye Stout TotalOrders 16
132 Steeleye Stout TotalSales 5274
133 Tarte au sucre TotalOrders 22
134 Tarte au sucre TotalSales 21638
135 Teatime Chocolate Biscuits TotalOrders 21
136 Teatime Chocolate Biscuits TotalSales 2986
137 Thüringer Rostbratwurst TotalOrders 15
138 Thüringer Rostbratwurst TotalSales 34755
139 Tofu TotalOrders 15
140 Tofu TotalSales 6234
141 Tourtière TotalOrders 22
142 Tourtière TotalSales 3184
143 Tunnbröd TotalOrders 10
144 Tunnbröd TotalSales 2288
145 Uncle Bob's Organic Dried Pears TotalOrders 10
146 Uncle Bob's Organic Dried Pears TotalSales 9186
147 Valkoinen suklaa TotalOrders 5
148 Valkoinen suklaa TotalSales 2173
149 Vegie-spread TotalOrders 7
150 Vegie-spread TotalSales 6899
151 Wimmers gute Semmelknödel TotalOrders 14
152 Wimmers gute Semmelknödel TotalSales 8056
153 Zaanse koeken TotalOrders 15
154 Zaanse koeken TotalSales 2930


3. UNPIVOTing Already Aggregated Columns (from a subquery/CTE)

SQL Server Query 3

            
 -- UNPIVOTing Already Aggregated Columns (from a subquery/CTE)  
-- Step 1: Aggregate data in a subquery/CTE
WITH SalesAndOrdersByYear AS (
SELECT
P.ProductName,
-- Aggregated columns here:
CAST(SUM(CASE WHEN YEAR(O.OrderDate) = 1996 THEN OD.Quantity * OD.UnitPrice END) AS DECIMAL(18,2)) AS Sales1996,
CAST(COUNT(DISTINCT CASE WHEN YEAR(O.OrderDate) = 1996 THEN O.OrderID END) AS DECIMAL(18,2)) AS Orders1996,
CAST(SUM(CASE WHEN YEAR(O.OrderDate) = 1997 THEN OD.Quantity * OD.UnitPrice END) AS DECIMAL(18,2)) AS Sales1997,
CAST(COUNT(DISTINCT CASE WHEN YEAR(O.OrderDate) = 1997 THEN O.OrderID END) AS DECIMAL(18,2)) AS Orders1997
FROM
Products AS P
JOIN [Order Details] AS OD ON P.ProductID = OD.ProductID
JOIN Orders AS O ON OD.OrderID = O.OrderID
GROUP BY
P.ProductName
)
-- Step 2: UNPIVOT the aggregated columns
SELECT
ProductName,
YearAndMetric, -- Will be like 'Sales1996', 'Orders1996'
MetricValue -- Will contain the actual aggregated number
FROM
SalesAndOrdersByYear
UNPIVOT
(
MetricValue FOR YearAndMetric IN (
Sales1996, -- This was an aggregated column from the CTE
Orders1996, -- This was an aggregated column from the CTE
Sales1997, -- This was an aggregated column from the CTE
Orders1997 -- This was an aggregated column from the CTE
)
) AS UnpivotResult
WHERE
MetricValue IS NOT NULL -- Exclude products/years with no data
ORDER BY
ProductName, YearAndMetric;

Create SQL query with SqlQueryBuilder 3

            
 var (sql3, parameters3) = new SqlQueryBuilder()  
.WithCTETable(new Table("SalesAndOrdersByYear"), new SqlQueryBuilder()
.Select()
.Column("P.ProductName")
.Column(new CAST(new SUM(new CASE()
.When(new YEAR(new Column("O.OrderDate")).Equale(1996))
.Then(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")).End()), SqlDataType.DECIMAL,
new Tuple<int, int>(18, 2)), "Sales1996")
.Column(new CAST(new COUNT(new CASE()
.When(new YEAR(new Column("O.OrderDate")).Equale("1996")).Then(new Column("O.OrderID")).End(), true),
SqlDataType.DECIMAL, new Tuple<int,int>(18, 2)), "Orders1996")
.Column(new CAST(new SUM(new CASE()
.When(new YEAR(new Column("O.OrderDate")).Equale(1997)).Then(
new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")).End()), SqlDataType.DECIMAL,
new Tuple<int,int>(18, 2)), "Sales1997")
.Column(new CAST(new COUNT(new CASE()
.When(new YEAR(new Column("O.OrderDate")).Equale(1997)).Then(new Column("O.OrderID")).End(), true),
SqlDataType.DECIMAL, new Tuple<int, int>(18, 2)), "Orders1997")
.From("Products", "P")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("[Order Details]", "OD")
.On(new Column("P.ProductID").Equale(new Column("OD.ProductID"))),
new INNERJOIN().TableName("Orders", "O")
.On(new Column("OD.OrderID").Equale(new Column("O.OrderID")))
})
.GroupBy(new GroupBy("P.ProductName"))
)
.Select()
.Columns("ProductName", "YearAndMetric", "MetricValue")
.From("SalesAndOrdersByYear")
.UnPivot(new UnPivot(new Column("MetricValue"))
.For(new Column("YearAndMetric"))
.IN("Sales1996","Orders1996","Sales1997","Orders1997")
.TableName(new Table("UnpivotResult")))
.Where(new Where(new IS_NOT_NULL(new Column("MetricValue"))))
.OrderBy(new OrderBy().SetColumnAscending("ProductName")
.SetColumnAscending("YearAndMetric"))
.Build();

Query build by SqlQueryBuilder 3

            
WITH SalesAndOrdersByYear
AS (SELECT P.ProductName,
           CAST (SUM(CASE WHEN YEAR(O.OrderDate) = @pMAIN_2507200206539963120 THEN OD.Quantity * OD.UnitPrice END) AS DECIMAL (18, 2)) AS Sales1996,
           CAST (COUNT(DISTINCT CASE WHEN YEAR(O.OrderDate) = @pMAIN_2507200206539963121 THEN O.OrderID END) AS DECIMAL (18, 2)) AS Orders1996,
           CAST (SUM(CASE WHEN YEAR(O.OrderDate) = @pMAIN_2507200206539963122 THEN OD.Quantity * OD.UnitPrice END) AS DECIMAL (18, 2)) AS Sales1997,
           CAST (COUNT(DISTINCT CASE WHEN YEAR(O.OrderDate) = @pMAIN_2507200206539963123 THEN O.OrderID END) AS DECIMAL (18, 2)) AS Orders1997
    FROM Products AS P
         INNER JOIN
         [Order Details] AS OD
         ON P.ProductID = OD.ProductID
         INNER JOIN
         Orders AS O
         ON OD.OrderID = O.OrderID
    GROUP BY P.ProductName)
SELECT ProductName,
       YearAndMetric,
       MetricValue
FROM SalesAndOrdersByYear UNPIVOT (MetricValue FOR YearAndMetric IN (Sales1996, Orders1996, Sales1997, Orders1997)) AS UnpivotResult
WHERE MetricValue IS NOT NULL
ORDER BY ProductName ASC, YearAndMetric ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200206539963120 1996
@pMAIN_2507200206539963121 1996
@pMAIN_2507200206539963122 1997
@pMAIN_2507200206539963123 1997

Query Results 3:

  ProductName MetricType MetricValue
1 Alice Mutton 8
2 Alice Mutton 18
3 Alice Mutton 7300
4 Alice Mutton 19718
5 Aniseed Syrup 1
6 Aniseed Syrup 7
7 Aniseed Syrup 240
8 Aniseed Syrup 1760
9 Boston Crab Meat 6
10 Boston Crab Meat 25
11 Boston Crab Meat 2998
12 Boston Crab Meat 10474
13 Camembert Pierrot 11
14 Camembert Pierrot 21
15 Camembert Pierrot 10064
16 Camembert Pierrot 21794
17 Carnarvon Tigers 5
18 Carnarvon Tigers 12
19 Carnarvon Tigers 5300
20 Carnarvon Tigers 17250
21 Chai 6
22 Chai 16
23 Chai 1800
24 Chai 5295
25 Chang 8
26 Chang 18
27 Chang 3435
28 Chang 7600
29 Chartreuse verte 8
30 Chartreuse verte 13
31 Chartreuse verte 3830
32 Chartreuse verte 4928
33 Chef Anton's Cajun Seasoning 5
34 Chef Anton's Cajun Seasoning 10
35 Chef Anton's Cajun Seasoning 1883
36 Chef Anton's Cajun Seasoning 5737
37 Chef Anton's Gumbo Mix 4
38 Chef Anton's Gumbo Mix 2
39 Chef Anton's Gumbo Mix 2193
40 Chef Anton's Gumbo Mix 405
41 Chocolade 0
42 Chocolade 5
43 Chocolade 1440
44 Côte de Blaye 5
45 Côte de Blaye 10
46 Côte de Blaye 29512
47 Côte de Blaye 51962
48 Escargots de Bourgogne 4
49 Escargots de Bourgogne 7
50 Escargots de Bourgogne 1643
51 Escargots de Bourgogne 2345
52 Filo Mix 3
53 Filo Mix 15
54 Filo Mix 268
55 Filo Mix 2142
56 Flotemysost 11
57 Flotemysost 21
58 Flotemysost 4489
59 Flotemysost 9034
60 Geitost 6
61 Geitost 16
62 Geitost 394
63 Geitost 814
64 Genen Shouyu 2
65 Genen Shouyu 4
66 Genen Shouyu 310
67 Genen Shouyu 1503
68 Gnocchi di nonna Alice 7
69 Gnocchi di nonna Alice 33
70 Gnocchi di nonna Alice 2918
71 Gnocchi di nonna Alice 34754
72 Gorgonzola Telino 13
73 Gorgonzola Telino 26
74 Gorgonzola Telino 4440
75 Gorgonzola Telino 8020
76 Grandma's Boysenberry Spread 2
77 Grandma's Boysenberry Spread 2
78 Grandma's Boysenberry Spread 720
79 Grandma's Boysenberry Spread 2500
80 Gravad lax 2
81 Gravad lax 2
82 Gravad lax 603
83 Gravad lax 676
84 Guaraná Fantástica 11
85 Guaraná Fantástica 19
86 Guaraná Fantástica 568
87 Guaraná Fantástica 1756
88 Gudbrandsdalsost 8
89 Gudbrandsdalsost 18
90 Gudbrandsdalsost 4291
91 Gudbrandsdalsost 15156
92 Gula Malacca 4
93 Gula Malacca 15
94 Gula Malacca 2139
95 Gula Malacca 7082
96 Gumbär Gummibärchen 4
97 Gumbär Gummibärchen 19
98 Gumbär Gummibärchen 3984
99 Gumbär Gummibärchen 10961
100 Gustaf's Knäckebröd 1
101 Gustaf's Knäckebröd 9
102 Gustaf's Knäckebröd 100
103 Gustaf's Knäckebröd 4338
104 Ikura 4
105 Ikura 19
106 Ikura 2108
107 Ikura 10391
108 Inlagd Sill 8
109 Inlagd Sill 15
110 Inlagd Sill 2933
111 Inlagd Sill 7163
112 Ipoh Coffee 6
113 Ipoh Coffee 11
114 Ipoh Coffee 5004
115 Ipoh Coffee 11518
116 Jack's New England Clam Chowder 8
117 Jack's New England Clam Chowder 21
118 Jack's New England Clam Chowder 877
119 Jack's New England Clam Chowder 5151
120 Konbu 6
121 Konbu 11
122 Konbu 432
123 Konbu 848
124 Lakkalikööri 7
125 Lakkalikööri 19
126 Lakkalikööri 2102
127 Lakkalikööri 7707
128 Laughing Lumberjack Lager 1
129 Laughing Lumberjack Lager 4
130 Laughing Lumberjack Lager 56
131 Laughing Lumberjack Lager 910
132 Longlife Tofu 5
133 Longlife Tofu 6
134 Longlife Tofu 1128
135 Longlife Tofu 1038
136 Louisiana Fiery Hot Pepper Sauce 8
137 Louisiana Fiery Hot Pepper Sauce 18
138 Louisiana Fiery Hot Pepper Sauce 2604
139 Louisiana Fiery Hot Pepper Sauce 9898
140 Louisiana Hot Spiced Okra 1
141 Louisiana Hot Spiced Okra 6
142 Louisiana Hot Spiced Okra 408
143 Louisiana Hot Spiced Okra 3094
144 Manjimup Dried Apples 6
145 Manjimup Dried Apples 19
146 Manjimup Dried Apples 6911
147 Manjimup Dried Apples 26065
148 Mascarpone Fabioli 3
149 Mascarpone Fabioli 5
150 Mascarpone Fabioli 1331
151 Mascarpone Fabioli 3136
152 Maxilaku 4
153 Maxilaku 9
154 Maxilaku 1920
155 Maxilaku 3240
156 Mishi Kobe Niku 0
157 Mishi Kobe Niku 4
158 Mishi Kobe Niku 8536
159 Mozzarella di Giovanni 13
160 Mozzarella di Giovanni 16
161 Mozzarella di Giovanni 7263
162 Mozzarella di Giovanni 11759
163 Nord-Ost Matjeshering 7
164 Nord-Ost Matjeshering 16
165 Nord-Ost Matjeshering 3146
166 Nord-Ost Matjeshering 6554
167 Northwoods Cranberry Sauce 2
168 Northwoods Cranberry Sauce 5
169 Northwoods Cranberry Sauce 4480
170 Northwoods Cranberry Sauce 4560
171 NuNuCa Nuß-Nougat-Creme 4
172 NuNuCa Nuß-Nougat-Creme 6
173 NuNuCa Nuß-Nougat-Creme 795
174 NuNuCa Nuß-Nougat-Creme 1926
175 Original Frankfurter grüne Soße 6
176 Original Frankfurter grüne Soße 17
177 Original Frankfurter grüne Soße 655
178 Original Frankfurter grüne Soße 5181
179 Outback Lager 7
180 Outback Lager 17
181 Outback Lager 1872
182 Outback Lager 5880
183 Pâté chinois 6
184 Pâté chinois 16
185 Pâté chinois 4377
186 Pâté chinois 8990
187 Pavlova 7
188 Pavlova 22
189 Pavlova 3502
190 Pavlova 9399
191 Perth Pasties 7
192 Perth Pasties 15
193 Perth Pasties 5528
194 Perth Pasties 10766
195 Queso Cabrales 5
196 Queso Cabrales 21
197 Queso Cabrales 1814
198 Queso Cabrales 7425
199 Queso Manchego La Pastora 1
200 Queso Manchego La Pastora 7
201 Queso Manchego La Pastora 364
202 Queso Manchego La Pastora 8854
203 Raclette Courdavault 10
204 Raclette Courdavault 31
205 Raclette Courdavault 10164
206 Raclette Courdavault 37917
207 Ravioli Angelo 6
208 Ravioli Angelo 8
209 Ravioli Angelo 2074
210 Ravioli Angelo 2281
211 Rhönbräu Klosterbier 7
212 Rhönbräu Klosterbier 25
213 Rhönbräu Klosterbier 744
214 Rhönbräu Klosterbier 4767
215 Röd Kaviar 1
216 Röd Kaviar 11
217 Röd Kaviar 300
218 Röd Kaviar 3720
219 Rogede sild 1
220 Rogede sild 9
221 Rogede sild 114
222 Rogede sild 3667
223 Rössle Sauerkraut 8
224 Rössle Sauerkraut 17
225 Rössle Sauerkraut 4914
226 Rössle Sauerkraut 14610
227 Sasquatch Ale 5
228 Sasquatch Ale 8
229 Sasquatch Ale 1008
230 Sasquatch Ale 2240
231 Schoggi Schokolade 2
232 Schoggi Schokolade 4
233 Schoggi Schokolade 1404
234 Schoggi Schokolade 10974
235 Scottish Longbreads 9
236 Scottish Longbreads 16
237 Scottish Longbreads 1330
238 Scottish Longbreads 4520
239 Singaporean Hokkien Fried Mee 5
240 Singaporean Hokkien Fried Mee 16
241 Singaporean Hokkien Fried Mee 400
242 Singaporean Hokkien Fried Mee 6006
243 Sir Rodney's Marmalade 5
244 Sir Rodney's Marmalade 4
245 Sir Rodney's Marmalade 6868
246 Sir Rodney's Marmalade 7776
247 Sir Rodney's Scones 5
248 Sir Rodney's Scones 23
249 Sir Rodney's Scones 440
250 Sir Rodney's Scones 5686
251 Sirop d'érable 0
252 Sirop d'érable 13
253 Sirop d'érable 10539
254 Spegesild 4
255 Spegesild 14
256 Spegesild 1132
257 Spegesild 3079
258 Steeleye Stout 7
259 Steeleye Stout 16
260 Steeleye Stout 3945
261 Steeleye Stout 5857
262 Tarte au sucre 11
263 Tarte au sucre 22
264 Tarte au sucre 9850
265 Tarte au sucre 22673
266 Teatime Chocolate Biscuits 5
267 Teatime Chocolate Biscuits 21
268 Teatime Chocolate Biscuits 905
269 Teatime Chocolate Biscuits 3211
270 Thüringer Rostbratwurst 7
271 Thüringer Rostbratwurst 15
272 Thüringer Rostbratwurst 12177
273 Thüringer Rostbratwurst 36194
274 Tofu 5
275 Tofu 15
276 Tofu 1581
277 Tofu 6561
278 Tourtière 9
279 Tourtière 22
280 Tourtière 908
281 Tourtière 3415
282 Tunnbröd 3
283 Tunnbröd 10
284 Tunnbröd 756
285 Tunnbröd 2392
286 Uncle Bob's Organic Dried Pears 2
287 Uncle Bob's Organic Dried Pears 10
288 Uncle Bob's Organic Dried Pears 600
289 Uncle Bob's Organic Dried Pears 9444
290 Valkoinen suklaa 2
291 Valkoinen suklaa 5
292 Valkoinen suklaa 390
293 Valkoinen suklaa 2226
294 Vegie-spread 4
295 Vegie-spread 7
296 Vegie-spread 3825
297 Vegie-spread 7417
298 Wimmers gute Semmelknödel 4
299 Wimmers gute Semmelknödel 14
300 Wimmers gute Semmelknödel 3298
301 Wimmers gute Semmelknödel 8571
302 Zaanse koeken 1
303 Zaanse koeken 15
304 Zaanse koeken 121
305 Zaanse koeken 3192


4. Show current UnitsInStock and UnitsOnOrder for products from specific suppliers as columns, with the supplier name as the main row identifier. This demonstrates UNPIVOTing inventory types, and then PIVOTing on supplier names.

SQL Server Query 4

            
 -- Show current UnitsInStock and UnitsOnOrder for products from specific suppliers as columns, with the supplier name as the main row identifier. This demonstrates UNPIVOTing inventory types, and then PIVOTing on supplier names.  
SELECT
ProductName,
InventoryType,
[Exotic Liquids] AS Exotic_Liquids, -- Supplier name 1
[New Orleans Cajun Delights] AS New_Orleans_Cajun_Delights, -- Supplier name 2
[Grandma Kelly''s Homestead] AS Grandma_Kelly_S_Homestead, -- Supplier name 3
[Tokyo Traders] AS Tokyo_Traders
FROM
(
-- Step 1: Select relevant data including supplier name, product name, and inventory metrics
SELECT
P.ProductName,
S.CompanyName AS SupplierName,
P.UnitsInStock,
P.UnitsOnOrder
FROM
Products AS P
JOIN Suppliers AS S ON P.SupplierID = S.SupplierID
WHERE
S.CompanyName IN ('Exotic Liquids', 'New Orleans Cajun Delights', 'Grandma Kelly''s Homestead', 'Tokyo Traders')
) AS SourceData
UNPIVOT
(
InventoryValue FOR InventoryType IN (UnitsInStock, UnitsOnOrder) -- Step 2: Unpivot inventory columns
) AS UnpivotedInventory
PIVOT
(
SUM(InventoryValue) -- Step 3: Aggregate (sum) the inventory values
FOR SupplierName IN ([Exotic Liquids], [New Orleans Cajun Delights], [Grandma Kelly''s Homestead], [Tokyo Traders]) -- Step 4: Pivot on supplier names
) AS PivotedBySupplier
ORDER BY
ProductName, InventoryType;

Create SQL query with SqlQueryBuilder 4

            
 var (sql4, parameters4) = new SqlQueryBuilder()  
.Select()
.Columns("ProductName","InventoryType")
.PivotedColumn("[Exotic Liquids]", "Exotic_Liquids")
.PivotedColumn("[New Orleans Cajun Delights]", "New_Orleans_Cajun_Delights")
.PivotedColumn("[Grandma Kelly''s Homestead]", "Grandma_Kelly_S_Homestead")
.PivotedColumn("[Tokyo Traders]", "Tokyo_Traders")
.From(new SqlQueryBuilder().Select()
.Column("P.ProductName")
.Column("S.CompanyName", "SupplierName")
.Columns("P.UnitsInStock", "P.UnitsOnOrder")
.From("Products", "P")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("Suppliers", "S")
.On(new Column("P.SupplierID").Equale(new Column("S.SupplierID")))
})
.Where(new Where(new IN(new Column("S.CompanyName"), "Exotic Liquids", "New Orleans Cajun Delights", "Grandma Kelly's Homestead", "Tokyo Traders")))
, "SourceData")
.UnPivot(new UnPivot(new Column("InventoryValue"))
.For(new Column("InventoryType"))
.IN("UnitsInStock", "UnitsOnOrder")
.TableName(new Table("UnpivotedInventory")))
.Pivot(new Pivot(new SUM(new Column("InventoryValue")))
.For(new Column("SupplierName"))
.IN("[Exotic Liquids]","[New Orleans Cajun Delights]","[Grandma Kelly''s Homestead]","[Tokyo Traders]")
.TableName(new Table("PivotedBySupplier")))
.OrderBy(new OrderBy()
.SetColumnAscending("ProductName")
.SetColumnAscending("InventoryType"))
.Build();

Query build by SqlQueryBuilder 4

            
SELECT ProductName,
       InventoryType,
       [Exotic Liquids] AS Exotic_Liquids,
       [New Orleans Cajun Delights] AS New_Orleans_Cajun_Delights,
       [Grandma Kelly''s Homestead] AS Grandma_Kelly_S_Homestead,
       [Tokyo Traders] AS Tokyo_Traders
FROM (SELECT P.ProductName,
             S.CompanyName AS SupplierName,
             P.UnitsInStock,
             P.UnitsOnOrder
      FROM Products AS P
           INNER JOIN
           Suppliers AS S
           ON P.SupplierID = S.SupplierID
      WHERE S.CompanyName IN (@pMAIN_2507200206540263240, @pMAIN_2507200206540263241, @pMAIN_2507200206540263242, @pMAIN_2507200206540263243)) AS SourceData UNPIVOT (InventoryValue FOR InventoryType IN (UnitsInStock, UnitsOnOrder)) AS UnpivotedInventory PIVOT (SUM (InventoryValue) FOR SupplierName IN ([Exotic Liquids], [New Orleans Cajun Delights], [Grandma Kelly''s Homestead], [Tokyo Traders])) AS PivotedBySupplier
ORDER BY ProductName ASC, InventoryType ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200206540263240 Exotic Liquids
@pMAIN_2507200206540263241 New Orleans Cajun Delights
@pMAIN_2507200206540263242 Grandma Kelly's Homestead
@pMAIN_2507200206540263243 Tokyo Traders

Query Results 4:

  ProductName InventoryType Exotic_Liquids New_Orleans_Cajun_Delights Grandma_Kelly_S_Homestead Tokyo_Traders
1 Aniseed Syrup UnitsInStock 13
2 Aniseed Syrup UnitsOnOrder 70
3 Chai UnitsInStock 39
4 Chai UnitsOnOrder 0
5 Chang UnitsInStock 17
6 Chang UnitsOnOrder 40
7 Chef Anton's Cajun Seasoning UnitsInStock 53
8 Chef Anton's Cajun Seasoning UnitsOnOrder 0
9 Chef Anton's Gumbo Mix UnitsInStock 0
10 Chef Anton's Gumbo Mix UnitsOnOrder 0
11 Grandma's Boysenberry Spread UnitsInStock
12 Grandma's Boysenberry Spread UnitsOnOrder
13 Ikura UnitsInStock 31
14 Ikura UnitsOnOrder 0
15 Longlife Tofu UnitsInStock 4
16 Longlife Tofu UnitsOnOrder 20
17 Louisiana Fiery Hot Pepper Sauce UnitsInStock 76
18 Louisiana Fiery Hot Pepper Sauce UnitsOnOrder 0
19 Louisiana Hot Spiced Okra UnitsInStock 4
20 Louisiana Hot Spiced Okra UnitsOnOrder 100
21 Mishi Kobe Niku UnitsInStock 29
22 Mishi Kobe Niku UnitsOnOrder 0
23 Northwoods Cranberry Sauce UnitsInStock
24 Northwoods Cranberry Sauce UnitsOnOrder
25 Uncle Bob's Organic Dried Pears UnitsInStock
26 Uncle Bob's Organic Dried Pears UnitsOnOrder


5. Sales vs. Order Count by Year for Top Product Categories

SQL Server Query 5

            
 -- Sales vs. Order Count by Year for Top Product Categories  
SELECT
CategoryName,
MetricType, -- Will be 'TotalSales' or 'TotalOrders'
ISNULL([1996], 0.00) AS Year_1996, -- Use ISNULL to show 0 for no data
ISNULL([1997], 0.00) AS Year_1997,
ISNULL([1998], 0.00) AS Year_1998
FROM
(
-- Step 1: Initial Aggregation (CTE to prepare data for UNPIVOT)
-- Calculate TotalSales and TotalOrders for each CategoryName and OrderYear
SELECT
C.CategoryName,
YEAR(O.OrderDate) AS OrderYear,
CAST(SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) AS DECIMAL(18, 2)) AS TotalSales,
-- Important: CAST TotalOrders to a compatible type (e.g., DECIMAL)
CAST(COUNT(DISTINCT O.OrderID) AS DECIMAL(18, 2)) AS TotalOrders
FROM
Categories AS C
JOIN Products AS P ON C.CategoryID = P.CategoryID
JOIN [Order Details] AS OD ON P.ProductID = OD.ProductID
JOIN Orders AS O ON OD.OrderID = O.OrderID
WHERE
YEAR(O.OrderDate) IN (1996, 1997, 1998)
GROUP BY
C.CategoryName,
YEAR(O.OrderDate)
) AS InitialAggregatedData
UNPIVOT
(
MetricValue FOR MetricType IN (TotalSales, TotalOrders) -- Step 2: UNPIVOT operation
-- Transforms 'TotalSales' and 'TotalOrders' columns into rows
-- MetricValue gets the actual number, MetricType gets 'TotalSales' or 'TotalOrders'
) AS UnpivotedMetrics
PIVOT
(
SUM(MetricValue) -- Step 3: PIVOT operation - Aggregate the MetricValue
FOR OrderYear IN ([1996], [1997], [1998]) -- Create columns for these specific years
) AS PivotedByYear
ORDER BY
CategoryName, MetricType;

Create SQL query with SqlQueryBuilder 5

            
 var (sql5, parameters5) = new SqlQueryBuilder()  
.Select()
.Columns("CategoryName","MetricType")
.Column(new ISNULL(new Column("[1996]"), 0.00), "Year_1996")
.Column(new ISNULL(new Column("[1997]"), 0.00), "Year_1997")
.Column(new ISNULL(new Column("[1998]"), 0.00), "Year_1998")
.From(new SqlQueryBuilder()
.Select()
.Column("C.CategoryName")
.Column(new YEAR(new Column("O.OrderDate")), "OrderYear")
.Column(new CAST(new SUM(new ColumnArithmatic("OD.Quantity")
.MULTIPLY("OD.UnitPrice").MULTIPLY().StartBracket(1).SUBTRACT("OD.Discount").EndBracket()),
SqlDataType.DECIMAL, new Tuple<int, int>(18, 2)), "TotalSales")
.Column(new CAST(new COUNT(new Column("O.OrderID"), true), SqlDataType.DECIMAL, new Tuple<int, int>(18, 2)), "TotalOrders")
.From("Categories", "C")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("Products", "P")
.On(new Column("C.CategoryID").Equale(new Column("P.CategoryID"))),
new INNERJOIN().TableName("[Order Details]", "OD")
.On(new Column("P.ProductID").Equale(new Column("OD.ProductID"))),
new INNERJOIN().TableName("Orders", "O")
.On(new Column("OD.OrderID").Equale(new Column("O.OrderID")))
})
.Where(new Where(new IN(new YEAR(new Column("O.OrderDate")), 1996, 1997, 1998)))
.GroupBy(new GroupBy(new Column("C.CategoryName"), new YEAR(new Column("O.OrderDate"))))
, "InitialAggregatedData")
.UnPivot(new UnPivot(new Column("MetricValue"))
.For(new Column("MetricType"))
.IN("TotalSales", "TotalOrders")
.TableName(new Table("UnpivotedMetrics")))
.Pivot(new Pivot(new SUM(new Column("MetricValue")))
.For(new Column("OrderYear"))
.IN("[1996]", "[1997]", "[1998]")
.TableName(new Table("PivotedByYear")))
.OrderBy(new OrderBy().SetColumnAscending("CategoryName")
.SetColumnAscending("MetricType"))
.Build();

Query build by SqlQueryBuilder 5

            
SELECT CategoryName,
       MetricType,
       ISNULL([1996], @pMAIN_2507200206540391190) AS Year_1996,
       ISNULL([1997], @pMAIN_2507200206540391191) AS Year_1997,
       ISNULL([1998], @pMAIN_2507200206540391192) AS Year_1998
FROM (SELECT C.CategoryName,
             YEAR(O.OrderDate) AS OrderYear,
             CAST (SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200206540391193 - OD.Discount)) AS DECIMAL (18, 2)) AS TotalSales,
             CAST (COUNT(DISTINCT O.OrderID) AS DECIMAL (18, 2)) AS TotalOrders
      FROM Categories AS C
           INNER JOIN
           Products AS P
           ON C.CategoryID = P.CategoryID
           INNER JOIN
           [Order Details] AS OD
           ON P.ProductID = OD.ProductID
           INNER JOIN
           Orders AS O
           ON OD.OrderID = O.OrderID
      WHERE YEAR(O.OrderDate) IN (@pMAIN_2507200206540391194, @pMAIN_2507200206540391195, @pMAIN_2507200206540391196)
      GROUP BY C.CategoryName, YEAR(O.OrderDate)) AS InitialAggregatedData UNPIVOT (MetricValue FOR MetricType IN (TotalSales, TotalOrders)) AS UnpivotedMetrics PIVOT (SUM (MetricValue) FOR OrderYear IN ([1996], [1997], [1998])) AS PivotedByYear
ORDER BY CategoryName ASC, MetricType ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200206540391190 0
@pMAIN_2507200206540391191 0
@pMAIN_2507200206540391192 0
@pMAIN_2507200206540391193 1
@pMAIN_2507200206540391194 1996
@pMAIN_2507200206540391195 1997
@pMAIN_2507200206540391196 1998

Query Results 5:

  CategoryName MetricType Year_1996 Year_1997 Year_1998
1 Beverages TotalOrders 67.00 159.00 128.00
2 Beverages TotalSales 47919.00 103924.31 116024.88
3 Condiments TotalOrders 31.00 100.00 62.00
4 Condiments TotalSales 17900.38 55368.59 32778.11
5 Confections TotalOrders 56.00 150.00 89.00
6 Confections TotalSales 29685.55 82657.75 55013.92
7 Dairy Products TotalOrders 62.00 151.00 90.00
8 Dairy Products TotalSales 40980.45 115387.64 78139.19
9 Grains/Cereals TotalOrders 27.00 100.00 55.00
10 Grains/Cereals TotalSales 9507.92 56871.82 29364.84
11 Meat/Poultry TotalOrders 35.00 83.00 43.00
12 Meat/Poultry TotalSales 28813.66 80975.11 53233.59
13 Produce TotalOrders 25.00 62.00 42.00
14 Produce TotalSales 13885.78 54940.77 31158.03
15 Seafood TotalOrders 51.00 139.00 101.00
16 Seafood TotalSales 19391.22 66959.22 44911.30