1

我正在尝试查询一些信息并将其显示在一行上。我所拥有的是我的客户的税务信息。我希望返回公司名称、州申报数量以及我们为他们提交的县申报数量。我收到一个错误,要求我在我的组中包含“描述”和“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
4

2 回答 2

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
于 2013-10-22T15:03:41.097 回答
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.

于 2013-10-22T15:04:55.843 回答