user3224208
user3224208

Reputation: 1027

Month wise display data in SQL Server

I have small question about SQL Server.

I have a table with sample data like this:

id | month  | stat   | count
---------------------------------
1  |     1  | admit  |  7
2  |     8  | admit  | 47
1  |     7  | admit  | 28
2  |     9  | admit  | 11
3  |    12  | dischr |  4
4  |    10  | openc  |  5
1  |    11  | admit  |  1
2  |     6  | admit  |  5
2  |     4  | admit  |  8
1  |     3  | dischr | 10
2  |     2  | admit  | 30
3  |     5  | dischr | 20
1  |     8  | admit  | 13
3  |     8  | dischr |  1
4  |     9  | admit  | 30
2  |    10  | admit  | 20
3  |    10  | deschr | 20

Based on this when month=1 then January and when month=2 then February all the way through 12, based on that condition I got output like below.

Month   |id |Admit  |Dischr |OpenC
August  |1  |13 |NULL   |NULL
January |1  |7  |NULL   |NULL
July    |1  |28 |NULL   |NULL
March   |1  |NULL   |10 |NULL
November|1  |1  |NULL   |NULL
April   |2  |8  |NULL   |NULL
August  |2  |47 |NULL   |NULL
February|2  |30 |NULL   |NULL
June    |2  |5  |NULL   |NULL
October 2   |20 |NULL   |NULL
September|2 |11 |NULL   |NULL
August  |3  |NULL   |1  |NULL
December|3  |NULL   |4  |NULL
May     |3  |NULL   |20 |NULL
October |3  |NULL   |NULL   |NULL
October |4  |NULL   |NULL   |5
September|4 |30 |NULL   |NULL

but I want output like month wise proper order and output look like below

Month   |id |Admit  |Dischr |OpenC
January |1  |7  |NULL   |NULL
February|2  |30 |NULL   |NULL
March   |1  |NULL   |10 |NULL
April   |2  |8  |NULL   |NULL
May     |3  |NULL   |20 |NULL
June    |2  |5  |NULL   |NULL
July    |1  |28 |NULL   |NULL
August  |1  |13 |NULL   |NULL
August  |2  |47 |NULL   |NULL
August  |3  |NULL   |1  |NULL
September|2 |11 |NULL   |NULL
September|4 |30 |NULL   |NULL
October |2  |20 |NULL   |NULL
October |3  |NULL   |NULL   |NULL
October |4  |NULL   |NULL   |5
November|1  |1  |NULL   |NULL
December|3  |NULL   |4  |NULL

Please tell me query how to solve this issue in SQL Server.

Upvotes: 1

Views: 1943

Answers (2)

Pரதீப்
Pரதீப்

Reputation: 93704

You need to convert the month column to date and use it in order by with ID

SELECT [Month],
        id,
        Admit,
        Dischr,
        OpenC
FROM   yourTable
ORDER  BY Cast([Month] + '01 2010' AS DATE),Id 

or

order by DATEPART(MM,[Month]+ ' 01 2010'),Id

Note : '1 2010' in cast is just a static value to convert the month varchar column to date

Upvotes: 3

Milen
Milen

Reputation: 8867

Add order by clause to your query to ensure your data is ordered according to your requirement. Something like this

SELECT ....
FROM yourTable
ORDER BY Month, Id

Upvotes: 0

Related Questions