Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mukhan85
Starting Member
46 Posts |
Posted - 2008-07-18 : 17:49:38
|
| Hi I have the following table:MONTH Status ------------ --------- 1 Successful 1 Failed 1 Canceled 2 Successful 2 Failed 2 Canceled 3 Successful 3 Failed 3 Canceled 4 Successful 4 Failed 4 Canceled 5 No Closure Stat 5 Successful 5 Failed 5 Canceled 5 Unsuccessful 6 Successful 6 Failed 6 Canceled 6 SWP 6 Unsuccessful 7 Successful 7 Failed 7 Canceled 7 SWP 7 Unsuccessful 8 No Closure Stat 9 No Closure Stat 10 No Closure Stat 11 Successful 12 No Closure Stat As you can see, Status field can have 'Successful', 'Unsuccessful', 'Failed', 'Canceled' , 'SWP' and 'No Closure Stat' values. Now, I need this values for all month: The output that I need is as follows:MONTH STATUS----- ------1 Successful1 Unsuccessful1 Failed1 Canceled1 SWP1 No Closure Stat2 Successful2 Unsuccessful2 Failed2 Canceled2 SWP2 No Closure Stat...I know that it is possible with joins, but I couldn't figure it out. Thank you a lot. |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2008-07-18 : 18:18:23
|
Assuming that that table has months 1-12,then you could do something like this:SELECT [Month], [Status]FROM( SELECT DISTINCT [Status] FROM MyTable) AS StatCROSS JOIN( SELECT DISTINCT [Month] FROM MyTable) AS Mon |
 |
|
|
mukhan85
Starting Member
46 Posts |
Posted - 2008-07-18 : 19:02:02
|
| Thank you it works great. Is it possible to extend that query so that it would give me the following result.Table:MONTH Status Number---- --------- -----1 Successful 31 Failed 71 Canceled 22 Successful 4 2 Failed 12 Canceled 33 Successful 63 Failed 73 Canceled 24 Successful .4 Failed .. . .. . .. . .As you can see, Status field can have 'Successful', 'Unsuccessful', 'Failed', 'Canceled' , 'SWP' and 'No Closure Stat' values. Now, I need this values for all month: The output that I need is as follows:MONTH STATUS NUMBER----- ------ ------1 Successful 31 Unsuccessful 01 Failed 71 Canceled 21 SWP 01 No Closure Stat 0 2 Successful 4 2 Unsuccessful 0 2 Failed 12 Canceled 32 SWP 0 2 No Closure Stat 0...I know that it is possible with joins, but I couldn't figure it out.Thank you a lot. |
 |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2008-07-18 : 19:08:46
|
| [code]SELECT [Month], [Status], COALESCE(Number, 0) AS NumberFROM ( SELECT [Month], [Status] FROM ( SELECT DISTINCT [Status] FROM MyTable ) AS Stat CROSS JOIN ( SELECT DISTINCT [Month] FROM MyTable ) AS Mon ) AS TLEFT OUTER JOIN MyTable ON T.[Status] = MyTable.[Status] AND T.[Month] = MyTable.[Month][/code] |
 |
|
|
|
|
|
|
|