多个Sql计数

时间:2011-06-23 19:12:42

标签: sql count

我的数据库中有一个表(tbl_MatterItem),用于跟踪项目的发送和接收日期。如果尚未发送或接收,则值为NULL。我有另一个链接到的表(tbl_Matter),以获取该特定项目的BillingLawyer。

BillingLawyer     ItemSent     ItemReceived
-------------     --------     ------------
   Alison         09/09/09        NULL
   Alison         10/10/10        NULL
   Alison         11/11/11       13/11/11
   Alison         12/12/12        NULL

我想为每位律师检索一行,包括他们的姓名,发送的物品数量以及收到的物品数量。

BillingLawyer    Sent    Received
-------------    -----   --------
   Alison         4         1

以下是我到目前为止:

SELECT BillingLawyer, 
(SELECT COUNT(DISTINCT itemSent)FROM tbl_matteritem mit WHERE itemid=2 AND itemSent IS NOT NULL AND mit.ItemSent= mi.itemSent) AS [Sent], 
(SELECT COUNT(DISTINCT itemReceived)FROM tbl_matteritem mitm WHERE itemid=2 AND itemReceived IS NOT NULL AND mitm.itemreceived = mi.itemreceived)AS Received
FROM tbl_matteritem mi JOIN tbl_matter m ON mi.matterid = m.matterid
GROUP BY BillingLawyer, ItemSent, itemreceived
ORDER BY 1

但是我的结果显示有一个额外的记录,看起来是什么位值?:

BillingLawyer    Sent    Received
-------------    ----    --------
   Alison         0         0
   Alison         1         1
   Alison         1         0
   Alison         1         0
   Alison         1         0

我出错的任何想法?

4 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
    BillingLawyer,
    SUM(CASE WHEN ItemSent IS NOT NULL THEN 1 ELSE 0 END) AS Sent,
    SUM(CASE WHEN ItemReceived IS NOT NULL THEN 1 ELSE 0 END) AS Received
FROM
    tbl_matteritem mi
JOIN tbl_matter m ON
    mi.matterid = m.matterid
GROUP BY BillingLawyer
ORDER BY BillingLawyer

答案 1 :(得分:0)

您在ItemSent上进行分组,因此count(distinct ItemSent)将返回1或0.毕竟,将为ItemSent的每个不同值创建一个新组,然后count()将应用于该组。

如果您想按BillingLawyer计算项目,请在BillingLawyer上分组,而不是ItemSent

答案 2 :(得分:0)

我首先删除DISTINCT,因为它会计入每个日期。

SELECT BillingLawyer, 
(SELECT COUNT( itemSent)FROM tbl_matteritem mit WHERE itemid=2 AND itemSent IS      NOT NULL AND mit.ItemSent= mi.itemSent) AS [Sent], 
(SELECT COUNT( itemReceived)FROM tbl_matteritem mitm WHERE itemid=2 AND itemReceived IS NOT NULL AND mitm.itemreceived = mi.itemreceived)AS Received
FROM tbl_matteritem mi JOIN tbl_matter m ON mi.matterid = m.matterid
GROUP BY BillingLawyer, ItemSent, itemreceived
ORDER BY 1

答案 3 :(得分:0)

请勿在{{1​​}}中加入ItemSent, itemreceived。 仅使用GROUP BY