我正在尝试将UNION
COUNT
查询的结果添加到一起,以便轻松获得“总计”。我的SQL查询是一个简单的UNION
,任何人都可以建议我如何添加生成的结果给我一个总数?
SELECT 'BOXES' AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE = 'TB_BOXES'
GROUP BY RECORD_TABLE
UNION
SELECT 'MAPS' AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE = 'MAPS'
GROUP BY RECORD_TABLE
我的结果如下所示,我想添加一个包含记录总数的“TOTAL”列。
DATASET RECORDS_IN_ARCHIVE
TB_BOXES 3149
TB_MAPS 856
答案 0 :(得分:0)
为UNION
使用公用表表达式应该诀窍:
WITH rawdata AS (
SELECT 'BOXES' AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE = 'TB_BOXES'
GROUP BY RECORD_TABLE
UNION
SELECT 'MAPS' AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE = 'MAPS'
GROUP BY RECORD_TABLE
) SELECT SUM(RECORDS_IN_ARCHIVE) FROM rawdata;
答案 1 :(得分:0)
WITH CTE AS (
SELECT Record_Table, COUNT(Record_Table) Records_In_Archive
FROM dbo.VIEW_GLOBAL_Search
WHERE Record_Table IN ('Maps','TB_Boxes')
GROUP BY Record_Table
ORDER BY Record_Table
)
SELECT ISNULL(Case Record_Table WHEN 'TB_Boxes' THEN 'Boxes' ELSE Record_Table
END,'Total') Record_Table,
SUM(Records_In_Archive) Records_In_Archive
FROM CTE
GROUP BY Case Record_Table WHEN 'TB_Boxes' THEN 'Boxes' ELSE Record_Table END
WITH ROLLUP
ORDER BY Record_Table
虽然,如果您正在寻找单独的结果:
SELECT 'Total', COUNT(Record_Table)
FROM dbo.VIEW_Global_Search
WHERE Record_Table IN ('TB_Boxes','Maps')
为什么要考虑这个?
答案 2 :(得分:0)
你的意思是添加新行总数?
SELECT RECORD_TABLE AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE IN ('TB_BOXES', 'MAPS')
GROUP BY RECORD_TABLE
UNION ALL
SELECT 'TOTAL' AS DATASET,
COUNT(RECORD_TABLE) AS RECORDS_IN_ARCHIVE
FROM dbo.VIEW_GLOBAL_SEARCH
WHERE RECORD_TABLE IN ('TB_BOXES', 'MAPS');