我正在尝试创建报告,并希望从表格“联系人”中提取一些信息。我试图提取与联系人有关的“顾问”以及根据一系列标准拥有该顾问的联系人数量。这很好并且有效,但是,我想拉出第三列,它也是基于不同标准集的“计数”。这是我遇到麻烦的地方。
目前,我在下面列出了“无法解析查询文本”的信息:
SELECT advisoridName AS Advisor,
COUNT(*) WHERE (advisorid IS NOT NULL) AND (ContactType = 1) AND (StateCode = 0) AS 'Active Participants',
COUNT(*) WHERE (advisorid IS NOT NULL) AND (ContactType = 1) AS 'Total Participants'
FROM Contact
GROUP BY advisoridName, advisorid
ORDER BY PDA
如果你能引导我朝着正确的方向前进,我们将不胜感激。
提前致谢
答案 0 :(得分:1)
COUNT(*)
不是有条件的,至少不是在TSQL中。我建议使用SUM(CASE WHEN
... - 就像这样:
SELECT advisoridName AS Advisor,
SUM(CASE WHEN (advisorid IS NOT NULL) AND (ContactType = 1) AND (StateCode = 0)
THEN 1
ELSE 0
END) AS 'Active Participants',
SUM(CASE WHEN (advisorid IS NOT NULL) AND (ContactType = 1)
THEN 1
ELSE 0
END) AS 'Total Participants'
FROM Contact
GROUP BY advisoridName, advisorid
ORDER BY PDA
答案 1 :(得分:0)
您可以使用COUNT执行相同的操作,但不需要GROUP BY
SELECT COUNT (CASE when advisorid IS NOT NULL AND ContactType = 1 AND StateCode = 0 THEN AdvisorID END ) as ActiveParticipants,
COUNT (CASE when advisorid IS NOT NULL AND ContactType = 1 THEN AdvisorID) as TotalParticipants
FROM Contact
ORDER By PDA