开发者

Adding column contents in a SQL UNION query

开发者 https://www.devze.com 2023-01-22 16:18 出处:网络
So far I have this query 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

So far I have this query

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

My goal is to UNION these two queries add SUM the 'item_count' columns foreach code_desc. Is this possible?


Without more information about the codes, like if it's possible that codes are mutually exclusive between the two tables, use:

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


Yeah, doing something like this

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


) as unionedTable
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号