我正在尝试查询某些信息并将其显示在一行上。我所拥有的是我的客户的税务信息。我希望返回公司名称和州备案数量以及我们为他们提供的县备案数量。我收到一个错误,要求我在我的小组中加入'description'和'tcode',但是当我这样做时,我只得到1作为计数。此外,我得到几行信息,它最终显示如下
co StateFilingCount LocalFilingCount
Co NULL NULL
Co NULL 1
Co 1 NULL
SELECT DISTINCT CT.co,
CASE WHEN description LIKE '%SITW' THEN COUNT(tcode) END AS StateFilingCount,
CASE WHEN tcode LIKE '__-%' THEN COUNT(tcode) END AS LocalFilingCount FROM CTax CT
WHERE tcode NOT LIKE 'ss-%' AND CT.endDate > GETDATE()
GROUP BY CT.co
ORDER BY CT.co ASC
答案 0 :(得分:0)
我想你想要一个小组计数。一种方法是:
SELECT DISTINCT CT.co,
SUM(CASE WHEN description LIKE '%SITW' THEN 1 ELSE 0 END) AS StateFilingCount,
SUM(CASE WHEN tcode LIKE '__-%' THEN 1 ELSE 0 END) AS LocalFilingCount
FROM CTax CT
WHERE tcode NOT LIKE 'ss-%'
AND CT.endDate > GETDATE()
GROUP BY CT.co
ORDER BY CT.co ASC
答案 1 :(得分:0)
使用SQL小提琴这会更容易,但我会拍摄一下:
SELECT
CT.co,
COUNT(CASE WHEN description LIKE '%SITW' THEN tcode END) AS StateFilingCount,
COUNT(CASE WHEN tcode LIKE '__-%' THEN tcode END) AS LocalFilingCount
FROM CTax CT
WHERE tcode NOT LIKE 'ss-%' AND CT.endDate > GETDATE()
GROUP BY CT.co
ORDER BY CT.co ASC
我会尝试将COUNT
移到CASE
语句之外。你也应该能够摆脱DISTINCT
,因为你正在做GROUP BY
。