我想查询具有不同数据类型的几个变量的数据库。
我的查询如下:
SELECT var1, var2,
SUM( CASE WHEN var3 ='2008' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS 'A1_U18_7',
SUM( CASE WHEN var3='2015' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS 'A34_U15_0',
CASE WHEN var3 = '2015' AND var4 = 'A0_RISE' THEN var5 ELSE 0 END AS 'A0_RISE'
FROM dataset1
GROUP BY var1
实际上我不需要总结前两个查询的结果,否则我会得到一个" 0"作为输出。总之,我得到了正确的答案。
然而,在" A0_RISE"的情况下,这种解决方法是不可行的。因为数据类型是文本。没有SUM函数,我在这里得到了输出" 0"也是。
我如何才能获得所有变量的输出?如果你对双打的SUM解决方案有更好的想法,我会非常感谢你在这里!
答案 0 :(得分:1)
也许使用Max?
SELECT var1, var2,
SUM( CASE WHEN var3 ='2008' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS 'A1_U18_7',
SUM( CASE WHEN var3='2015' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS 'A34_U15_0',
MAX(CASE WHEN var3 = '2015' AND var4 = 'A0_RISE' THEN var5 ELSE '' END ) AS 'A0_RISE'
FROM dataset1
GROUP BY var1
答案 1 :(得分:0)
将 var5转换为整数,就像这个group by var1,var2
一样,并在组中添加var2,如同SELECT var1, var2,
SUM( CASE WHEN var3 ='2008' AND var4='A1_U18' THEN CAST(var5 AS UNSIGNED) ELSE 0 END ) AS 'A1_U18_7',
SUM( CASE WHEN var3='2015' AND var4='A1_U18' THEN CAST(var5 AS UNSIGNED) ELSE 0 END ) AS 'A34_U15_0',
CASE WHEN var3 = '2015' AND var4 = 'A0_RISE' THEN CAST(var5 AS UNSIGNED) ELSE 0 END AS 'A0_RISE'
FROM dataset1
GROUP BY var1,var2
if [ "$foo" != "1" ]
then
echo Success
fi
答案 2 :(得分:0)
也许是group_concat()
?
SELECT var1,
SUM(CASE WHEN var3 ='2008' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS A1_U18_7,
SUM( CASE WHEN var3='2015' AND var4='A1_U18' THEN var5 ELSE 0 END ) AS A34_U15_0,
GROUP_CONCAT(CASE WHEN var3 = '2015' AND var4 = 'A0_RISE' THEN var5 END) AS A0_RISE
FROM dataset1
GROUP BY var1;
请勿在{{1}}中加入var2
,除非您还将其包含在SELECT
中。