简体   繁体   中英

Combining three similar sql queries into a single result

I have a table say (TimeValue) something like this

 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

Now I have three sql statement like the followings

  1. select owner, value as 'First sql' from TimeValue where time >= 1 and time <= 3 group by owner

  2. select owner, value as 'Second sql' from TimeValue where time >= 4 and time <= 6 group by owner

  3. select owner, value as 'Third sql' from TimeValue where time >= 7 and time <= 9 group by owner

Now these are the result of the above 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

My question, what would be the sql statement if I want the following result??

 Owner    First SQL     Second SQL     Third SQL
==================================================
  A        10            40              70
  B        20            50              80
  C        30            60              90

Thank you in advance

One way is to use a CASE statement, like this:

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

Note that you need an aggregating function, such as MAX , around value . In fact, many RDBMS engines would not even take SQL without an aggregating function around it.

SQL FIDDLE

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

base on your example you should use SUM instead of MAX

The same idea with dasblinkenlight but different approach and I agree on aggregating function, such as MAX or 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

you can also use self-joins:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM