PIVOT example


1. Show the total quantity ordered for each product for specific customers ('ALFKI', 'BLAUS', 'FRANS'), with customer IDs as columns.

SQL Server Query 1

            
 SELECT  
ProductName,
[ALFKI],
[BLAUS],
[FRANS]
FROM
(
SELECT
P.ProductName,
C.CustomerID,
OD.Quantity
FROM
[Order Details] AS OD
JOIN Products AS P ON OD.ProductID = P.ProductID
JOIN Orders AS O ON OD.OrderID = O.OrderID
JOIN Customers AS C ON O.CustomerID = C.CustomerID
WHERE C.CustomerID IN ('ALFKI', 'BLAUS', 'FRANS')
) AS SourceTable
PIVOT
(
SUM(Quantity)
FOR CustomerID IN ([ALFKI], [BLAUS], [FRANS])
) AS PivotTable
ORDER BY
ProductName;

Create SQL query with SqlQueryBuilder 1

            
 var (sql1, parameters1) = new SqlQueryBuilder()  
.Select()
.Column("ProductName")
.PivotedColumn("[ALFKI]")
.PivotedColumn("[BLAUS]")
.PivotedColumn("[FRANS]")
.From(new SqlQueryBuilder().Select()
.Columns("P.ProductName","C.CustomerID","OD.Quantity")
.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"))),
new INNERJOIN().TableName("Customers", "C")
.On(new Column("O.CustomerID").Equale(new Column("C.CustomerID")))
})
.Where(new Where(new IN(new Column("C.CustomerID"), "ALFKI","BLAUS","FRANS"))), "SourceTable"
)
.Pivot(new Pivot(new SUM(new Column("Quantity")))
.For(new Column("CustomerID")).IN("[ALFKI]","[BLAUS]","[FRANS]")
.TableName(new Table("PivotTable"))
)
.OrderBy(new OrderBy().SetColumnAscending("ProductName"))
.Build();

Query build by SqlQueryBuilder 1

            
SELECT ProductName,
       [ALFKI],
       [BLAUS],
       [FRANS]
FROM (SELECT P.ProductName,
             C.CustomerID,
             OD.Quantity
      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
           INNER JOIN
           Customers AS C
           ON O.CustomerID = C.CustomerID
      WHERE C.CustomerID IN (@pMAIN_2507200208304276340, @pMAIN_2507200208304276341, @pMAIN_2507200208304276342)) AS SourceTable PIVOT (SUM (Quantity) FOR CustomerID IN ([ALFKI], [BLAUS], [FRANS])) AS PivotTable
ORDER BY ProductName ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208304276340 ALFKI
@pMAIN_2507200208304276341 BLAUS
@pMAIN_2507200208304276342 FRANS

Query Results 1:

  ProductName ALFKI BLAUS FRANS
1 Aniseed Syrup 6
2 Boston Crab Meat 1
3 Camembert Pierrot 21 4
4 Carnarvon Tigers 10 8
5 Chartreuse verte 21 5
6 Escargots de Bourgogne 40
7 Flotemysost 20
8 Grandma's Boysenberry Spread 16
9 Gumbär Gummibärchen 2
10 Lakkalikööri 15 14
11 Longlife Tofu 5
12 Manjimup Dried Apples 8 10
13 Original Frankfurter grüne Soße 2 10
14 Queso Cabrales 14
15 Raclette Courdavault 15
16 Ravioli Angelo 4
17 Rogede sild 4
18 Rössle Sauerkraut 17 3
19 Sir Rodney's Scones 23
20 Sirop d'érable 4
21 Spegesild 2
22 Teatime Chocolate Biscuits 5
23 Tourtière 20
24 Vegie-spread 20
25 Zaanse koeken 14 5


2. Pivoting Multiple Aggregations (Simplified & Advanced)

SQL Server Query 2

            
 SELECT  
ProductName,
ISNULL([Sales_1996], 0) AS [Sales_1996],
ISNULL([Orders_1996], 0) AS [Orders_1996],
ISNULL([Sales_1997], 0) AS [Sales_1997],
ISNULL([Orders_1997], 0) AS [Orders_1997],
ISNULL([Sales_1998], 0) AS [Sales_1998],
ISNULL([Orders_1998], 0) AS [Orders_1998]
FROM
(
SELECT
P.ProductName,
'Sales_' + CAST(YEAR(O.OrderDate) AS NVARCHAR(4)) AS MetricName,
SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) AS MetricValue
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) IN (1996, 1997, 1998)
GROUP BY
P.ProductName,
YEAR(O.OrderDate)

UNION ALL -- Union with the order counts

SELECT
P.ProductName,
'Orders_' + CAST(YEAR(O.OrderDate) AS NVARCHAR(4)) AS MetricName,
CAST(COUNT(DISTINCT O.OrderID) AS DECIMAL(18,2)) AS MetricValue -- Cast to match sales 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) IN (1996, 1997, 1998)
GROUP BY
P.ProductName,
YEAR(O.OrderDate)
) AS SourceData
PIVOT
(
SUM(MetricValue) -- The aggregate function for the pivoted values
FOR MetricName IN ([Sales_1996], [Orders_1996], [Sales_1997], [Orders_1997], [Sales_1998], [Orders_1998])
) AS PivotTable
ORDER BY
ProductName;

Create SQL query with SqlQueryBuilder 2

            
 var (sql2, parameters2) = new SqlQueryBuilder()  
.Select()
.Column("ProductName")
.Column(new ISNULL(new Column("[Sales_1996]"), 0), "[Sales_1996]")
.Column(new ISNULL(new Column("[Orders_1996]"), 0), "[Orders_1996]")
.Column(new ISNULL(new Column("[Sales_1997]"), 0), "[Sales_1997]")
.Column(new ISNULL(new Column("[Orders_1997]"), 0), "[Orders_1997]")
.Column(new ISNULL(new Column("[Sales_1998]"), 0), "[Sales_1998]")
.Column(new ISNULL(new Column("[Orders_1998]"), 0), "[Orders_1998]")
.From(new SqlQueryBuilder().Select()
.Column("P.ProductName")
.Column(new CONCAT("Sales_", new CAST(new YEAR(new Column("O.OrderDate")), SqlDataType.NVARCHAR, "4")), "MetricName")
.Column(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")
.MULTIPLY().StartBracket(1).SUBTRACT("OD.Discount").EndBracket()), "MetricValue")
.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 IN(new YEAR(new Column("O.OrderDate")), 1996, 1997, 1998)))
.GroupBy(new GroupBy(new Column("P.ProductName"), new YEAR(new Column("O.OrderDate"))))
.UnionAll(new SqlQueryBuilder().Select()
.Column("P.ProductName")
.Column(new CONCAT("Orders_", new CAST(new YEAR(new Column("O.OrderDate")), SqlDataType.NVARCHAR, "4")), "MetricName")
.Column(new CAST(new COUNT(new Column("O.OrderID"), true), SqlDataType.DECIMAL, new Tuple<int, int>(18, 2)), "MetricValue")
.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 IN(new YEAR(new Column("O.OrderDate")), 1996, 1997, 1998)))
.GroupBy(new GroupBy(new Column("P.ProductName"), new YEAR(new Column("O.OrderDate"))))
), "SourceData")
.Pivot(new Pivot(new SUM(new Column("MetricValue")))
.For(new Column("MetricName"))
.IN("[Sales_1996]","[Orders_1996]","[Sales_1997]","[Orders_1997]","[Sales_1998]","[Orders_1998]")
.TableName(new Table("PivotTable")))
.OrderBy(new OrderBy().SetColumnAscending("ProductName"))
.Build();

Query build by SqlQueryBuilder 2

            
SELECT ProductName,
       ISNULL([Sales_1996], @pMAIN_2507200208304451150) AS [Sales_1996],
       ISNULL([Orders_1996], @pMAIN_2507200208304451151) AS [Orders_1996],
       ISNULL([Sales_1997], @pMAIN_2507200208304451152) AS [Sales_1997],
       ISNULL([Orders_1997], @pMAIN_2507200208304451153) AS [Orders_1997],
       ISNULL([Sales_1998], @pMAIN_2507200208304451154) AS [Sales_1998],
       ISNULL([Orders_1998], @pMAIN_2507200208304451155) AS [Orders_1998]
FROM (SELECT P.ProductName,
             CONCAT(@pMAIN_2507200208304451156, CAST (YEAR(O.OrderDate) AS NVARCHAR (4))) AS MetricName,
             SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200208304451157 - OD.Discount)) AS MetricValue
      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) IN (@pMAIN_2507200208304451158, @pMAIN_2507200208304451159, @pMAIN_250720020830445115_10)
      GROUP BY P.ProductName, YEAR(O.OrderDate)
      UNION ALL
      SELECT P.ProductName,
             CONCAT(@pMAIN_250720020830445115_11, CAST (YEAR(O.OrderDate) AS NVARCHAR (4))) AS MetricName,
             CAST (COUNT(DISTINCT O.OrderID) AS DECIMAL (18, 2)) AS MetricValue
      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) IN (@pMAIN_250720020830445115_12, @pMAIN_250720020830445115_13, @pMAIN_250720020830445115_14)
      GROUP BY P.ProductName, YEAR(O.OrderDate)) AS SourceData PIVOT (SUM (MetricValue) FOR MetricName IN ([Sales_1996], [Orders_1996], [Sales_1997], [Orders_1997], [Sales_1998], [Orders_1998])) AS PivotTable
ORDER BY ProductName ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208304451150 0
@pMAIN_2507200208304451151 0
@pMAIN_2507200208304451152 0
@pMAIN_2507200208304451153 0
@pMAIN_2507200208304451154 0
@pMAIN_2507200208304451155 0
@pMAIN_2507200208304451156 Sales_
@pMAIN_2507200208304451157 1
@pMAIN_2507200208304451158 1996
@pMAIN_2507200208304451159 1997
@pMAIN_250720020830445115_10 1998
@pMAIN_250720020830445115_11 Orders_
@pMAIN_250720020830445115_12 1996
@pMAIN_250720020830445115_13 1997
@pMAIN_250720020830445115_14 1998

Query Results 2:

  ProductName Sales_1996 Orders_1996 Sales_1997 Orders_1997 Sales_1998 Orders_1998
1 Alice Mutton 6962.2799987793 8 17604.6000442505 18 8131.49993896484 11
2 Aniseed Syrup 240 1 1724 7 1080 4
3 Boston Crab Meat 2778.29996871948 6 9814.72990989685 25 5317.60001373291 10
4 Camembert Pierrot 9024.95999145508 11 20505.400177002 21 17295.1199645996 19
5 Carnarvon Tigers 4725 5 15950 12 8496.875 10
6 Chai 1605.60005187988 6 4887.00000762939 16 6295.5 16
7 Chang 3017.95999908447 8 7038.55001831055 18 6299.45002746582 18
8 Chartreuse verte 3558.23994445801 8 4475.70000267029 13 4260.60000228882 9
9 Chef Anton's Cajun Seasoning 1851.51998901367 5 5214.88000488281 10 1501.5 5
10 Chef Anton's Gumbo Mix 1931.19999694824 4 373.625007629394 2 3042.375 4
11 Chocolade 0 0 1282.01251983643 5 86.7000045776367 1
12 Côte de Blaye 24874.3999023438 5 49198.0853271484 10 67324.25 9
13 Escargots de Bourgogne 1378.00001525879 4 2076.27502441406 7 2427.40000915527 7
14 Filo Mix 246.399997711182 3 2124.14999961853 15 862.399997711182 11
15 Flotemysost 4248.40000915527 11 8438.74999237061 21 6863.875 10
16 Geitost 385.5 6 786 16 476.625 10
17 Genen Shouyu 310 2 1474.82499694824 4 0 0
18 Gnocchi di nonna Alice 2763.36001968384 7 32604.0000915527 33 7225.69998168945 10
19 Gorgonzola Telino 4154.5 13 7300.75 26 3465.625 12
20 Grandma's Boysenberry Spread 720 2 2500 2 3917 8
21 Gravad lax 603.200023651123 2 629.199981689453 2 1456 2
22 Guaraná Fantástica 556.740007400513 11 1630.12500762939 19 2317.5 21
23 Gudbrandsdalsost 4239.35999679565 8 13062.6000061035 18 4640.40002441406 5
24 Gula Malacca 2042.12493896484 4 6737.93998146057 15 1135.88001251221 5
25 Gumbär Gummibärchen 3361.49996948242 4 10443.0780754089 19 6044.56649780274 9
26 Gustaf's Knäckebröd 95.7600021362305 1 4233.60000610352 9 2793 4
27 Ikura 1929.44000244141 4 9935.5 19 9002.40002441406 10
28 Inlagd Sill 2626.55997467041 8 6894.15000152588 15 3937.75 8
29 Ipoh Coffee 4931.20004272461 6 11069.9000015259 11 7525.60009765625 11
30 Jack's New England Clam Chowder 807.344989776611 8 4957.25249481201 21 2915.74750518799 18
31 Konbu 422.399993896484 6 812.940000534058 11 3725.10002803802 23
32 Lakkalikööri 2046.24001312256 7 7379.10004806518 19 6335.10000038147 13
33 Laughing Lumberjack Lager 42 1 910 4 1444.80001831055 5
34 Longlife Tofu 1032 5 1000.5 6 400 2
35 Louisiana Fiery Hot Pepper Sauce 2473.79997253418 8 9373.18492889404 18 2022.90496826172 6
36 Louisiana Hot Spiced Okra 408 1 2958.00003051758 6 17 1
37 Manjimup Dried Apples 6158.60009002686 6 24570.8001556396 19 11090.25 14
38 Mascarpone Fabioli 1167.35998535156 3 2668.80004882812 5 4568 7
39 Maxilaku 1920 4 3128.60000610352 9 4196 8
40 Mishi Kobe Niku 0 0 6935.5 4 291 1
41 Mozzarella di Giovanni 6772.32994842529 13 11602.8000602722 16 6524.99990081787 9
42 Nord-Ost Matjeshering 2645.46003723145 7 6034.39502334595 16 4744.34243774414 9
43 Northwoods Cranberry Sauce 3920 2 4260 5 4592 6
44 NuNuCa Nuß-Nougat-Creme 775.600002288818 4 1692.59994506836 6 1236.20000457764 8
45 Original Frankfurter grüne Soße 655.200012207031 6 4761.37998771668 17 3755.05000114441 15
46 Outback Lager 1809 7 5468.39999389648 17 3395.25 15
47 Pâté chinois 3933.11990356445 6 7832.87981033325 16 5660.39999389648 11
48 Pavlova 3128.19505310059 7 8663.42245483398 22 5424.15801620483 14
49 Perth Pasties 5103.75994873047 7 10661.9300308228 15 4808.47988891602 8
50 Queso Cabrales 1606.08003234863 5 6911.9400100708 21 4383.75 12
51 Queso Manchego La Pastora 346.559997558594 1 8335.30004882812 7 3575.79999542236 6
52 Raclette Courdavault 9035.40000915527 10 35775.3000183106 31 26345 13
53 Ravioli Angelo 2063.10000991821 6 2156.69999694824 8 3441.75 9
54 Rhönbräu Klosterbier 738.420003890991 7 4485.54497909546 25 2953.52500152588 14
55 Röd Kaviar 300 1 3517.5 11 179.700000762939 2
56 Rogede sild 91.2000045776367 1 3355.875 9 891.100006103516 4
57 Rössle Sauerkraut 4757.48001098633 8 13948.6799926758 17 6990.47982788086 8
58 Sasquatch Ale 1002.40001678467 5 2107 8 3241 6
59 Schoggi Schokolade 1272.375 2 10974 4 2853.5 3
60 Scottish Longbreads 1294 9 4157.5 16 3262.5 9
61 Singaporean Hokkien Fried Mee 377.999998092651 5 5408.20001220703 16 2788.80001831055 9
62 Sir Rodney's Marmalade 6544.79986572266 5 7314.30004882812 4 8704.25999450684 7
63 Sir Rodney's Scones 416 5 5273 23 3415 11
64 Sirop d'érable 0 0 9091.50006103516 13 5261.10009765625 11
65 Spegesild 1084.31998443604 4 2981.39997005463 14 1817.2799987793 9
66 Steeleye Stout 3736.80001068115 7 5274.90000915527 16 4632.29998779297 13
67 Tarte au sucre 9603.74993896484 11 21638.3000411987 22 15992.919921875 15
68 Teatime Chocolate Biscuits 901.54999256134 5 2986.74999427795 21 1974.31999778748 11
69 Thüringer Rostbratwurst 11929.5 7 34755.9130859375 15 33683.2589111328 10
70 Tofu 1385.70001220703 5 6234.48749160767 15 371.302499771118 2
71 Tourtière 885.000007629394 9 3184.28502655029 22 658.952499389648 5
72 Tunnbröd 756 3 2288.69999694824 10 1557 7
73 Uncle Bob's Organic Dried Pears 552 2 9186.29998779297 10 12306 17
74 Valkoinen suklaa 370.5 2 2173.4375 5 893.75 3
75 Vegie-spread 3348.54000854492 4 6899.25500488281 7 6453.29998779297 6
76 Wimmers gute Semmelknödel 3205.29995727539 4 8056.4748840332 14 10696.1925048828 12
77 Zaanse koeken 97.2799987792969 1 2930.75 15 930.049987792969 5


3. Pivoting Multiple Aggregations (Simplified & Advanced)

SQL Server Query 3

            
 SELECT  
CategoryName,
MetricType,
[1996] AS _1996,
[1997] AS _1997,
[1998] AS _1998
FROM
(
-- Subquery to prepare data for PIVOT, combining multiple aggregates
-- First part: Total Sales
SELECT
C.CategoryName,
YEAR(O.OrderDate) AS OrderYear,
'TotalSales' AS MetricType,
SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) AS MetricValue
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)

UNION ALL

-- Second part: Total Orders (for a specific year)
SELECT
C.CategoryName,
YEAR(O.OrderDate) AS OrderYear,
'TotalOrders' AS MetricType,
CAST(COUNT(DISTINCT O.OrderID) AS DECIMAL(18, 2)) AS MetricValue -- Cast to match TotalSales' data type
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 SourceData
PIVOT
(
SUM(MetricValue) -- Aggregate the combined MetricValue
FOR OrderYear IN ([1996], [1997], [1998])
) AS PivotTable
ORDER BY
CategoryName, MetricType;

Create SQL query with SqlQueryBuilder 3

            
 var (sql3, parameters3) = new SqlQueryBuilder()  
.Select()
.Columns("CategoryName","MetricType")
.PivotedColumn("[1996]", "_1996")
.PivotedColumn("[1997]", "_1997")
.PivotedColumn("[1998]", "_1998")
.From(new SqlQueryBuilder().Select()
.Column("C.CategoryName")
.Column(new YEAR(new Column("O.OrderDate")), "OrderYear")
.ColumnWithValue("TotalSales","MetricType")
.Column(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")
.MULTIPLY().StartBracket(1).SUBTRACT("OD.Discount").EndBracket()), "MetricValue")
.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"))))
.UnionAll(new SqlQueryBuilder().Select()
.Column("C.CategoryName")
.Column(new YEAR(new Column("O.OrderDate")), "OrderYear")
.ColumnWithValue("TotalOrders", "MetricType")
.Column(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")
.MULTIPLY().StartBracket(1).SUBTRACT("OD.Discount").EndBracket()), "MetricValue")
.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")))))
, "SourceData")
.Pivot(new Pivot(new SUM(new Column("MetricValue")))
.For(new Column("OrderYear"))
.IN("[1996]", "[1997]", "[1998]")
.TableName(new Table("PivotTable")))
.OrderBy(new OrderBy().SetColumnAscending("CategoryName")
.SetColumnAscending("MetricType"))
.Build();

Query build by SqlQueryBuilder 3

            
SELECT CategoryName,
       MetricType,
       [1996] AS _1996,
       [1997] AS _1997,
       [1998] AS _1998
FROM (SELECT C.CategoryName,
             YEAR(O.OrderDate) AS OrderYear,
             @pMAIN_2507200208304766170 AS MetricType,
             SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200208304766171 - OD.Discount)) AS MetricValue
      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_2507200208304766172, @pMAIN_2507200208304766173, @pMAIN_2507200208304766174)
      GROUP BY C.CategoryName, YEAR(O.OrderDate)
      UNION ALL
      SELECT C.CategoryName,
             YEAR(O.OrderDate) AS OrderYear,
             @pMAIN_2507200208304766175 AS MetricType,
             SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200208304766176 - OD.Discount)) AS MetricValue
      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_2507200208304766177, @pMAIN_2507200208304766178, @pMAIN_2507200208304766179)
      GROUP BY C.CategoryName, YEAR(O.OrderDate)) AS SourceData PIVOT (SUM (MetricValue) FOR OrderYear IN ([1996], [1997], [1998])) AS PivotTable
ORDER BY CategoryName ASC, MetricType ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208304766170 TotalSales
@pMAIN_2507200208304766171 1
@pMAIN_2507200208304766172 1996
@pMAIN_2507200208304766173 1997
@pMAIN_2507200208304766174 1998
@pMAIN_2507200208304766175 TotalOrders
@pMAIN_2507200208304766176 1
@pMAIN_2507200208304766177 1996
@pMAIN_2507200208304766178 1997
@pMAIN_2507200208304766179 1998

Query Results 3:

  CategoryName MetricType _1996 _1997 _1998
1 Beverages TotalOrders 47918.9999923706 103924.305395126 116024.875135422
2 Beverages TotalSales 47918.9999923706 103924.305395126 116024.875135422
3 Condiments TotalOrders 17900.3849182129 55368.5900039673 32778.1100673676
4 Condiments TotalSales 17900.3849182129 55368.5900039673 32778.1100673676
5 Confections TotalOrders 29685.5498209 82657.750585556 55013.9244251251
6 Confections TotalSales 29685.5498209 82657.750585556 55013.9244251251
7 Dairy Products TotalOrders 40980.4499702454 115387.640361786 78139.1948852539
8 Dairy Products TotalSales 40980.4499702454 115387.640361786 78139.1948852539
9 Grains/Cereals TotalOrders 9507.9199848175 56871.8249874115 29364.842502594
10 Grains/Cereals TotalSales 9507.9199848175 56871.8249874115 29364.842502594
11 Meat/Poultry TotalOrders 28813.6598587036 80975.1079978943 53233.5912322998
12 Meat/Poultry TotalSales 28813.6598587036 80975.1079978943 53233.5912322998
13 Produce TotalOrders 13885.7801132202 54940.7676277161 31158.032327652
14 Produce TotalSales 13885.7801132202 54940.7676277161 31158.032327652
15 Seafood TotalOrders 19391.2249946594 66959.2174062729 44911.2950239182
16 Seafood TotalSales 19391.2249946594 66959.2174062729 44911.2950239182


4. Top-Selling Products by Category, Filtered by Date & Minimum Sales

SQL Server Query 4

            
 -- Parameters for pagination and filtering  
DECLARE @PageNumber INT = 2; -- Example: Get the 2nd page
DECLARE @PageSize INT = 5; -- Example: 5 products per page
DECLARE @TargetYear INT = 1997; -- Example: Orders from 1997
DECLARE @MinCategorySalesValue DECIMAL(18, 2) = 50.00; -- Example: Minimum total sales for a category

-- Calculate the number of rows to skip
DECLARE @OffsetRows INT = (@PageNumber - 1) * @PageSize;

SELECT
Cat.CategoryName,
P.ProductName,
SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) AS ProductTotalSales,
COUNT(DISTINCT O.OrderID) AS NumberOfOrders
FROM
Categories AS Cat
JOIN
Products AS P ON Cat.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) = @TargetYear -- Filter orders by year (BEFORE grouping)
GROUP BY
Cat.CategoryName,
P.ProductName
HAVING
SUM(OD.Quantity * OD.UnitPrice * (1 - OD.Discount)) >= @MinCategorySalesValue -- Filter groups by total sales
ORDER BY
ProductTotalSales DESC, -- Sort by product sales (highest first)
Cat.CategoryName ASC, -- Tie-breaker 1
P.ProductName ASC -- Tie-breaker 2 (ensures unique, consistent order)
OFFSET @OffsetRows ROWS
FETCH NEXT @PageSize ROWS ONLY;

Create SQL query with SqlQueryBuilder 4

            
 var (sql4, parameters4) = new SqlQueryBuilder()  
.Select()
.Columns("Cat.CategoryName", "P.ProductName")
.Column(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")
.MULTIPLY().StartBracket(1).SUBTRACT("OD.Discount").EndBracket()), "ProductTotalSales")
.Column(new COUNT(new Column("O.OrderID"), true), "NumberOfOrders")
.From("Categories", "Cat")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("Products", "P")
.On(new Column("Cat.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 YEAR(new Column("O.OrderDate")).Equale(1997)))
.GroupBy(new GroupBy("Cat.CategoryName", "P.ProductName"))
.Having(new Having(new SUM(
new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice").MULTIPLY()
.StartBracket(1).SUBTRACT("OD.Discount").EndBracket()).GreaterThanOrEqualeTo(50.00)))
.OrderBy(new OrderBy().SetColumnDescending("ProductTotalSales")
.SetColumnAscending("Cat.CategoryName").Offset(5,5))
.Build();

Query build by SqlQueryBuilder 4

            
SELECT Cat.CategoryName,
       P.ProductName,
       SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200208305110540 - OD.Discount)) AS ProductTotalSales,
       COUNT(DISTINCT O.OrderID) AS NumberOfOrders
FROM Categories AS Cat
     INNER JOIN
     Products AS P
     ON Cat.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) = @pMAIN_2507200208305110541
GROUP BY Cat.CategoryName, P.ProductName
HAVING SUM(OD.Quantity * OD.UnitPrice * (@pMAIN_2507200208305110542 - OD.Discount)) >= @pMAIN_2507200208305110543
ORDER BY ProductTotalSales DESC, Cat.CategoryName ASC
OFFSET @pMAIN_2507200208305110544 ROWS FETCH NEXT @pMAIN_2507200208305110545 ROWS ONLY;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208305110540 1
@pMAIN_2507200208305110541 1997
@pMAIN_2507200208305110542 1
@pMAIN_2507200208305110543 50
@pMAIN_2507200208305110544 5
@pMAIN_2507200208305110545 5

Query Results 4:

  CategoryName ProductName ProductTotalSales NumberOfOrders
1 Confections Tarte au sucre 21638.3000411987 22
2 Dairy Products Camembert Pierrot 20505.400177002 21
3 Meat/Poultry Alice Mutton 17604.6000442505 18
4 Seafood Carnarvon Tigers 15950 12
5 Produce Rössle Sauerkraut 13948.6799926758 17


5. Search Functionality with Pagination

SQL Server Query 5

            
 -- Parameters for pagination and search  
DECLARE @PageNumber INT = 1;
DECLARE @PageSize INT = 10;
DECLARE @SearchProductName NVARCHAR(40) = 'Chai'; -- Example: Search for 'Chai' or 'Cha' or 'syrup'

-- Calculate the number of rows to skip
DECLARE @OffsetRows INT = (@PageNumber - 1) * @PageSize;

SELECT
O.OrderID,
O.OrderDate,
C.CompanyName,
P.ProductName,
OD.Quantity,
OD.UnitPrice
FROM
Orders AS O
JOIN
[Order Details] AS OD ON O.OrderID = OD.OrderID
JOIN
Products AS P ON OD.ProductID = P.ProductID
JOIN
Customers AS C ON O.CustomerID = C.CustomerID
WHERE
P.ProductName LIKE '%' + @SearchProductName + '%' -- Search condition
ORDER BY
O.OrderDate DESC, -- Sort by order date
O.OrderID DESC, -- Tie-breaker for orders
P.ProductName ASC -- Tie-breaker for products within an order
OFFSET @OffsetRows ROWS
FETCH NEXT @PageSize ROWS ONLY;

Create SQL query with SqlQueryBuilder 5

            
 var (sql5, parameters5) = new SqlQueryBuilder()  
.Select()
.Columns("O.OrderID","O.OrderDate","C.CompanyName","P.ProductName","OD.Quantity","OD.UnitPrice")
.From("Orders", "O")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("[Order Details]", "OD")
.On(new Column("O.OrderID").Equale(new Column("OD.OrderID"))),
new INNERJOIN().TableName("Products", "P")
.On(new Column("OD.ProductID").Equale(new Column("P.ProductID"))),
new INNERJOIN().TableName("Customers", "C")
.On(new Column("O.CustomerID").Equale(new Column("C.CustomerID")))
})
.Where(new Where(new LIKE(new Column("P.ProductName"), "%chai%")))
.OrderBy(new OrderBy().SetColumnDescending("O.OrderDate")
.SetColumnDescending("O.OrderID")
.SetColumnAscending("P.ProductName").Offset(0, 10))
.Build();

Query build by SqlQueryBuilder 5

            
SELECT O.OrderID,
       O.OrderDate,
       C.CompanyName,
       P.ProductName,
       OD.Quantity,
       OD.UnitPrice
FROM Orders AS O
     INNER JOIN
     [Order Details] AS OD
     ON O.OrderID = OD.OrderID
     INNER JOIN
     Products AS P
     ON OD.ProductID = P.ProductID
     INNER JOIN
     Customers AS C
     ON O.CustomerID = C.CustomerID
WHERE P.ProductName LIKE @pMAIN_2507200208305327640
ORDER BY O.OrderDate DESC, O.OrderID DESC, P.ProductName ASC
OFFSET @pMAIN_2507200208305327641 ROWS FETCH NEXT @pMAIN_2507200208305327642 ROWS ONLY;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208305327640 %chai%
@pMAIN_2507200208305327641 0
@pMAIN_2507200208305327642 10

Query Results 5:

  OrderID OrderDate CompanyName ProductName Quantity UnitPrice
1 11070 5/5/1998 12:00:00 AM Lehmanns Marktstand Chai 40 18.0000
2 11047 4/24/1998 12:00:00 AM Eastern Connection Chai 25 18.0000
3 11035 4/20/1998 12:00:00 AM Suprêmes délices Chai 10 18.0000
4 11031 4/17/1998 12:00:00 AM Save-a-lot Markets Chai 45 18.0000
5 11025 4/15/1998 12:00:00 AM Wartian Herkku Chai 10 18.0000
6 11006 4/7/1998 12:00:00 AM Great Lakes Food Market Chai 8 18.0000
7 11005 4/7/1998 12:00:00 AM Wilman Kala Chai 2 18.0000
8 11003 4/6/1998 12:00:00 AM The Cracker Box Chai 4 18.0000
9 10935 3/9/1998 12:00:00 AM Wellington Importadora Chai 21 18.0000
10 10918 3/2/1998 12:00:00 AM Bottom-Dollar Markets Chai 60 18.0000


6. Pagination with Total Row Count in a Single Query

SQL Server Query 6

            
 -- Parameters for pagination  
DECLARE @PageNumber INT = 2;
DECLARE @PageSize INT = 5;

-- Calculate the number of rows to skip
DECLARE @OffsetRows INT = (@PageNumber - 1) * @PageSize;

SELECT
OrderID,
CustomerID,
OrderDate,
Freight,
-- Window function to get the total count of rows without pagination
COUNT(*) OVER() AS TotalRowCount
FROM
Orders
WHERE
OrderDate >= '1997-01-01' -- Example filter
ORDER BY
OrderDate ASC,
OrderID ASC
OFFSET @OffsetRows ROWS
FETCH NEXT @PageSize ROWS ONLY;

Create SQL query with SqlQueryBuilder 6

            
 var (sql6, parameters6) = new SqlQueryBuilder()  
.Select()
.Columns("OrderID","CustomerID","OrderDate","Freight")
.Column(new COUNT(new Column("OrderID")).OVER(new OVER()), "TotalRowCount")
.From("Orders", "O")
.Where(new Where(new Column("OrderDate").GreaterThanOrEqualeTo("1997-01-01")))
.OrderBy(new OrderBy().SetColumnAscending("OrderDate")
.SetColumnAscending("OrderID").Offset(5, 5))
.Build();

Query build by SqlQueryBuilder 6

            
SELECT OrderID,
       CustomerID,
       OrderDate,
       Freight,
       COUNT(OrderID) OVER () AS TotalRowCount
FROM Orders AS O
WHERE OrderDate >= @pMAIN_2507200208305415960
ORDER BY OrderDate ASC, OrderID ASC
OFFSET @pMAIN_2507200208305415961 ROWS FETCH NEXT @pMAIN_2507200208305415962 ROWS ONLY;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208305415960 1997-01-01
@pMAIN_2507200208305415961 5
@pMAIN_2507200208305415962 5

Query Results 6:

  OrderID CustomerID OrderDate Freight TotalRowCount
1 10405 LINOD 1/6/1997 12:00:00 AM 34.8200 678
2 10406 QUEEN 1/7/1997 12:00:00 AM 108.0400 678
3 10407 OTTIK 1/7/1997 12:00:00 AM 91.4800 678
4 10408 FOLIG 1/8/1997 12:00:00 AM 11.2600 678
5 10409 OCEAN 1/9/1997 12:00:00 AM 29.8300 678


7. For each order, find the details of the previous order placed by the same customer, sorted by OrderDate

SQL Server Query 7

            
 SELECT  
O.OrderID,
O.CustomerID,
O.OrderDate,
LAG(O.OrderID) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate) AS PreviousOrderID,
LAG(O.OrderDate) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate) AS PreviousOrderDate,
LAG(SUM(OD.Quantity * OD.UnitPrice)) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate) AS PreviousOrderTotal
FROM
Orders AS O
JOIN
[Order Details] AS OD ON O.OrderID = OD.OrderID
GROUP BY
O.OrderID, O.CustomerID, O.OrderDate -- Group by order details before window function
ORDER BY
O.CustomerID, O.OrderDate
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY

Create SQL query with SqlQueryBuilder 7

            
 var (sql7, parameters7) = new SqlQueryBuilder()  
.Select()
.Columns("O.OrderID","O.CustomerID","O.OrderDate")
.Column(new LAG(new Column("O.OrderID")).PARTITION_BY(new Column("O.CustomerID"))
.ORDER_BY(new OrderBy().SetColumnAscending("O.OrderDate")), "PreviousOrderID")
.Column(new LAG(new Column("O.OrderDate")).PARTITION_BY(new Column("O.CustomerID"))
.ORDER_BY(new OrderBy().SetColumnAscending("O.OrderDate")), "PreviousOrderDate")
.Column(new LAG(new SUM(new ColumnArithmatic("OD.Quantity").MULTIPLY("OD.UnitPrice")))
.PARTITION_BY(new Column("O.CustomerID"))
.ORDER_BY(new OrderBy().SetColumnAscending("O.OrderDate")), "PreviousOrderTotal")
.From("Orders", "O")
.Join(new List<IJoin>()
{
new INNERJOIN().TableName("[Order Details]", "OD")
.On(new Column("O.OrderID").Equale(new Column("OD.OrderID")))
})
.GroupBy(new GroupBy("O.OrderID", "O.CustomerID", "O.OrderDate"))
.OrderBy(new OrderBy().SetColumnAscending("O.CustomerID")
.SetColumnAscending("O.OrderDate").Offset(10, 10))
.Build();

Query build by SqlQueryBuilder 7

            
SELECT O.OrderID,
       O.CustomerID,
       O.OrderDate,
       LAG(O.OrderID, @pMAIN_2507200208305468750) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate ASC) AS PreviousOrderID,
       LAG(O.OrderDate, @pMAIN_2507200208305468751) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate ASC) AS PreviousOrderDate,
       LAG(SUM(OD.Quantity * OD.UnitPrice), @pMAIN_2507200208305468752) OVER (PARTITION BY O.CustomerID ORDER BY O.OrderDate ASC) AS PreviousOrderTotal
FROM Orders AS O
     INNER JOIN
     [Order Details] AS OD
     ON O.OrderID = OD.OrderID
GROUP BY O.OrderID, O.CustomerID, O.OrderDate
ORDER BY O.CustomerID ASC, O.OrderDate ASC
OFFSET @pMAIN_2507200208305468753 ROWS FETCH NEXT @pMAIN_2507200208305468754 ROWS ONLY;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200208305468750 1
@pMAIN_2507200208305468751 1
@pMAIN_2507200208305468752 1
@pMAIN_2507200208305468753 10
@pMAIN_2507200208305468754 10

Query Results 7:

  OrderID CustomerID OrderDate PreviousOrderID PreviousOrderDate PreviousOrderTotal
1 10365 ANTON 11/27/1996 12:00:00 AM
2 10507 ANTON 4/15/1997 12:00:00 AM 10365 11/27/1996 12:00:00 AM 403.2000
3 10535 ANTON 5/13/1997 12:00:00 AM 10507 4/15/1997 12:00:00 AM 881.2500
4 10573 ANTON 6/19/1997 12:00:00 AM 10535 5/13/1997 12:00:00 AM 2156.5000
5 10677 ANTON 9/22/1997 12:00:00 AM 10573 6/19/1997 12:00:00 AM 2082.0000
6 10682 ANTON 9/25/1997 12:00:00 AM 10677 9/22/1997 12:00:00 AM 956.9000
7 10856 ANTON 1/28/1998 12:00:00 AM 10682 9/25/1997 12:00:00 AM 375.5000
8 10355 AROUT 11/15/1996 12:00:00 AM
9 10383 AROUT 12/16/1996 12:00:00 AM 10355 11/15/1996 12:00:00 AM 480.0000
10 10453 AROUT 2/21/1997 12:00:00 AM 10383 12/16/1996 12:00:00 AM 899.0000