Click here to Skip to main content
15,907,281 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to pivot the table as shown below


Dates 2016-01-17 2016-01-18 2016-01-19

Orders 100 120 150

CanceledOrders 50 20 30

Can anyone give me suggestions in writing query?Here Dates have to come dynamically.

What I have tried:

This is Sql actual Result Set

----------------------------------
| Dates |Orders |Canceled Orders|
----------- |----- |---------------|
|2016-01-17 |100 | 50 |
|2016-01-18 |120 | 20 |
|2016-01-20 |150 | 30 |
----------------------------------
Posted
Updated 18-Jan-17 7:17am
v4
Comments
Maciej Los 18-Jan-17 2:19am    
Sorry, but your question is unclear. Please, be more specific and provide more details, such as expected output.

1 solution

If the number of date columns is variable there is no chance to solve this problem with T-SQL language (anyway you might do this with a CLR function in C# or VB.net).

If the number of date columns is fixed and always the same, you can do something like:

SQL
DECLARE @date1 AS nvarchar(10);
DECLARE @date2 AS nvarchar(10);
DECLARE @date3 AS nvarchar(10);
DECLARE @query AS nvarchar(max);

--Gather your dates and set them as column headers (nvarchars ):
SET @date1 = <first date found>;
SET @date2 = <second date found>;
SET @date3 = <third date found>;

--Now create your query as nvarchar(max) variable:
SET @query = 'SELECT <a field>
                   , <another field>
                   , SUM(<first field to summarize>) AS [' + @date1 + '] 
                   , SUM(<second field to summarize>) AS [' + @date2 + ']
                   , SUM(<third field to summarize>) AS [' + @date3 + ']
               FROM [dbo].[<source table name>]
              WHERE (<any filter expressions here>)';

--Execute the query
EXEC sp_executesql @query;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900