多个Sql计数

问题描述

| 我的数据库中有一个表(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
有什么想法我要去哪里吗?     

解决方法

        尝试这个:
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
    ,        您正在
ItemSent
上分组,因此
count(distinct ItemSent
将返回1或0。毕竟,将为different5ѭ的每个不同值创建一个新组,然后将
count()
应用于该组。 如果要按
BillingLawyer
计算项目,请按
BillingLawyer
分组,而不是
ItemSent
。     ,        我想先删除
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
    ,        请勿在
GROUP BY
中包括
ItemSent,itemreceived
。 仅使用
GROUP BY BillingLawyer