我在下面有几个代码陈述,我试图找到一种方法来使这更简单,更容易。我认为CASE声明是最好的,但经过几天的反复试验,我一直无法弄清楚如何做到这一点。任何和所有的帮助和/或解释将不胜感激。
select Count(lcs.statename) as [Name 1]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
where lcs.statename = 'Follow Up'
AND lcnum = '412'
AND status = '0'
select Count(lcs.statename) as [Name 2]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
where lcs.statename = 'Initial Review'
AND lcnum = '412'
AND status = '0'
select Count(lcs.statename) as [Name 3]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
where lcs.statename = 'Execution'
AND lcnum = '412'
AND status = '0'
select Count(lcs.statename) as [Name 4]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
where lcs.statename = 'Holdback'
AND lcnum = '412'
AND status = '0'
答案 0 :(得分:2)
尝试类似:
SELECT SUM(CASE WHEN lcs.statename = 'Follow Up' THEN 1 ELSE 0 END) as [Name 1],
SUM(CASE WHEN lcs.statename = 'Initial Review' THEN 1 ELSE 0 END) as [Name 2],
SUM(CASE WHEN lcs.statename = 'Execution' THEN 1 ELSE 0 END) as [Name 3],
SUM(CASE WHEN lcs.statename = 'Holdback' THEN 1 ELSE 0 END) as [Name 4]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
WHERE lcnum = '412'
AND status = '0'
答案 1 :(得分:1)
您可以使用SUM()和CASE:
来完成SELECT
SUM(CASE WHEN lcs.statename = 'Follow Up' THEN 1 ELSE 0 END) as [Name 1],
SUM(CASE WHEN lcs.statename = 'Initial Review' THEN 1 ELSE 0 END) as [Name 2],
...
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
WHERE lcnum = '412' AND status = '0';
或者,如果您可以阅读多行,则可以使用GROUP BY
:
SELECT lcs.statename, COUNT(*) AS num
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
WHERE lcnum = '412' AND status = '0'
GROUP BY lcs.statename;
会给你类似的东西
Follow Up 25
Initial Review 17
...
答案 2 :(得分:0)
您可以将CASE语句与SUM()
函数一起使用,如下所示:
SELECT SUM(CASE WHEN lcs.statename = 'Follow Up' THEN 1 ELSE 0 END) as [Name 1],
SUM(CASE WHEN lcs.statename = 'Initial Review' THEN 1 ELSE 0 END) as [Name 2],
SUM(CASE WHEN lcs.statename = 'Execution' THEN 1 ELSE 0 END) as [Name 3],
SUM(CASE WHEN lcs.statename = 'Holdback' THEN 1 ELSE 0 END) as [Name 4]
FROM hsi.itemlc as ilc
LEFT JOIN hsi.lcstate as lcs on lcs.statenum = ilc.statenum
WHERE lcnum = '412'
AND status = '0'
导致每个州名的条件计数。