1

我有一个带有条件的库存表,即新的、使用的、其他的,我正在查询一小部分数据,并且所有记录集可能只包含一个或所有条件。我尝试使用 case 语句,但如果没有找到任何条件返回该条件,我需要它返回 0

这是我迄今为止尝试过的:

select(
case
    when new_used = 'N' then 'new'
    when new_used = 'U' then 'used'
    when new_used = 'O' then 'other'
    end
    )as conditions,
    count(*) as count
from myDB
where something = something
group by(
case 
    when New_Used = 'N' then 'new'
    when New_Used = 'U' then 'used'
    when New_Used = 'O' then 'other'
end
)

这将返回如下数据:

conditions | count
------------------
new           10
used          45

我试图让数据返回如下:

conditions | count
------------------
new        | 10
used       | 45
other      | 0

提前致谢

4

3 回答 3

3
;WITH constants(letter,word) AS 
(
  SELECT l,w FROM (VALUES('N','new'),('U','used'),('O','other')) AS x(l,w)
)
SELECT 
  conditions = c.word, 
  [count] = COUNT(x.new_used)
FROM constants AS c
LEFT OUTER JOIN dbo.myDB AS x
ON c.letter = x.new_used
AND something = something
GROUP BY c.word;
于 2013-08-21T16:04:38.513 回答
2

尝试这个 -

DECLARE @t TABLE (new_used CHAR(1))
INSERT INTO @t (new_used)
  SELECT t = 'N'
  UNION ALL 
  SELECT 'N'
  UNION ALL 
  SELECT 'U'

SELECT conditions, ISNULL(r.cnt, 0) AS [count]
FROM (
    VALUES('U', 'used'), ('N', 'new'), ('O', 'other')
) t(c, conditions)
LEFT JOIN (
    SELECT new_used, COUNT(1) AS cnt
    FROM @t
    --WHERE something = something
    GROUP BY new_used
) r ON r.new_used = t.c

在输出 -

new     2
used    1
other   0
于 2013-08-21T16:00:07.653 回答
0

您可以将其作为交叉表进行:

select
sum(case when new_used = 'N' then 1 else 0 end) as N,
sum(case when new_used = 'U' then 1 else 0 end) as U,
sum(case when new_used = 'O' then 1 else 0 end) as Other
from myDB
where something = something
于 2013-08-21T15:59:16.833 回答