![](/img/trans.png)
[英]How to update a SQL-Server 2008 table with records from the same table with different ID values
[英]counting records on the same table with different values possibly none sql server 2008
我有一个清单表,其中包含一个条件,即新的,使用过的,其他条件,我正在查询一小部分该数据,并且所有记录集可能仅包含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
提前致谢
;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;
尝试这个 -
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
您可以将其作为交叉表:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.