总计数(与分组相乘)

时间:2013-12-17 21:34:32

标签: sql sql-server count sum

我正在花时间搞清楚如何总结这两个查询的总和:

select t.processed as title, count(t.processed) as ckos
from circ_longterm_history clh, title t
where t.bib# = clh.bib#
and clh.cko_location = 'dic'
group by t.processed
order by ckos DESC

select t.processed as title, count(t.processed) as ckos
from circ_history ch, title t, item i
where i.item# = ch.item#
and t.bib# = i.bib#
and ch.cko_location = 'dic'
group by t.processed
order by ckos DESC

基本上我想要一个结果集,其中一列为t.processed,另一列为第一个计数加上第二个计数的总和。

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

SELECT A.title, A.ckos +B.ckos as ckos from
(select t.processed as title, count(t.processed) as ckos
from circ_longterm_history clh, title t
where t.bib# = clh.bib#
and clh.cko_location = 'dic'
group by t.processed
) as A inner join

(select t.processed as title, count(t.processed) as ckos
from circ_history ch, title t, item i
where i.item# = ch.item#
and t.bib# = i.bib#
and ch.cko_location = 'dic'
group by t.processed
) as B on A.title =B.title order by ckos DESC

答案 1 :(得分:0)

; WITH CTE AS (
    SELECT T.PROCESSED AS TITLE, T.PROCESSED AS CKOS
    FROM dbo.CIRC_LONGTERM_HISTORY CLH
    INNER JOIN dbo.TITLE T
    WHERE T.[BIB#] = CLH.[BIB#]
      AND CLH.CKO_LOCATION = 'DIC'

    UNION ALL

    SELECT T.PROCESSED AS TITLE, T.PROCESSED AS CKOS
    FROM dbo.CIRC_HISTORY CH
    INNER JOIN dbo.ITEM I
      ON I.[ITEM#] = CH.[ITEM#]
    INNER JOIN dbo.TITLE T
      ON T.[BIB#] = I.[BIB#]
    WHERE CH.CKO_LOCATION = 'DIC'
)
SELECT TITLE, COUNT(*) AS CKOS
FROM CTE
GROUP BY TITLE
ORDER BY CKOS DESC

答案 2 :(得分:0)

我不知道这是否对您有所帮助

如果你想从2个查询总和,我通常会喜欢这个

示例有一个这样的表:

id     name    
1     jenny     
2     jack 
 
select count(id) as id, name 
from table 
group by name 
union all 
select count(id) as id, name 
from table 
group by name

如果显示如下:

id    name

1     jenny

1     jenny

2     jack

2     jack

所以如果你想加总id 就这样做:

select sum(id), name 
from (select count(name) as id, name from table group by name 
      UNION ALL 
      select count(name) as title, name from table group by name)aa 
group by name

所以看起来像这样:

sum   name

2     jenny

2     jack

但是如果你使用UNION代替UNION ALL 结果将是这样的:

sum   name

1     jenny

1     jack

答案 3 :(得分:0)

我相信以下内容应该有效(尽管我没有样本数据来测试它......):

SELECT t.processed as title, 
       COALESCE(SUM(clh.count), 0) + COALESCE(SUM(ch.count), 0) as ckos
FROM Title t
LEFT JOIN (SELECT bib#, COUNT(*) as count
           FROM Circ_Longterm_History
           WHERE cko_location = 'dic'
           GROUP BY bib#) clh
       ON clh.bib# = t.bib#
LEFT JOIN (SELECT i.bib#, COUNT(*) as count
           FROM Item i
           JOIN Circ_History ch
             ON ch.item# = i.item#
           WHERE ch.cko_location = 'dic'
           GROUP BY i.bib#) ch
       ON ch.bib# = t.bib#
GROUP BY t.processed
ORDER BY ckos DESC