| Author |
Topic |
|
Fakir
Starting Member
2 Posts |
Posted - 2007-04-18 : 23:39:49
|
| I am trying to write a query that needs a decision, probably using CASE.Here is the problem.There are 2 observation posts, one of which measures water level only, while the other measures water level and water temperature.My table looks like this:date, post, data_kind, value2007/04/19 12:45, A, 1, 9992007/04/19 12:45, B, 1, 9982007/04/19 12:45, B, 2, 192007/04/19 13:55, A, 1, 9962007/04/19 14:00, B, 2, 20.5data_kind 1: water level, 2: temperatureThe end result should look like this:date, A_water_level,B_water_level,B_water_temp2007/04/19 12:45, 999, 998, 192007/04/19 13:55, 996, null, null2007/04/19 14:00, null, null, 20.5(I used comma to separate data, so that it might be easier to read(?))How do I start? Can anyone give me a hint, please? Thank you. |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-04-19 : 00:00:23
|
[code]declare @table table( date datetime, post char(1), data_kind int, value decimal(5,1))insert into @table select '2007/04/19 12:45', 'A', 1, 999 union allselect '2007/04/19 12:45', 'B', 1, 998 union allselect '2007/04/19 12:45', 'B', 2, 19 union allselect '2007/04/19 13:55', 'A', 1, 996 union allselect '2007/04/19 14:00', 'B', 2, 20.5select date, A_water_level = sum(case when post = 'A' and data_kind = 1 then value end), B_water_level = sum(case when post = 'B' and data_kind = 1 then value end), A_water_temp = sum(case when post = 'A' and data_kind = 2 then value end), B_water_temp = sum(case when post = 'B' and data_kind = 2 then value end)from @tablegroup by datedate A_water_level B_water_level A_water_temp B_water_temp ------------------------ ---------------- ---------------- --------------- --------------2007-04-19 12:45:00.000 999.0 998.0 NULL 19.02007-04-19 13:55:00.000 996.0 NULL NULL NULL2007-04-19 14:00:00.000 NULL NULL NULL 20.5[/code] KH |
 |
|
|
jezemine
Master Smack Fu Yak Hacker
2886 Posts |
Posted - 2007-04-19 : 00:14:07
|
[code]declare @t table (date datetime, post char(1), data_kind int, value float)insert into @tselect '2007/04/19 12:45', 'A', 1, 999 union allselect '2007/04/19 12:45', 'B', 1, 998 union allselect '2007/04/19 12:45', 'B', 2, 19 union allselect '2007/04/19 13:55', 'A', 1, 996 union allselect '2007/04/19 14:00', 'B', 2, 20.5select date ,max(case when post='A' and data_kind=1 then value end) as A_water_level ,max(case when post='B' and data_kind=1 then value end) as B_water_level ,max(case when post='B' and data_kind=2 then value end) as B_water_tempfrom @tgroup by date[/code]EDIT: i guess i should refresh the page before posting a long answer like this... how can I compete with you guys anyway. so fast!  www.elsasoft.org |
 |
|
|
Fakir
Starting Member
2 Posts |
Posted - 2007-04-19 : 00:44:53
|
| My God, I don't know how can I thank you guys. Thank you khtan and jezemine, you made my day!Fakir |
 |
|
|
|
|
|