I have read the stuff on MS pivot tables and I am still having problems getting this correct.
I have a temp table that is being created, we will say that column 1 is a Store number, and column 2 is a week number and lastly column 3 is a total of some type. Also the Week numbers are dynamic, the store numbers are static.
Store Week xCount
------- ---- ------
102 1 96
101 1 138
105 1 37
109 1 59
101 2 282
102 2 212
105 2 78
109 2 97
105 3 60
102 3 123
101 3 220
109 3 87
I would like it to come out as a pivot table, like this:
Store 1 2 3 4 5 6....
-----
101 138 282 220
102 96 212 123
105 37
109
Store numbers down the side and weeks across the top.
If you are using SQL Server 2005+, then you can use the PIVOT function to transform the data from rows into columns.
It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.
First up, here are some quick table definitions and data for use:
CREATE TABLE yt
(
[Store] int,
[Week] int,
[xCount] int
);
INSERT INTO yt
(
[Store],
[Week], [xCount]
)
VALUES
(102, 1, 96),
(101, 1, 138),
(105, 1, 37),
(109, 1, 59),
(101, 2, 282),
(102, 2, 212),
(105, 2, 78),
(109, 2, 97),
(105, 3, 60),
(102, 3, 123),
(101, 3, 220),
(109, 3, 87);
If your values are known, then you will hard-code the query:
select *
from
(
select store, week, xCount
from yt
) src
pivot
(
sum(xcount)
for week in ([1], [2], [3])
) piv;
See SQL Demo
Then if you need to generate the week number dynamically, your code will be:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(Week)
from yt
group by Week
order by Week
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT store,' + #cols + ' from
(
select store, week, xCount
from yt
) x
pivot
(
sum(xCount)
for week in (' + #cols + ')
) p '
execute(#query);
See SQL Demo.
The dynamic version, generates the list of week numbers that should be converted to columns. Both give the same result:
| STORE | 1 | 2 | 3 |
---------------------------
| 101 | 138 | 282 | 220 |
| 102 | 96 | 212 | 123 |
| 105 | 37 | 78 | 60 |
| 109 | 59 | 97 | 87 |
This is for dynamic # of weeks.
Full example here:SQL Dynamic Pivot
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','') + QUOTENAME(Week)
FROM (SELECT DISTINCT Week FROM #StoreSales) AS Weeks
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Store, ' + #ColumnName + '
FROM #StoreSales
PIVOT(SUM(xCount)
FOR Week IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:
SELECT StoreID,
Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID
One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.
My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .
This is what you can do:
SELECT *
FROM yourTable
PIVOT (MAX(xCount)
FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt
DEMO
I'm writing an sp that could be useful for this purpose, basically this sp pivot any table and return a new table pivoted or return just the set of data, this is the way to execute it:
Exec dbo.rs_pivot_table #schema=dbo,#table=table_name,#column=column_to_pivot,#agg='sum([column_to_agg]),avg([another_column_to_agg]),',
#sel_cols='column_to_select1,column_to_select2,column_to_select1',#new_table=returned_table_pivoted;
please note that in the parameter #agg the column names must be with '[' and the parameter must end with a comma ','
SP
Create Procedure [dbo].[rs_pivot_table]
#schema sysname=dbo,
#table sysname,
#column sysname,
#agg nvarchar(max),
#sel_cols varchar(max),
#new_table sysname,
#add_to_col_name sysname=null
As
--Exec dbo.rs_pivot_table dbo,##TEMPORAL1,tip_liq,'sum([val_liq]),sum([can_liq]),','cod_emp,cod_con,tip_liq',##TEMPORAL1PVT,'hola';
Begin
Declare #query varchar(max)='';
Declare #aggDet varchar(100);
Declare #opp_agg varchar(5);
Declare #col_agg varchar(100);
Declare #pivot_col sysname;
Declare #query_col_pvt varchar(max)='';
Declare #full_query_pivot varchar(max)='';
Declare #ind_tmpTbl int; --Indicador de tabla temporal 1=tabla temporal global 0=Tabla fisica
Create Table #pvt_column(
pivot_col varchar(100)
);
Declare #column_agg table(
opp_agg varchar(5),
col_agg varchar(100)
);
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(#table) AND type in (N'U'))
Set #ind_tmpTbl=0;
ELSE IF OBJECT_ID('tempdb..'+ltrim(rtrim(#table))) IS NOT NULL
Set #ind_tmpTbl=1;
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(#new_table) AND type in (N'U')) OR
OBJECT_ID('tempdb..'+ltrim(rtrim(#new_table))) IS NOT NULL
Begin
Set #query='DROP TABLE '+#new_table+'';
Exec (#query);
End;
Select #query='Select distinct '+#column+' From '+(case when #ind_tmpTbl=1 then 'tempdb.' else '' end)+#schema+'.'+#table+' where '+#column+' is not null;';
Print #query;
Insert into #pvt_column(pivot_col)
Exec (#query)
While charindex(',',#agg,1)>0
Begin
Select #aggDet=Substring(#agg,1,charindex(',',#agg,1)-1);
Insert Into #column_agg(opp_agg,col_agg)
Values(substring(#aggDet,1,charindex('(',#aggDet,1)-1),ltrim(rtrim(replace(substring(#aggDet,charindex('[',#aggDet,1),charindex(']',#aggDet,1)-4),')',''))));
Set #agg=Substring(#agg,charindex(',',#agg,1)+1,len(#agg))
End
Declare cur_agg cursor read_only forward_only local static for
Select
opp_agg,col_agg
from #column_agg;
Open cur_agg;
Fetch Next From cur_agg
Into #opp_agg,#col_agg;
While ##fetch_status=0
Begin
Declare cur_col cursor read_only forward_only local static for
Select
pivot_col
From #pvt_column;
Open cur_col;
Fetch Next From cur_col
Into #pivot_col;
While ##fetch_status=0
Begin
Select #query_col_pvt='isnull('+#opp_agg+'(case when '+#column+'='+quotename(#pivot_col,char(39))+' then '+#col_agg+
' else null end),0) as ['+lower(Replace(Replace(#opp_agg+'_'+convert(varchar(100),#pivot_col)+'_'+replace(replace(#col_agg,'[',''),']',''),' ',''),'&',''))+
(case when #add_to_col_name is null then space(0) else '_'+isnull(ltrim(rtrim(#add_to_col_name)),'') end)+']'
print #query_col_pvt
Select #full_query_pivot=#full_query_pivot+#query_col_pvt+', '
--print #full_query_pivot
Fetch Next From cur_col
Into #pivot_col;
End
Close cur_col;
Deallocate cur_col;
Fetch Next From cur_agg
Into #opp_agg,#col_agg;
End
Close cur_agg;
Deallocate cur_agg;
Select #full_query_pivot=substring(#full_query_pivot,1,len(#full_query_pivot)-1);
Select #query='Select '+#sel_cols+','+#full_query_pivot+' into '+#new_table+' From '+(case when #ind_tmpTbl=1 then 'tempdb.' else '' end)+
#schema+'.'+#table+' Group by '+#sel_cols+';';
print #query;
Exec (#query);
End;
GO
This is an example of execution:
Exec dbo.rs_pivot_table #schema=dbo,#table=##TEMPORAL1,#column=tip_liq,#agg='sum([val_liq]),avg([can_liq]),',#sel_cols='cod_emp,cod_con,tip_liq',#new_table=##TEMPORAL1PVT;
then Select * From ##TEMPORAL1PVT would return:
Here is a revision of #Tayrn answer above that might help you understand pivoting a little easier:
This may not be the best way to do this, but this is what helped me wrap my head around how to pivot tables.
ID = rows you want to pivot
MY_KEY = the column you are selecting from your original table that contains the column names you want to pivot.
VAL = the value you want returning under each column.
MAX(VAL) => Can be replaced with other aggregiate functions. SUM(VAL), MIN(VAL), ETC...
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(MY_KEY)
from yt
group by MY_KEY
order by MY_KEY ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT ID,' + #cols + ' from
(
select ID, MY_KEY, VAL
from yt
) x
pivot
(
sum(VAL)
for MY_KEY in (' + #cols + ')
) p '
execute(#query);
select * from (select name, ID from Empoyee) Visits
pivot(sum(ID) for name
in ([Emp1],
[Emp2],
[Emp3]
) ) as pivottable;
Just give you some idea how other databases solve this problem. DolphinDB also has built-in support for pivoting and the sql looks much more intuitive and neat. It is as simple as specifying the key column (Store), pivoting column (Week), and the calculated metric (sum(xCount)).
//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)
//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week
DolphinDB is a columnar high performance database. The calculation in the demo costs as low as 546 ms on a dell xps laptop (i7 cpu). To get more details, please refer to online DolphinDB manual https://www.dolphindb.com/help/index.html?pivotby.html
Pivot is one of the SQL operator which is used to turn the unique data from one column into multiple column in the output. This is also mean by transforming the rows into columns (rotating table). Let us consider this table,
If I want to filter this data based on the types of product (Speaker, Glass, Headset) by each customer, then use Pivot operator.
Select CustmerName, Speaker, Glass, Headset
from TblCustomer
Pivot
(
Sum(Price) for Product in ([Speaker],[Glass],[Headset])
) as PivotTable
Running SQL Server 2005/2008, I am rewriting my query to be cleaner and more compliant to not include bad habits. I used to have lots of IF statements and PIVOT to do this, but found a better way to achieve it now and just need a last bit to make it almost perfect.
DECLARE #startdate DATETIME;
DECLARE #enddate DATETIME;
DECLARE #showstore INT;
DECLARE #showcashier INT;
DECLARE #showregister INT;
DECLARE #showdate INT;
DECLARE #sql NVARCHAR(MAX);
DECLARE #result0 NVARCHAR(MAX);
SET #startdate = '1/1/2012';
SET #enddate = '2/28/2013';
SET #showdate = 1;
SET #showstore = 0;
SET #showcashier = 1;
SET #showregister = 0;
SET #startdate = DATEADD(DAY, DATEDIFF(DAY, 0, #startdate), 0);
SET #enddate = DATEADD(DAY, DATEDIFF(DAY, 0, #enddate), 0);
SET #sql = N'CREATE TABLE ##a13 (' + SUBSTRING(
CASE WHEN #showdate = 1 THEN ',[Transaction Date] DATETIME' ELSE '' END +
CASE WHEN #showstore = 1 THEN ',[Store ID] VARCHAR(10)' ELSE '' END +
CASE WHEN #showcashier = 1 THEN ',[Cashier] VARCHAR(100)' ELSE '' END +
CASE WHEN #showregister = 1 THEN ',[Register] VARCHAR(20)' ELSE '' END, 2, 2000);
DECLARE myCursor CURSOR FOR
SELECT DISTINCT c.CurrencyDesc
FROM dbo.Currencies AS c INNER JOIN dbo.rpPay AS p ON c.POSCurrency = p.PayType
INNER JOIN dbo.RPTrs AS r ON r.ReceiptNO = p.ReceiptNo
WHERE
c.CurrencyDesc <> 'Testing' AND c.CurrencyDesc <> 'Cash Change' AND
r.TRSDate >= #startdate AND r.TRSDate <= #enddate
OPEN myCursor
FETCH NEXT FROM myCursor INTO #result0
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = #sql + ',[' + #result0 + '] INT'
FETCH NEXT FROM myCursor INTO #result0
END
CLOSE myCursor
DEALLOCATE myCursor
SET #sql = #sql + ')'
EXECUTE sp_executesql #sql, N'#startdate DATETIME,
#enddate DATETIME',#startdate, #enddate;
SET #sql = 'SELECT * FROM ##a13; DROP TABLE ##a13'
EXECUTE sp_executesql #sql
This Returns a table empty of rows. (know that the Currencies tables has more CurrencyDesc then shown here because these are just the ones used in the date range provided)
Which is exactly what I expect from it. Great so far so good. Now I need to add rows of data to it based on a Date Range (#startdate >= and <= #enddate) and depending on what they have checked off from the 4 possible options (#showstore, #showcashier, #showdate, #showregister)
Example : Date from 1/1/2013 till 2/28/2013 and show Register only (as seen in the picture) should have this DATA :
| Register | Cash | House Acct | MasterCard | Visa/MC
--------------------------------------------------------
1 | 01 | 20.00 | 235.25 | 1235.32 | 135.23
2 | 02 | 30.00 | 3542.42 | 323.52 | 523.64
3 | 03 | 23.35 | 100.32 | 3267.24 | 235.25
Reason for 2005/2008 is because some of the clients this is executed against, still use 2005 and in order to use PIVOT I would have to change the compatibility level on each database that is 2005.
PS. Before I get yelled at again, if I use #a13 instead of the global ##a13 it gives me
Msg 208, Level 16, State 0, Line 1
Invalid object name '#a13'.
What can I do about that so I don't use global temp tables?
If I am incorrect here, please clarify.
I BELIEVE you are asking how to populate a table with dynamic columns based on user input. The right answer here is, don't do that!
The best practice for this kind of thing is to have ALL the fields in your output table, then in your application/display layer you only show the fields that the user has requested.
Customizing a table layout within TSQL just to make a clean presentation introduces a lot of unnecessary complexity. This complexity comes with an increased performance cost as well.
If you have a static output table then it's trivial to return your data using the parameters given.
I am working on a appliaction in which I have a following schema
Tasks Master
Task_ID
Task_Name
Task_Details
Task_ID
Task_Date
Task_Count (can be any number like 2 or 3 or 4 or 40)
the Input Form is like that which the staff will fill at the end of the day.
Date | Task Name | Task_Count
24/01/2010 | How many cheque books issued today | 12
24/01/2010 | How many ATM Issued today | 7
Now I want a matrix report showing all tasks suppose 28 tasks in vertical row and on given month it should show all the dates of the particular month horizontal direction like from 1 to 31 days or 30 or 28 as per month days with the task_count using PIVOT in query. i am failed to produce the result as i dont know to make it work. please help.
thanks
You'll need to use a dynamic query since the columns returned by the pivot changes each month.
With some time this could probably be made more elegant, but here's the basic idea:
declare #StartOfMonth datetime = '11/1/2010';
declare #counter datetime = #StartOfMonth;
declare #sql varchar(MAX) = '';
declare #columnnames varchar(MAX);
declare #columnfilter varchar(MAX);
declare #fieldname varchar(12);
--First, create a string of dynamic columns, one for each day of the month.
WHILE (MONTH(#counter) = MONTH(#StartOfMonth))
BEGIN
SET #fieldname = '[' + CONVERT(varchar(10), #counter, 101) + ']';
--Wrap the columns in ISNULL(#,0) to avoid having null values for days without tasks.
SET #columnnames = ISNULL(#columnnames + ',', '') + 'ISNULL(' + #fieldname + ',0) AS ' + #fieldname;
--Also create a dynamic list of the Task_Date values to include in the pivot.
SET #columnfilter = ISNULL(#columnfilter + ',', '') + #fieldname;
SET #counter = DATEADD(DAY,1,#counter);
END
--Put it all together into a pivot query.
set #sql = 'SELECT Task_Name, ' + #columnnames + ' FROM (';
set #sql = #sql + 'SELECT M.Task_Name, D.Task_Date, D.Task_Count '
set #sql = #sql + 'FROM Task_Detail D JOIN Task_Master M ON D.Task_ID = M.Task_ID) as SourceTable ';
set #sql = #sql + 'PIVOT (SUM(Task_Count) FOR Task_Date IN (' + #columnfilter + ')) AS PivotTable';
exec (#sql)