我想将结果集中的某些值分组为新值。
例如我的结果集是:
KS2
2a
3c
4c
3c
2a
2a
1c
No KS2
1b
2c
5c
4c
我在底部组中的currrent SQL会产生以下结果:
KS2
2a
3c
4c
1c
No KS2
1b
2c
5c
4c
我想将值1a,1b和1c分组为值1和2a,2b和2c的单行为2.所有其他值应正常分组。所以我的结果集看起来像:
KS2
2
3c
4c
1
No KS2
5c
4c
这是我的代码:
GROUP BY
CASE Name
WHEN 'English' THEN
CASE WHEN [Ks2en]=NULL OR [Ks2en]='' THEN
'No KS2'
ELSE
[Ks2en]
END
WHEN 'Mathematics' THEN
CASE WHEN [Ks2ma]=NULL OR [Ks2ma]='' THEN
'No KS2'
ELSE
[Ks2ma]
END
ELSE
CASE WHEN [Ks2av]=NULL OR [Ks2av]='' THEN
'No KS2'
ELSE
[Ks2av]
END
END
编辑:这是基于EricZ答案的解决方案:
GROUP BY
CASE Name
WHEN 'English' THEN
CASE WHEN [Ks2en] IS NULL OR [Ks2en]='' THEN
'No KS2'
WHEN [Ks2en] IN ('1a','1b','1c') THEN
'1'
WHEN [Ks2en] IN ('2a','2b','2c') THEN
'2'
ELSE
[Ks2en]
END
WHEN 'Mathematics' THEN
CASE WHEN [Ks2ma] IS NULL OR [Ks2ma]='' THEN
'No KS2'
WHEN [Ks2ma] IN ('1a','1b','1c') THEN
'1'
WHEN [Ks2ma] IN ('2a','2b','2c') THEN
'2'
ELSE
[Ks2ma]
END
ELSE
CASE WHEN [Ks2av] IS NULL OR [Ks2av]='' THEN
'No KS2'
WHEN [Ks2av] IN ('1a','1b','1c') THEN
'1'
WHEN [Ks2av] IN ('2a','2b','2c') THEN
'2'
ELSE
[Ks2av]
END
END
答案 0 :(得分:1)
你想要这样的东西吗?
GROUP BY
CASE
WHEN Name = 'English' THEN ISNULL(NULLIF([Ks2en],''),'No KS2')
WHEN Name = 'Mathematics' THEN ISNULL(NULLIF([Ks2ma],''),'No KS2')
WHEN [Ks2av] IN ('1a','1b','1c') THEN '1'
WHEN [Ks2av] IN ('2a','2b','2c') THEN '2'
ELSE ISNULL(NULLIF([Ks2av],''),'No KS2')
END
请注意,在您的代码中,[Ks2en]=NULL
始终返回false,您可以使用[Ks2en] IS NULL
来检查NULL值
答案 1 :(得分:0)
您可以使用另一个表来存储“分组行为”。这可以是一个包含('1a','1'),('1b','1'),('2a','2')等条目的两列表格。
这是一个SQLFiddle,其中一个例子放在一起: http://sqlfiddle.com/#!2/deb87/7