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

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],
       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 に答える