Sql-Server
SQL 查詢 - 如何選擇顯示組、組總計、總計?
我已經看到了一些建議,但想知道從數據表中選擇組、組總計、總計的最佳方法,而不使用子查詢或不必要的連接。
我最初的想法是這樣的:
select product_family, sum(widgets), sum(widgets) over () from table.widget group by product_family
或以下內容:
select product_family, sum(widgets), sum(widgets) over (partition by all_field) from table.widget group by product_family
顯然這些都不起作用。我知道一個分區可以比實際的行/組具有更高的順序,但不是如何按“全部”進行分區,而不是將其留空作為第一個範例。但是,它與 group by 語句中斷。
我能找到的最好的是這樣的:
select product_family, family_sum, sum(family_sum) over () as grand_sum from ( select product_family, sum(widgets) from table.widget group by product_family ) as A
不過,這仍然涉及一個子查詢,這沒關係。我只是覺得我在這裡缺少一個簡單的功能。
GROUP BY ROLLUP
或者 - 甚至更好 -GROUP BY GROUPING SETS
如果您想要一個額外的總計行是最好的。如果您想要每一行的總計 - 在另一列中 - 那麼您的查詢需要進行微調。
SUM(widgets)
您可以在視窗函式中使用聚合:select product_family, sum(widgets) as total, sum(sum(widgets)) over () as grand_total from table.widget group by product_family ;
GROUP BY ROLLUP
做你想做的事。舉個例子:
SELECT o.schema_id , type_desc , [Count Of Objects] = COUNT(o.object_id) FROM sys.objects o GROUP BY ROLLUP (o.schema_id, o.type_desc)
這會產生以下輸出:
╔═══════════╦════════════════════════╦══════════════════╗ ║ schema_id ║ type_desc ║ 對象計數 ║ ╠═══════════╬════════════════════════╬══════════════════╣ ║ 1 ║ PRIMARY_KEY_CONSTRAINT ║ 7 ║ ║ 1 ║ SERVICE_QUEUE ║ 3 ║ ║ 1 ║ USER_TABLE ║ 8 ║ ║ 1 ║ 空 ║ 18 ║ ║ 4 ║ INTERNAL_TABLE ║ 16 ║ ║ 4 ║ SYSTEM_TABLE ║ 72 ║ ║ 4 ║ 空 ║ 88 ║ ║空║空║106║ ╚═══════════╩════════════════════════╩══════════════════╝
前
NULL
兩列中顯示的表示累計金額。為了使它“漂亮”,您可以使用一些替代值來代替
NULL
匯總值:SELECT [Schema Name] = CASE WHEN s.name IS NULL THEN '[Grand Total]' ELSE s.name END , [Object Type] = CASE WHEN o.type_desc IS NULL THEN '[Total - ' + COALESCE(s.name, 'Overall') + ']' COLLATE SQL_Latin1_General_CP1_CI_AS ELSE o.type_desc END , [Count of Objects] = COUNT(o.object_id) FROM sys.objects o INNER JOIN sys.schemas s ON o.schema_id = s.schema_id GROUP BY ROLLUP (s.name, o.type_desc);
╔═══════════════╦════════════════════════╦══════════════════╗ ║ 架構名稱 ║ 對像類型 ║ 對象計數 ║ ╠═══════════════╬════════════════════════╬══════════════════╣ ║ dbo ║ PRIMARY_KEY_CONSTRAINT ║ 7 ║ ║ dbo ║ SERVICE_QUEUE ║ 3 ║ ║ dbo ║ USER_TABLE ║ 8 ║ ║ dbo ║ [總計 - dbo] ║ 18 ║ ║ 系統 ║ INTERNAL_TABLE ║ 16 ║ ║ 系統 ║ SYSTEM_TABLE ║ 72 ║ ║ 系統 ║ [總計 - 系統] ║ 88 ║ ║【合計】║【合計-合計】║106║ ╚═══════════════╩════════════════════════╩══════════════════╝