[英]Combining three similar sql queries into a single result
我有一张桌子说(TimeValue)像这样
Time Value Owner
======================
1 10 A
2 20 B
3 30 C
4 40 A
5 50 B
6 60 C
7 70 A
8 80 B
现在我有三个sql语句,如下所示
select owner, value as 'First sql' from TimeValue where time >= 1 and time <= 3 group by owner
select owner, value as 'Second sql' from TimeValue where time >= 4 and time <= 6 group by owner
select owner, value as 'Third sql' from TimeValue where time >= 7 and time <= 9 group by owner
现在这些是上面的sql的结果
1。
Value Owner
=================
10 A
20 B
30 C
2。
Value Owner
=================
40 A
50 B
60 C
3
Value Owner
===============
70 A
80 B
90 C
我的问题是,如果我想要以下结果,sql语句将是什么?
Owner First SQL Second SQL Third SQL
==================================================
A 10 40 70
B 20 50 80
C 30 60 90
先感谢您
一种方法是使用CASE
语句,如下所示:
SELECT
owner
, MAX(CASE WHEN time >= 1 AND time <= 3 THEN value ELSE NULL END) AS FIRST
, MAX(CASE WHEN time >= 4 AND time <= 6 THEN value ELSE NULL END) AS SECOND
, MAX(CASE WHEN time >= 7 AND time <= 9 THEN value ELSE NULL END) AS THIRD
FROM TimeValue
GROUP BY owner
请注意,您需要在value
周围添加一个汇总函数,例如MAX
。 实际上,如果没有RDBMS引擎的聚合功能,许多引擎甚至都不会采用SQL。
select owner,
SUM(case when (time >= 1 and time <= 3) then value end) as 'FirstSQL',
SUM(case when (time >= 4 and time <= 6) then value end) as 'SecondSQL',
SUM(case when (time >= 7 and time <= 9) then value end) as 'ThirdSQL'
from TimeValue
group by owner
根据您的示例,您应该使用SUM而不是MAX
dasblinkenlight的想法相同,但方法不同,我同意汇总功能,例如MAX或SUM
SELECT
owner,
MAX(IF(time between 1 and 3, value,NULL) ) as first,
MAX(IF(time between 4 and 6, value,NULL) ) as sec,
MAX(IF(time between 7 and 9, value,NULL) ) as third
FROM TimeValue
GROUP BY owner
您还可以使用自我联接:
select
tv0.owner
, tv0.value sql1
, tv1.value sql2
, tv2.value sql3
from timevalue tv0
inner join timevalue tv1 on tv1.owner = tv0.owner
inner join timevalue tv2 on tv2.owner = tv0.owner
where tv0.time between 1 and 3
and tv1.time between 4 and 6
and tv2.time between 7 and 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.