views:

106

answers:

5

Hi there,

maybe anyone can help me out with my SELECT statement on MS SQL Server. I am not very skilled in (T)SQL.

I have a table called RECORDS and with a DATETIME column called [BEGIN]. Now I would like to get some nvarchars which look like this "December 08, January 09, February 09"..

I came up with the following myself.

SELECT DISTINCT DATENAME(MONTH, [BEGIN]) + ' ' + SUBSTRING(DATENAME(YEAR, [BEGIN]),3,4) 
FROM RECORDS

However this is unsorted I would like to have the result set ordered from first to last.

February 09
January 09
December 08

Anyone?

+1  A: 
SELECT  DATENAME(MONTH, DATEADD(month, b_month - 1, 0)) + ' ' + SUBSTRING(CAST(b_year AS VARCHAR), 3, 4)
FROM    (
        SELECT  DISTINCT YEAR([BEGIN]) AS b_year, MONTH([BEGIN]) AS b_month
        FROM    RECORDS
        ) q
ORDER BY
        b_year, b_month
Quassnoi
Now, this is not goint to work. Result is something like April 07, April 08, April 09 ...
`@rantaplan`: see the update
Quassnoi
@Quassnoi Thanks for your help, but with your last statement all I get is January 05 over and over
`@rantaplan`: sure, see the new update
Quassnoi
@Quassnoi Awesome! But its from last to first. ORDER BY b_year DESC, b_month DESC did work and solved my issue. Thanks a lot!
+1  A: 

what about

with tbldate AS 
(
select distinct DATENAME(MONTH, date) + ' ' + SUBSTRING(DATENAME(YEAR, date),3,4)  as date
from dbo.tbldate  
)
select * from tbldate
order by date desc
anishmarokey
Won't work, `column` is not in `SELECT` clause
Quassnoi
Not working with DISTINCT. See the comment I left on BBlake answer
i updated . have you tried that ? ? ?
anishmarokey
A: 

Add ORDER BY [BEGIN] DESC

BBlake
But this is not working with DISTINCT. Translated the error message is something like ORDER BY elements need to be select if SELECT DISTINCT is in use..
A: 
SELECT DISTINCT DATENAME(MONTH, [BEGIN]) + ' ' + SUBSTRING(DATENAME(YEAR, [BEGIN]),3,4) FROM RECORDS
ORDER BY 1 DESC
MRFerocius
+1  A: 
select  datename(month, yyyymm) 
    + ' ' 
    + right(convert(varchar(10), yyyymm), 2)
from
(
    select  dateadd(month, datediff(month, 0, [BEGIN]), 0) as yyyymm
    from    yourtable
    group by dateadd(month, datediff(month, 0, [BEGIN]), 0)
) a
order by yyyymm desc
Squirrel