1

我在下面有几个代码语句,我正在尝试找出一种方法来使这变得更加简单和容易。我认为 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'
4

3 回答 3

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'
于 2012-10-16T16:46:16.573 回答
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
...
于 2012-10-16T16:46:41.547 回答
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'

这导致每个州名称的条件计数。

于 2012-10-16T16:47:20.017 回答