例如,有以下数据:
a 10
b 5
c 15
d 2
a 3
b 6
c 8
d 10
如何将a
和b
加在一起,c
和d
得到这样的结果?
ab 24
cd 35
答案 0 :(得分:3)
select sum(case when col1 in ('a','b') then col2 end) as ab_sum,
sum(case when col1 in ('c','d') then col2 end) as cd_sum
from your_table
答案 1 :(得分:2)
这也可以帮到你,
DECLARE @TAB TABLE(NAME VARCHAR(1), MARK INT)
INSERT INTO @TAB VALUES
('A',10),
('B', 5),
('C',15),
('D', 2),
('A', 3),
('B', 6),
('C', 8),
('D',10)
SELECT NAME,SUM(MARK)
FROM (
SELECT CASE WHEN NAME IN ('A','B') THEN 'AB' WHEN NAME IN ('C','D') THEN 'CD' END NAME,
MARK
FROM @TAB A
) LU
GROUP BY NAME
答案 2 :(得分:1)
尝试:
select
'ab' col1,
SUM(col2) col2
from tbl
where col1 in ('a', 'b')
union
select
'cd',
SUM(col2)
from tbl
where col1 in ('c', 'd')
答案 3 :(得分:1)
对我来说似乎是一个很好的机会:
| CODE_RANGE | RANGE_VALUE |
|------------|-------------|
| ab | 24 |
| cd | 35 |
SELECT
CASE
WHEN code BETWEEN 'a' AND 'b' THEN 'ab'
WHEN code BETWEEN 'c' AND 'd' THEN 'cd' END AS code_range
, SUM(value) AS range_value
FROM Table1
GROUP BY
CASE
WHEN code BETWEEN 'a' AND 'b' THEN 'ab'
WHEN code BETWEEN 'c' AND 'd' THEN 'cd' END
答案 4 :(得分:0)
SELECT
(CASE col1
WHEN 'a' THEN 'ab'
WHEN 'b' THEN 'ab'
WHEN 'c' THEN 'cd'
WHEN 'd' THEN 'cd'
END) x,
SUM(col2) y
FROM tbl
GROUP BY (CASE col1
WHEN 'a' THEN 'ab'
WHEN 'b' THEN 'ab'
WHEN 'c' THEN 'cd'
WHEN 'd' THEN 'cd'
END)