I have a sql table in the format;
Name Date Value
ABC 1/21/2015 52
ABC 1/22/2015 12
ABC 1/23/2015 32
DEF 1/21/2015 78
DEF 1/22/2015 53
etc...
For compatibility with a legacy program I need to format a text file as follows:
ABC
1/21/2015,52
1/22/2015,12
1/23/2015,32
DEF
1/21/2015,78
1/22/2015,53
Any suggestions would be helpful.
You can specify the format of the dates in your statements using CONVERT and FORMAT. For example: select convert(varchar(max), DateColumn, 13), format(DateColumn, 'dd-MMM-yyyy')
FORMAT returns NULL for errors other than a culture that is not valid. For example, NULL is returned if the value specified in format is not valid. The FORMAT function is nondeterministic.
The OUTPUT clause has access to two temporary or in-memory SQL tables, called INSERTED and DELETED tables. These tables are populated when an INSERT/UPDATE/DELETE operation is done on a table. As a result, the OUTPUT clause can provide us the affected records by referencing these tables.
One option is to create header rows for the result set using a UNION
and then sort such that they appear at the top of each Name
group. You can do this using a computed column which identifies these generated rows as being headers.
SELECT CASE WHEN t.Header = 1
THEN t.Name
ELSE CONCAT(t.Date, ',', t.Value)
END
FROM
(
SELECT DISTINCT Name, NULL AS Date, NULL AS Value, 1 AS Header
FROM yourTable
UNION ALL
SELECT Name, Date, Value, 0 AS Header
FROM yourTable
) t
ORDER BY t.Name, t.Header DESC, t.Date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With