I have to form a sql query.
My requirement is -
I have a table -
| ID | Date | Value |
| 1 | 2014-09-01 | 4 |
| 2 | 2014-11-09 | 5 |
| 3 | 2014-08-06 | 66 |
| 4 | 2014-08-09 | 55 |
| 5 | 2014-08-08 | 78 |
| 6 | 2014-12-01 | 79 |
| 7 | 2014-12-13 | 90 |
| 8 | 2014-11-11 | 92 |
| 9 | 2014-12-11 | 87 |
| 10 | 2014-09-09 | 34 |
ID- Primary Key, Auto Increment.
I want a result like this -
| Date | Value | |
| 4 | |
| September-2014 | 34 | |
| November-2014 | 5 | |
| November-2014 | 92 | |
| August-2014 | 66 | |
| August-2014 | 55 | |
| August-2014 | 78 | |
| December-2014 | 79 | |
| December-2014 | 90 | |
| 87 | |
Please help.
Thanks a ton in advance.
Vikram AgrawalPosted Jan 12, 2015, 8:24 AM
You can get results in this format by using the following query.
SELECT CAST(DATENAME(MM,DATE_COLUMN) AS VARCHAR(20)) + '-' + CAST(YEAR(DATE_COLUMN) AS VARCHAR(5)) DATE, VALUE FROM MY_TABLE
Thanks.
Mark it as accepted answer if it is helpful to you
Pradeep ShetPosted Jan 12, 2015, 9:02 AM
The query would be
SELECT MONTH(DATE) + '-' + YEAR(DATE) AS Date, Value
FROM table
ORDER BY DATE
I hope this helps you. Plz mark it as answered if it helped you.
Riddhi ValechaPosted Jan 12, 2015, 7:45 AM
I did not get your logic.
Please explain.
I tried, but this is not working.
Deepak VermaPosted Jan 1, 2015, 2:30 AM
Hello Riddhi,
Execute the below statements in SQL Server:
DECLARE @table TABLE( ID INT IDENTITY(1, 1), [Date] DATE, Value INT)
DECLARE @result TABLE( [Date] DATE, Value INT)
INSERT INTO @table ([date], value)
VALUES ( '2014 - 09 - 01', 4),
( '2014 - 11 - 09', 5),
( '2014 - 08 - 06', 66),
( '2014 - 08 - 09', 55),
( '2014 - 08 - 08', 78),
( '2014 - 12 - 01', 79),
( '2014 - 12 - 13', 90),
( '2014 - 11 - 11', 92),
( '2014 - 12 - 11', 87),
( '2014 - 09 - 09', 34)
SELECT *
FROM @table
DECLARE @Date DATE
WHILE( EXISTS(SELECT id
FROM @table) )
BEGIN
SET @Date = (SELECT TOP 1 [date]
FROM @table)
INSERT INTO @result
([date],
Value)
SELECT [date],
value
FROM @table
WHERE DATEPART(month, [Date]) = DATEPART(month, @Date)
AND DATEPART(year, [Date]) = DATEPART(year, @Date)
DELETE FROM @table
WHERE DATEPART(month, [Date]) = DATEPART(month, @Date)
AND DATEPART(year, [Date]) = DATEPART(year, @Date)
END
SELECT DateName(MONTH, [Date]) + '-' + CAST(Datepart(Year, [Date]) AS VARCHAR(4)) [Date],
Value
FROM @result