So I have the following date
ID NAME MONTH COUNT
1 David December2012 500
2 Rob December2012 320
1 David January2013 400
2 Rob January2013 280
I am trying to make this.......
ID Name December2012 January2013
1 David 500 400
2 Rob 320 280
Where I get confused is how I want to keep two of the columns and just pivot the two other fields. Anyone know how I would do this.
Thank you so much for your help/time. I have never posted one of these, and responses are greatly appreciated!
You did not specify what RDBMS you are using. You can pivot the data in all databases using an aggregate function with a CASE expression:
select id, name,
sum(case when month = 'December2012' then "count" end) December2012,
sum(case when month = 'January2013' then "count" end) January2013
from yourtable
group by id, name
See SQL Fiddle with Demo
If you are using SQL Server 2005+ or Oracle 11g then you can use the PIVOT function:
select *
from
(
select id, name, month, [count]
from yourtable
) src
pivot
(
sum([count])
for month in (December2012, January2013)
) piv
See SQL Fiddle with Demo.
In SQL Server, if the values of the month are unknown then you can use dynamic SQL similar to this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(month)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT id, name,' + #cols + ' from
(
select id, name, month, [count]
from yourtable
) x
pivot
(
sum([count])
for month in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo
All versions yield the result:
| ID | NAME | DECEMBER2012 | JANUARY2013 |
-------------------------------------------
| 1 | David | 500 | 400 |
| 2 | Rob | 320 | 280 |
Since you didn't specify what RDBMS you are using, then you can do this:
SELECT
ID,
NAME,
MAX(CASE WHEN MONTH = 'December2012' THEN "COUNT" END) AS "December2012",
MAX(CASE WHEN MONTH = 'January2013' THEN "COUNT" END) AS "January2013"
FROM Tablename
GROUP BY ID, Name;
Related
I have a table on which simple select gives out put like below
I want to write a select statement to output like below
Can someone help me...
Since you are basically rotating your current columns of Sale, Income and Profit into rows and then move the month values to columns, then you will want to first unpivot the current columns, then pivot the months.
Depending on your version of SQL Server there are a few ways that you can unpivot the data. You can use the UNPIVOT function or CROSS APPLY:
select month, type, value
from yourtable
cross apply
(
select 'Sale', sale union all
select 'Income', Income union all
select 'Profit', Profit
) c (type, value)
See SQL Fiddle with Demo. This will convert your current data into:
| MONTH | TYPE | VALUE |
|-------|--------|-------|
| Jan | Sale | 100 |
| Jan | Income | 50 |
| Jan | Profit | 10 |
| Feb | Sale | 20 |
| Feb | Income | 40 |
Then you can use the PIVOT function to convert the months into your column headers.
select type, Jan, Feb, Mar, Apr
from
(
select month, type, value
from yourtable
cross apply
(
select 'Sale', sale union all
select 'Income', Income union all
select 'Profit', Profit
) c (type, value)
) d
pivot
(
sum(value)
for month in (Jan, Feb, Mar, Apr)
) piv;
See SQL Fiddle with Demo.
if you have an unknown number of months, then you can use dynamic SQL:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct N',' + QUOTENAME(Month)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = N'SELECT type, ' + #cols + N'
from
(
select month, type, value
from yourtable
cross apply
(
select ''Sale'', sale union all
select ''Income'', Income union all
select ''Profit'', Profit
) c (type, value)
) x
pivot
(
sum(value)
for month in (' + #cols + N')
) p '
execute sp_executesql #query;
See SQL Fiddle with Demo
You Can Use UNPIVOT then PIVOT
THE BEST IS TO DO QUERY EMBEDED SQL
create DISTINCT COLUMS of months with STUFF function then
replace FOR oMonth IN ([January-2013], [February-2013], [March-2013], [April-2013])
here core query
SELECT
*
FROM
( SELECT
oMonth, value,col
from (
select DATENAME(month,oDate) + '-' + CAST(YEAR( oDate) as varchar) as oMonth, Sales ,Income,Profit
FROM SalesSource
)A
unpivot
(
value for col in ( Sales ,Income,Profit)
) u
) as sourceTable
PIVOT
(
sum( value)
FOR oMonth IN ([January-2013], [February-2013], [March-2013], [April-2013])
) AS PivotTable;
I am trying to use dynamic pivot and need help on converting rows to columns
The table looks like:
ID expense revenue date
1 43 45 12-31-2012
1 32 32 01-01-2013
3 64 56 01-31-2013
4 31 32 02-31-2013
and I need for reporting purposes like
ID expense12-31-2012 expense01-01-2013 expense01-31-2013 revenue12-31-2013
1 43 32
3 64
In order to get both the expense and revenue columns as headers with the date, I would recommend applying both the UNPIVOT and the PIVOT functions.
The UNPIVOT will convert the expense and revenue columns into rows that you can append the date to. Once the date is added to the column names, then you can apply the PIVOT function.
The UNPIVOT code will be:
select id,
col+'_'+convert(varchar(10), date, 110) new_col,
value
from yt
unpivot
(
value
for col in (expense, revenue)
) un
See SQL Fiddle with Demo. This produces a result:
| ID | NEW_COL | VALUE |
-----------------------------------
| 1 | expense_12-31-2012 | 43 |
| 1 | revenue_12-31-2012 | 45 |
| 2 | expense_01-01-2013 | 32 |
As you can see the expense/revenue columns are now rows with a new_col that has been created by concatenating the date to the end. This new_col is then used in the PIVOT:
select id,
[expense_12-31-2012], [revenue_12-31-2012],
[expense_01-01-2013], [revenue_01-01-2013],
[expense_01-31-2013], [revenue_01-31-2013],
[expense_03-03-2013], [revenue_03-03-2013]
from
(
select id,
col+'_'+convert(varchar(10), date, 110) new_col,
value
from yt
unpivot
(
value
for col in (expense, revenue)
) un
) src
pivot
(
sum(value)
for new_col in ([expense_12-31-2012], [revenue_12-31-2012],
[expense_01-01-2013], [revenue_01-01-2013],
[expense_01-31-2013], [revenue_01-31-2013],
[expense_03-03-2013], [revenue_03-03-2013])
) piv;
See SQL Fiddle with Demo.
The above version will work great if you have a known number of dates to turn into columns but if you have an unknown number of dates, then you will want to use dynamic SQL to generate the result:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(c.col+'_'+convert(varchar(10), yt.date, 110))
from yt
cross apply
(
select 'expense' col union all
select 'revenue'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT id,' + #cols + '
from
(
select id,
col+''_''+convert(varchar(10), date, 110) new_col,
value
from yt
unpivot
(
value
for col in (expense, revenue)
) un
) src
pivot
(
sum(value)
for new_col in (' + #cols + ')
) p '
execute(#query);
See SQL Fiddle with Demo. Both queries generate the same result.
I have a Table1:
ID Instance Name Size Tech
1 0 D1 123 ABC
1 1 D2 234 CDV
2 2 D3 234 CDV
2 3 D4 345 SDF
I need the resultset using Dynamic PIVOT to look like along with the headers:
ID | Instance0_Name | Instance0_Size | Instance0_Tech | Instance1_Name | Instance1_Size | Instance1_tech
1 | D1 | 123 | ABC | D2 | 234 | CDV
Any help would be appreciated. using Sql Server 2008.
Sorry for the earlier post.
Your desired output is not exactly clear, but you can use the both the UNPIVOT and PIVOT function to get the result
If you know the number of columns, then you can hard code the values:
select *
from
(
select id,
'Instance'+cast(instance as varchar(10))+'_'+col col,
value
from
(
select id,
Instance,
Name,
cast(Size as varchar(50)) Size,
Tech
from yourtable
) x
unpivot
(
value
for col in (Name, Size, Tech)
) u
) x1
pivot
(
max(value)
for col in
([Instance0_Name], [Instance0_Size], [Instance0_Tech],
[Instance1_Name], [Instance1_Size], [Instance1_Tech],
[Instance2_Name], [Instance2_Size], [Instance2_Tech],
[Instance3_Name], [Instance3_Size], [Instance3_Tech])
) p
See SQL Fiddle with Demo
Then if you have an unknown number of values, you can use dynamic sql:
DECLARE #query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
select #colsPivot = STUFF((SELECT ','
+ quotename('Instance'+ cast(instance as varchar(10))+'_'+c.name)
from yourtable t
cross apply sys.columns as C
where C.object_id = object_id('yourtable') and
C.name not in ('id', 'instance')
group by t.instance, c.name
order by t.instance
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select *
from
(
select id,
''Instance''+cast(instance as varchar(10))+''_''+col col,
value
from
(
select id,
Instance,
Name,
cast(Size as varchar(50)) Size,
Tech
from yourtable
) x
unpivot
(
value
for col in (Name, Size, Tech)
) u
) x1
pivot
(
max(value)
for col in ('+ #colspivot +')
) p'
exec(#query)
See SQL Fiddle with Demo
If the result is not correct, then please edit your OP and post the result that you expect from both of the Ids you provided.
I have a table with 3 columns: ItemCode, Quantity and DocDate.
I would like to create the following report in a more "elegant" way:
SELECT T0.ItemCode,
(SELECT SUM(QUANTITY) FROM MyTable T1 WHERE YEAR(T0.DocDate) = 2011 AND T0.ItemCode = T1.ItemCode) AS '2011',
(SELECT SUM(QUANTITY) FROM MyTable T1 WHERE YEAR(T0.DocDate) = 2012 AND T0.ItemCode = T1.ItemCode) AS '2012'
FROM MyTable T0
GROUP BY T0.ItemCode, YEAR(T0.DocDate)
I'm pretty sure there's a better, more efficient way to write this but I can't come up with the right syntax. Any ideas?
You can try this:
SELECT T0.ItemCode,
SUM(CASE WHEN YEAR(T0.DocDate) = 2011 THEN QUANTITY ELSE 0 END) AS '2011',
SUM(CASE WHEN YEAR(T0.DocDate) = 2012 THEN QUANTITY ELSE 0 END) AS '2012'
FROM MyTable T0
GROUP BY
T0.ItemCode
This type of data transformation is known as a PIVOT. There are several ways that you can perform this operation. You can use the PIVOT function or you can use an aggregate function with a CASE statement:
Static Pivot Version: This is where you hard-code all of the values into the query
select ItemCode, [2011], [2012]
from
(
SELECT ItemCode,
QUANTITY,
YEAR(DocDate) Year
FROM MyTable
) src
pivot
(
sum(quantity)
for year in ([2011], [2012])
) piv
See SQL Fiddle with Demo
Case with Aggregate:
SELECT ItemCode,
SUM(CASE WHEN YEAR(DocDate) = 2011 THEN QUANTITY ELSE 0 END) AS '2011',
SUM(CASE WHEN YEAR(DocDate) = 2012 THEN QUANTITY ELSE 0 END) AS '2012'
FROM MyTable
GROUP BY ItemCode;
See SQL Fiddle with Demo
Dynamic Pivot: The previous two versions will work great is you have a known number of year values to transform, but it you have an unknown number then you can use dynamic sql:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(YEAR(DocDate))
from mytable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT itemcode, ' + #cols + ' from
(
select itemcode, quantity, year(docdate) year
from mytable
) x
pivot
(
sum(quantity)
for year in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo
All three versions will produce the same result:
| ITEMCODE | 2011 | 2012 |
--------------------------
| 1 | 200 | 45 |
| 2 | 89 | 0 |
| 3 | 0 | 7 |
This question already has answers here:
SQL turning values returned in 11 rows into 89 total columns
(2 answers)
Closed 9 years ago.
this is my query
select * from dbo.tblHRIS_ChildDetails where intSID=463
output:
intCHID intsid nvrchildname nvrgender dttchildDOB Occupation
3 463 SK Female 2001-12-11 00:00:00.000 Studying
4 463 SM Male 2007-10-08 00:00:00.000 Student
i need the output like this this is query is dynamic it may return n number of rows based on the intSID
chidname1 gender DOB childoccupation1 chidname2 gender DOB childoccupation2
SK female 2001-12-11 00:00:00.000 studying SM Male 2007-10-08 00:00:00.000 Student
For this type of data, you will need to implement both the UNPIVOT and then the PIVOT functions of SQL Server. The UNPIVOT takes your data from the multiple columns and place it into two columns and then you apply the PIVOT to transform the data back into columns.
If you know all of the values that you want to transform, then you can hard-code it, similar to this:
select *
from
(
select value, col+'_'+cast(rn as varchar(10)) col
from
(
select nvrchildname,
nvrgender,
convert(varchar(10), dttchildDOB, 120) dttchildDOB,
occupation,
row_number() over(partition by intsid order by intCHID) rn
from tblHRIS_ChildDetails
where intsid = 463
) src
unpivot
(
value
for col in (nvrchildname, nvrgender, dttchildDOB, occupation)
) unpiv
) src1
pivot
(
max(value)
for col in ([nvrchildname_1], [nvrgender_1],
[dttchildDOB_1], [occupation_1],
[nvrchildname_2], [nvrgender_2],
[dttchildDOB_2], [occupation_2])
) piv
See SQL Fiddle with Demo
Now, if you have an unknown number of values to transform, then you can use dynamic SQL for this:
DECLARE #colsUnpivot AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
select #colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('tblHRIS_ChildDetails') and
C.name not in ('intCHID', 'intsid')
for xml path('')), 1, 1, '')
select #colsPivot = STUFF((SELECT ','
+ quotename(c.name
+'_'+ cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by intsid order by intCHID) rn
from tblHRIS_ChildDetails
) t
cross apply sys.columns as C
where C.object_id = object_id('tblHRIS_ChildDetails') and
C.name not in ('intCHID', 'intsid')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select *
from
(
select col+''_''+cast(rn as varchar(10)) col, value
from
(
select nvrchildname,
nvrgender,
convert(varchar(10), dttchildDOB, 120) dttchildDOB,
occupation,
row_number() over(partition by intsid order by intCHID) rn
from tblHRIS_ChildDetails
where intsid = 463
) x
unpivot
(
value
for col in ('+ #colsunpivot +')
) u
) x1
pivot
(
max(value)
for col in ('+ #colspivot +')
) p'
exec(#query)
See SQL Fiddle with Demo
The result of both queries is:
| NVRCHILDNAME_1 | NVRGENDER_1 | DTTCHILDDOB_1 | OCCUPATION_1 | NVRCHILDNAME_2 | NVRGENDER_2 | DTTCHILDDOB_2 | OCCUPATION_2 |
-----------------------------------------------------------------------------------------------------------------------------
| SK | Female | 2001-12-11 | Studying | SM | Male | 2007-10-08 | Student |
You have to provide distinct column names but besides that, it's simple. But as others stated, this is not commonly done and looks like if you want print some report with two columns.
select
max(case when intCHID=1 then nvrchildname end) as chidname1,
max(case when intCHID=1 then gender end) as gender1,
max(case when intCHID=1 then dttchildDOB end) as DOB1,
max(case when intCHID=1 then Occupation end) as cildOccupation1,
max(case when intCHID=2 then nvrchildname end) as chidname2,
max(case when intCHID=2 then gender end) as gender2,
max(case when intCHID=2 then dttchildDOB end) as DOB2,
max(case when intCHID=2 then Occupation end) as cildOccupation2
from
dbo.tblHRIS_ChildDetails
where
intSID=463