我想让[LA,LI,LS,LU,LX,LY] = LUFT以及[XY,MN,ST] = BASE 请参阅下文以了解更多信息 这是我的疑问:
SELECT
[ABC] = 'LUFT',
ROUND(SUM([GWU VS]),1) AS [GWU LUFT],
[ABC] = 'BASE',
ROUND(SUM([GWU VS]),1) AS [GWU BASE]
FROM tbl1
WHERE [ABC]='LA' OR [ABC]='LI' OR [ABC]='LS'
OR [ABC]='LU' OR [ABC]='LX' OR [ABC]='LY'
AND
[ABC]='XY' OR [ABC]='MN' OR [ABC]='ST'
--GROUP BY [ABC]
--ORDER BY [ABC] ASC
我的表:
ABC GWU VS
LA 100
LI 80
LS 50
LU 200
LX 220
LY 150
XY 450
MN 600
ST 85
但我得到了错误的结果 我真正希望得到的结果是:
ABC GWU VS
LUFT 800
BASE 1135
答案 0 :(得分:0)
case
是最明显的答案:
sum(case when [ABC] in ('LA', 'LI', ...) then [GWU VS] else 0 end) AS [GWU LUFT],
答案 1 :(得分:0)
这将按照您的要求提供结果:
SELECT
'LUFT' as [ABC],
ROUND(SUM([GWU VS]),1) AS [GWU VS]
FROM tbl1
WHERE ([ABC] IN ('LA','LI','LS','LU','LX','LY'))
UNION
SELECT
'BASE' as [ABC],
ROUND(SUM([GWU VS]),1) AS [GWU VS]
FROM tbl1
WHERE ([ABC] IN ('LA','LI','LS'))
答案 2 :(得分:0)
使用Case
语句将ABC
列分为两组,然后应用group by
。试试这个。
SELECT ABC=CASE
WHEN abc IN ( 'LA', 'LI', 'LS', 'LU','LX', 'LY' ) THEN 'LUFT'
ELSE 'BASE'
END,
[GWU VS]=Sum([GWU VS])
FROM Yourtable
GROUP BY CASE
WHEN abc IN ( 'LA', 'LI', 'LS', 'LU','LX', 'LY' ) THEN 'LUFT'
ELSE 'BASE'
END