Reconcile sets and label subtotal rows
Compare distinct sets with `EXCEPT` and `INTERSECT`, then use `GROUPING SETS` and `GROUPING_ID` to distinguish detail rows from subtotals.
What you are trying to do
A data migration review must identify keys present on only one side and produce detail, regional subtotal, and grand total rows from a synthetic sales feed.
Work through it
- Run the first statement and read its
GROUPING_ID. Zero marks a detail group. One marks a regional subtotal. Three marks the grand total. - Notice that a source
NULLregion at detail level hasGROUPING_IDzero. The grouping bit distinguishes that real null from a subtotal null. - Run the reconciliation statement.
EXCEPTandINTERSECTcompare distinct result sets. Their semantics treat matching NULL values as equal for this comparison. - The left-only set contains key 1, the right-only set contains key 3, and the shared set contains keys 2 and NULL. Duplicate key 2 is collapsed by the set operators.
- Review the exact grouping and set-operator rules in Microsoft's references. GROUP BY · EXCEPT and INTERSECT
Check your work
The aggregate output includes detail, regional subtotal, and grand total levels with grouping IDs 0, 1, and 3. The reconciliation output labels key 1 as left only, key 3 as right only, and key 2 plus NULL as present in both.
Practice SQL
Open in SQL Flow;WITH Sales AS (
SELECT Region, ProductGroup, Amount
FROM (VALUES
(CAST(N'North' AS nvarchar(10)), N'Books', 20),
(N'North', N'Tools', 30),
(N'South', N'Books', 15),
(CAST(NULL AS nvarchar(10)), N'Tools', 7)
) AS v(Region, ProductGroup, Amount)
)
SELECT Region, ProductGroup, SUM(Amount) AS TotalAmount, GROUPING_ID(Region, ProductGroup) AS GroupingLevel
FROM Sales
GROUP BY GROUPING SETS ((Region, ProductGroup), (Region), ())
ORDER BY GroupingLevel, Region, ProductGroup;
;WITH LeftRows AS (
SELECT ItemId FROM (VALUES (1), (2), (2), (CAST(NULL AS int))) AS v(ItemId)
), RightRows AS (
SELECT ItemId FROM (VALUES (2), (3), (CAST(NULL AS int))) AS v(ItemId)
)
SELECT N'Left only' AS ResultSet, ItemId
FROM (SELECT ItemId FROM LeftRows EXCEPT SELECT ItemId FROM RightRows) AS Difference
UNION ALL
SELECT N'Right only', ItemId
FROM (SELECT ItemId FROM RightRows EXCEPT SELECT ItemId FROM LeftRows) AS Difference
UNION ALL
SELECT N'In both', ItemId
FROM (SELECT ItemId FROM LeftRows INTERSECT SELECT ItemId FROM RightRows) AS Shared
ORDER BY ResultSet, ItemId;
Knowledge check
Commands in this lesson
Next lesson Test an index with measured plan evidence