Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual output format required in SQL

Tags:

sql

sql-server

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.

like image 483
tkeen Avatar asked Jun 02 '16 23:06

tkeen


People also ask

How do I change the format in SQL?

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')

What is the return type of format function in SQL?

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.

What is the output of SQL query?

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.


1 Answers

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
like image 173
Tim Biegeleisen Avatar answered Oct 16 '22 10:10

Tim Biegeleisen