在SQL UNION查询中添加列内容

时间:2010-10-28 19:01:19

标签: sql database union union-all

到目前为止,我有这个查询

SELECT
    COUNT(f.code_id) as item_count, 
    f.code_desc
FROM 
    foo f
    INNER JOIN foohistory fh ON f.history_id = fh.history_id
WHERE
    MONTH(fh.create_dt) = 6
    AND YEAR(fh.create_dr) = 2010
GROUP BY 
    f.code_desc

    UNION ALL

SELECT
    COUNT(b.code_id) as item_count, 
    b.code_desc
FROM 
    bar b
    INNER JOIN barhistory bh ON b.history_id = bh.history_id
WHERE
    MONTH(bh.create_dt) = 6
    AND YEAR(bh.create_dr) = 2010
GROUP BY 
    b.code_desc

我的目标是给UNION这两个查询添加SUM'item_count'列foreach code_desc。这可能吗?

2 个答案:

答案 0 :(得分:5)

如果没有关于代码的更多信息,例如,如果代码在两个表之间是互斥的,请使用:

SELECT x.code_desc,
       SUM(x.item_count)
 FROM (SELECT f.code_desc,
              COUNT(f.code_id) as item_count
         FROM foo f
         JOIN foohistory fh ON f.history_id = fh.history_id
        WHERE MONTH(fh.create_dt) = 6
          AND YEAR(fh.create_dr) = 2010
     GROUP BY f.code_desc
       UNION ALL
       SELECT b.code_desc,
              COUNT(b.code_id) as item_count    
         FROM bar b
         JOIN barhistory bh ON b.history_id = bh.history_id
        WHERE MONTH(bh.create_dt) = 6
          AND YEAR(bh.create_dr) = 2010
     GROUP BY b.code_desc) x
GROUP BY x.code_desc

答案 1 :(得分:0)

是的,做这样的事情

SELECT Sum(unionedTable.item_count)
FROM 
(
//your query 


) as unionedTable