我在这张桌子上形成一个查询时需要帮助:
COUNT | Region
2 West
3 W
4 East
5 E
描述: 当Region值为West时,计数表示SUCCESS。当Region值为W时,count表示ERROR
我想要这样的事情:
Region | Total| Error | Success
West | 5 | 3 | 2
EAST | 9 | 5 | 4
第一个表是另一个查询的输出。我可以在另一个内部编写一个查询来获取它,但是如何让CASE语句工作。
答案 0 :(得分:1)
正如@jarlh所说:不要存储这样的数据。改变你的桌面设计。但目前你可以使用
select case when region in ('West','W') then 'West'
when region in ('East','E') then 'East'
end as Region,
sum(count) as total,
sum(case when region in ('W','E') then count end) as error,
sum(case when region not in ('W','E') then count end) as success
from your_table
group by case when region in ('West','W') then 'West'
when region in ('East','E') then 'East'
end
答案 1 :(得分:0)
对于你正在做的事情似乎并不正确,但如果它是什么,那么这应该可以胜任。
declare @t table ([Count] int, Region varchar(32))
insert @t ([Count], Region) values (2, 'West'), (3, 'W'), (4, 'East'), (5, 'E')
select
coalesce(t1.Region, t2.Region) as Region,
isnull(t1.[Count], 0) + isnull(t2.[Count], 0) as Total,
isnull(t2.[Count], 0) as Error,
isnull(t1.[Count], 0) as Success
from
@t t1
full outer join @t t2 on t2.Region = left(t1.Region, 1)
where
len(t1.Region) > 1
我使用了完整的外部联接,因为您没有声明数据将始终配对,即可能有“东部”没有“E”。
答案 2 :(得分:0)
使用Core SQL-2003之外的以下功能:F591,“派生表”
select region,
sum(error+success) total,
sum(error) error,
sum(success) success
from
(select case when char_length(Region) = 1 then count else 0 end as error,
case when char_length(Region) > 1 then count else 0 end as success,
case Region when 'W' then 'West'
when 'E' then 'East'
else Region end as Region
from tablename)
group by region
(未测试...)