SQL计数麻烦

时间:2014-05-08 14:27:37

标签: sql sql-server sql-server-2008 count

我有以下方案

我需要计算有多少客户的未付款状态。并且此计数必须仅显示具有计数>= 2的计数。这部分我正确地做(我认为):

--SELECTING Client Count
SELECT Client, COUNT(HyphenStatus) as UnpaidCount
FROM CasesFromSimplicity
WHERE HyphenStatus = 'UnPaid' AND FCManager = 'Mike'
GROUP BY Client
HAVING COUNT(HyphenStatus) >= 2
ORDER BY Client ASC

然后我需要为经理视图创建一个看起来像这样的表:

+-----------+--------------+----------------+------------+
| FCManager | CountingTwos | CountingThrees | FourOrMore |
+-----------+--------------+----------------+------------+
| Mike      |            2 |              1 |          1 |
+-----------+--------------+----------------+------------+

这告诉我,我的顾问Mike有两个客户,其中包含count of 2one client with a count of 3以及one client with a count of 4

我此刻已经做了以下查询,但这似乎没有起作用。

--Selecting the count for manager
SELECT
FCManager
,(SELECT COUNT(HyphenStatus) FROM CasesFromSimplicity WHERE HyphenStatus = 'UnPaid' AND FCManager = 'Mike' HAVING COUNT(HyphenStatus) = 2) CountingTwos
,(SELECT COUNT(HyphenStatus) FROM CasesFromSimplicity WHERE HyphenStatus = 'UnPaid' AND FCManager = 'Mike' HAVING COUNT(HyphenStatus) = 3) CountingThrees
,(SELECT COUNT(HyphenStatus) FROM CasesFromSimplicity WHERE HyphenStatus = 'UnPaid' AND FCManager = 'Mike' HAVING COUNT(HyphenStatus) >= 4) FourOrMore
FROM CasesFromSimplicity
GROUP BY FCManager

有谁能告诉我我做错了什么?或者把我送到正确的地方阅读。我在搜索时找不到任何东西。 我在发帖时一直在想,我会在子查询中需要一个组,但是这会返回多于1个结果而不起作用?

我为您创建了一个SQL Fiddle来查看我的问题。

感谢Mike,感谢任何帮助。

如果我需要进一步解释,请告诉我?我正在使用SQL SERVER 2008

1 个答案:

答案 0 :(得分:2)

好吧,假设SQL Server 2005+,你可以这样做:

;WITH CTE AS
(
    SELECT  FCManager,
            Client, 
            COUNT(HyphenStatus) as UnpaidCount
    FROM CasesFromSimplicity
    WHERE HyphenStatus = 'UnPaid' 
    GROUP BY FCManager,
             Client
    HAVING COUNT(HyphenStatus) >= 2
)
SELECT  FCManager,
        SUM(CASE WHEN UnpaidCount = 2 THEN 1 ELSE 0 END) CountingTwos,
        SUM(CASE WHEN UnpaidCount = 3 THEN 1 ELSE 0 END) CountingThrees,
        SUM(CASE WHEN UnpaidCount > 3 THEN 1 ELSE 0 END) FourOrMore 
FROM CTE 
GROUP BY FCManager

Here is修改后的sqlfiddle。