Pivot Structure in SQL - sql

I need a sql query to populate data in a pivotal structure, lets say I have the below table as example, I need a query in SQL server 2008
ID|EMAIL|Name|Region|Catergory
1|a#a.com|A|AMERICA|PP
2|b#b.com|B|EMEA|CC
3|c#c.com|C|APAC|PP
4|d#d.com|D|APAC|DD
5|E#c.com|E|EMEA|CC
6|E#d.com|ED|UNKNOW|CC
Is there any way to get the below pivot structure table,
Below is the result i would want from the above table in counts,
Category|AMERICAS|EMEA|APAC|UNKNOW
PP|1|0|0|0
CC|0|2|0
DD|0|0|1|0

SELECT *
FROM
(
SELECT id, Catergory, region
FROM table1
) AS t
PIVOT
(
COUNT(ID)
FOR Region IN([AMERICAS],
[EMEA],
[APAC],
[UNKNOW])
) AS p;
SQL Fiddle Demo
DECLARE #cols AS NVARCHAR(MAX);
DECLARE #query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' +
QUOTENAME(Region)
FROM table1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT #query = 'SELECT *
FROM
(
SELECT id, Catergory, region
FROM table1
) AS t
PIVOT
(
COUNT(ID)
FOR Region IN(' + #cols + ')) AS p;';
execute(#query);
Updated SQL Fiddle Demo

Try this one -
DECLARE #temp TABLE
(
ID INT,
Name CHAR(2),
Region VARCHAR(10),
Catergory CHAR(2)
)
INSERT INTO #temp (ID, Name, Region, Catergory)
VALUES
(1, 'A', 'AMERICA', 'PP'),
(2, 'B', 'EMEA', 'CC'),
(3, 'C', 'APAC', 'PP'),
(4, 'D', 'APAC', 'DD'),
(5, 'E', 'EMEA', 'CC'),
(6, 'ED', 'UNKNOW', 'CC')
SELECT *
FROM (
SELECT Name, Region, Catergory
FROM #temp
) src
PIVOT (
COUNT(Name)
FOR Region IN (AMERICAS, EMEA, APAC, UNKNOW)
) pvt
Output -
Catergory AMERICAS EMEA APAC UNKNOW
--------- ----------- ----------- ----------- -----------
CC 0 2 0 1
DD 0 0 1 0
PP 0 0 1 0

Related

Combination of dynamic pivot and static pivot in SQL Server

Dynamic pivot combined combined with static aggregates
I have a table that looks something like this:
Place State Category CategCount MCount Buys Cost
London UK Old 3 NULL 22 4.50
London UK Old 6 5 3 22.00
Brussels BE Young 2 NULL 4 3.50
Brussels BE M NULL 5 12 1.20
Brussels BE M NULL 2 1 1.20
I basically need to:
Group by a number of fields (Place, State, Category in the example)
Count per such group
Sum MCount, Cost (and others, not in example) per group, these columns are static
Pivot over Category and sum CategCount for each such grouped category (here Old, Young). This is the dynamic part
Result should look like:
Count Place State Category SumMCount SumOld SumYoung SumCost SumBuys
2 London UK Old 5 9 0 26.50 25
1 Brussels BE Young 0 0 2 3.50 4
2 Brussels BE NULL 7 0 0 2.40 13
I know how to get a dynamic pivot query (as per https://stackoverflow.com/a/38505375/111575) and I know how to do the static part. But I don't know how to combine the two. Anybody any ideas? Maybe I go about it all wrong?
What I've got so far:
The following gives me the proper dynamic pivot results for Old and Young, but not sure how to add the count and the the 'regular' sums/aggregates to it:
create table #temp
(
Place nvarchar(20),
State nvarchar(20),
Category nvarchar(20) null,
CategCount int null,
MCount int null,
Buys int,
Cost int
)
insert into #temp values ('London', 'UK', 'Old', 3, NULL, 22, 4.50)
insert into #temp values ('London', 'UK', 'Old', 6, 5, 3, 22.00)
insert into #temp values ('Brussels', 'BE', 'Young', 2, NULL, 4, 3.50)
insert into #temp values ('Brussels', 'BE', 'M', NULL, 5, 12, 1.20)
insert into #temp values ('Brussels', 'BE', 'M', NULL, 2, 1, 1.20)
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(Category) + ',' FROM (select distinct Category from #temp where CategCount IS NOT NULL) as tmp
select #cols = substring(#cols, 0, len(#cols)) --trim "," at end
--select (#cols) as bm
set #query =
'SELECT * from
(
select
sum(CategCount) as totalCatCount,
Category
from #temp
group by Category
) src
pivot
(
max(totalCatCount) for Category in (' + #cols + ')
) piv'
execute(#query)
drop table #temp
Returning:
And the following is the 'regular' query without the pivoting:
select count(*) as count, place, state, category,
sum(ISNULL(CategCount, 0)) as SumCatCount,
sum(ISNULL(MCount, 0)) as SumMCount,
sum(ISNULL(buys, 0)) as SumBuys,
sum(Cost) as SumCost
from #temp
group by place, state, category
Returning:
But it should look something like this:
I have used your static pivot part of the query as the source of dynamic pivot. Create two sets of dynamic pivot column list. One for pivoting and the another with Coalesce() to select pivoted columns (to convert null into 0). If there is no categcount for any category then that category has been replaced with null (case when). Two more aliases for Category and SumCatCount have been created since those were used in pivot condition.
Here goes your answer:
create table #temp
(
Place nvarchar(20),
State nvarchar(20),
Category nvarchar(20) null,
CategCount int null,
MCount int null,
Buys int,
Cost int
)
insert into #temp values ('London', 'UK', 'Old', 3, NULL, 22, 4.50)
insert into #temp values ('London', 'UK', 'Old', 6, 5, 3, 22.00)
insert into #temp values ('Brussels', 'BE', 'Young', 2, NULL, 4, 3.50)
insert into #temp values ('Brussels', 'BE', 'M', NULL, 5, 12, 1.20)
insert into #temp values ('Brussels', 'BE', 'M', NULL, 2, 1, 1.20)
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
DECLARE #colsForSelect AS NVARCHAR(MAX)='';
SET #cols = STUFF((SELECT distinct ',' + quotename(category)
FROM #temp where CategCount is not null
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #colsForSelect = STUFF((SELECT distinct ',' + ' Coalesce('+quotename(category)+',0) '+ quotename(category)
FROM #temp where CategCount is not null
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
--select (#cols) as bm
set #query =
'SELECT count,place,state,(case when OldSumCatCount >0 then OldCategory else null end)Category,SumMCount, ' + #colsForSelect + ',SumCost,SumBuys from
(
select count(*) as count, place, state,category OldCategory, category,
sum(ISNULL(MCount, 0)) as SumMCount,
sum(ISNULL(CategCount, 0)) as OldSumCatCount,
sum(ISNULL(CategCount, 0)) as SumCatCount,
sum(Cost) as SumCost,
sum(ISNULL(buys, 0)) as SumBuys
from #temp
group by place , state, category
) src
pivot
(
max(SumCatCount) for Category in (' + #cols + ')
) piv
order by place desc,count'
execute(#query)
GO
count
place
state
Category
SumMCount
Old
Young
SumCost
SumBuys
2
London
UK
Old
5
9
0
26
25
1
Brussels
BE
Young
0
0
2
3
4
2
Brussels
BE
null
7
0
0
2
13
db<>fiddle here
Thanks to #Larnu in the comments for pointing me in the right direction. His/her statement on "you cannot JOIN a static to a dynamic query" and that either all or nothing has to be dynamic, prompted me to build onto the dynamic part and simply extend it.
I thought I needed to repeat the columns somehow in the PIVOT section, but that appears to not be the case. Only the column you want to pivot, apparently (logically so, once you think about it).
The only part I haven't figured out yet is how to get rid of NULL in the resulting set, hopefully someone answers with that in mind ;).
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
SELECT #cols = #cols + QUOTENAME(Category) + ',' FROM (select distinct Category from #temp where CategCount IS NOT NULL) as tmp
select #cols = substring(#cols, 0, len(#cols)) --trim "," at end
--select (#cols) as bm
set #query =
'SELECT * from
(
select
count(*) as count,
Place,
State,
Category,
Category as CatPivot,
sum(ISNULL(CategCount, 0)) as TotalCatCount,
sum(ISNULL(Buys, 0)) as SumBuys,
sum(ISNULL(Cost, 0)) as SumCost,
sum(ISNULL(MCount, 0)) as SumMCount
from #temp
group by Category, Place, State
) src
pivot
(
max(TotalCatCount) for CatPivot in (' + #cols + ')
) piv'
execute(#query)
Here I am sharing another answer which is same but as suggested by #Anthony Hancock dynamic column names for pivot have been created with string_agg() instead of stuff() and xml path for(). It's way too faster and more readable (for SQL Server 2017 and onward)
DECLARE #cols AS NVARCHAR(MAX)='';
DECLARE #query AS NVARCHAR(MAX)='';
DECLARE #colsForSelect AS NVARCHAR(MAX)='';
select #cols =string_agg(category,',') from (
select distinct category FROM #temp where CategCount is not null )t
select #colsForSelect= STRING_AGG(category,',') from
(select distinct 'coalesce('+category+',0) '+category category FROM #temp where CategCount is not null )t
set #query =
'SELECT count,place,state,(case when OldSumCatCount >0 then OldCategory else null end)Category,SumMCount, ' + #colsForSelect + ',SumCost,SumBuys from
(
select count(*) as count, place, state,category OldCategory, category,
sum(ISNULL(MCount, 0)) as SumMCount,
sum(ISNULL(CategCount, 0)) as OldSumCatCount,
sum(ISNULL(CategCount, 0)) as SumCatCount,
sum(Cost) as SumCost,
sum(ISNULL(buys, 0)) as SumBuys
from #temp
group by place , state, category
) src
pivot
(
max(SumCatCount) for Category in (' + #cols + ')
) piv
order by place desc,count'
execute(#query)

Multiple Rows into One Row multiple columns

We need to list all numbers as a flat data set, how can we do that?
Table Name: Telephone
ID TYPE NUMBER
==================================
123 MN 042153939
123 HN 2242116
123 MN 1234567890
123 HN 12345678
Create Table Telephone
(
ID Integer,
Type char(3),
Number Varchar(20)
);
insert into Telephone values
(123, 'MN', '042153939'),
(123, 'HN', '2242116'),
(123, 'MN', '1234567890'),
(123, 'HN', '12345678');
I want SQL to return data in this format
ID MN#1 Mn#2 HN#1 HN#2
================================================
123 042153939 1234567890 2242116 12345678
Dynamic approach
Init
DROP TABLE IF EXISTS #Telephone;
CREATE TABLE #Telephone(ID INT,Type CHAR(3),Number VARCHAR(20));
INSERT INTO #Telephone (ID,Type,Number) VALUES
(123, 'MN', '042153939'),
(123, 'HN', '2242116'),
(123, 'MN', '1234567890'),
(123, 'HN', '12345678');
The code
DECLARE #ColumnList NVARCHAR(MAX);
SELECT #ColumnList = STUFF((SELECT ',[' + RTRIM(t.[Type]) + '#'
+ CONVERT(NVARCHAR(255),ROW_NUMBER()OVER(PARTITION BY t.[Type] ORDER BY t.ID)) + ']'
FROM #Telephone t FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
;
DECLARE #sql NVARCHAR(MAX) = '';
SET #sql = N'
SELECT ID,' + #ColumnList + N'
FROM (
SELECT t.ID,t.Number, RTRIM(t.[Type]) + ''#'' + CONVERT(NVARCHAR(255),ROW_NUMBER()OVER(PARTITION BY t.[Type] ORDER BY t.ID)) AS [Type]
FROM #Telephone t
) a
PIVOT(MAX(a.Number) FOR a.Type IN (' + #ColumnList + N')) p
'
;
--PRINT #sql
IF #sql IS NOT NULL EXEC(#sql);
try pivoting like below :
SELECT first_column AS <first_column_alias>,
[pivot_value1], [pivot_value2], ... [pivot_value_n]
FROM
(<source_table>) AS <source_table_alias>
PIVOT
(
aggregate_function(<aggregate_column>)
FOR <pivot_column> IN ([pivot_value1], [pivot_value2], ... [pivot_value_n])
) AS <pivot_table_alias>;
We can try using a pivot query with the help of ROW_NUMBER():
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY TYPE DESC, NUMBER) rn
FROM Telephone
)
SELECT
ID,
MAX(CASE WHEN rn = 1 THEN NUMBER END) AS [MN#1],
MAX(CASE WHEN rn = 2 THEN NUMBER END) AS [MN#2],
MAX(CASE WHEN rn = 3 THEN NUMBER END) AS [HN#3],
MAX(CASE WHEN rn = 4 THEN NUMBER END) AS [HN#4]
FROM cte
GROUP BY ID;
You may try this. with row_number() and pivot.
For more info about pivot you may find this link PIVOT.
; with cte as (
select row_number() over (partition by type order by id ) as Slno, * from Telephone
)
, ct as (
select id, type + '#' + cast(slno as varchar(5)) as Type, values from cte
)
select * from (
select * from ct
) as d
pivot
( max(values) for type in ( [MN#1],[Mn#2],[HN#1],[HN#2] )
) as p

pivot data from one table

input table
country tag short
UK F1 Units
UK F2 Volume
UK F3 Value
FR T3 Units
FR T2 Volume
FR T1 Value
result output i want :
country Units Volume Value
uk f1 f2 f3
fr t1 t2 t3
If there are a fixed number of different short values, simply use case expressions to do conditional aggregation:
select country,
max(case when short = 'Units' then tag end) as Units,
max(case when short = 'Volume' then tag end) as Volume,
max(case when short = 'Value' then tag end) as val
from tablename
group by country
For solution you have to use dynamic pivoting.
create table #temp
(
country varchar(30),tag varchar(20),short varchar(300)
)
insert into #temp values ('UK', 'F1', 'Units')
insert into #temp values ('UK', 'F2' , 'Volume')
insert into #temp values ('UK' ,'F3', 'Value')
insert into #temp values ('FR', 'T3' , 'Units')
insert into #temp values ('FR' , 'T2', 'Volume')
insert into #temp values ('FR', 'T1' , 'Value')
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.short)
FROM #temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT country, ' + #cols + ' from
(
select country
, tag
, short
from #temp
) x
pivot
(
max(tag)
for short in (' + #cols + ')
) p '
execute(#query)
drop table #temp
Table Structure
CREATE TABLE tablename
(
[country] [NVARCHAR](10) NULL,
[tag] [NVARCHAR](10) NULL,
[short] [NVARCHAR](10) NULL
)
INSERT INTO tablename
VALUES
('UK','F1','Units'),
('UK','F2','Volume'),
('UK','F3','Value'),
('FR','T3','Units'),
('FR','T2','Volume'),
('FR','T1','Value');
Using Pivot function
SELECT *
FROM tablename
PIVOT ( Max(tag)
FOR short IN ([Units], [volume], [Value]) ) piv;
Online Demo: Link
Using Dynamic SQL PIVOT
DECLARE #cols AS NVARCHAR(max),
#query AS NVARCHAR(max)
SELECT #cols = Stuff((SELECT distinct ',' + Quotename(short)
FROM tablename
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1,'');
SET #query = 'SELECT *
FROM tablename
PIVOT ( Max(tag)
FOR short IN (' + #cols + ') ) piv;';
EXECUTE(#query);
Online Demo: Link
Result
+---------+-------+--------+-------+
| country | Units | volume | Value |
+---------+-------+--------+-------+
| FR | T3 | T2 | T1 |
| UK | F1 | F2 | F3 |
+---------+-------+--------+-------+

Separate values of a column as diferrent columns as same query

I have a table UTENSILS with 3 columns like this:
CLASS_NAME RANGE COUNT
---------------------------
pens 0-0.5 200
pencil 0-0.5 50
pens 0.5-1.0 300
pencil 0.5-1.0 40
pens 1.0-1.5 150
pencil 1.0-1.5 45
I want a query that displays the above table result as below:
RANGE Pens Pencils
------------------------------
0-0.5 200 50
0.5-1.0 300 40
1.0-1.5 150 45
Any ideas about this? Thanks in advance!
What you are trying to do is known as a PIVOT. This is when you transform data from rows into columns. Some databases have a PIVOT function that you can take advantage of but you did not specify which RDBMS.
If you do not have a PIVOT function then you can replicate the functionality using an aggregate function along with a CASE statement:
select `range`,
sum(case when class_name = 'pens' then `count` end) pens,
sum(case when class_name = 'pencil' then `count` end) pencils
from yourtable
group by `range`
See SQL Fiddle with Demo
Note: the backticks are for MySQL, if SQL Server then use a square bracket around range and count. These are used to escape the reserved words.
If you are working in an RDBMS that has a PIVOT function, then you can use the following:
select *
from
(
select class_name, [range], [count]
from yourtable
) src
pivot
(
sum([count])
for class_name in ([pens], [pencil])
) piv
See SQL Fiddle with Demo
Both will produce the same result:
| RANGE | PENS | PENCIL |
---------------------------
| 0-0.5 | 200 | 50 |
| 0.5-1.0 | 300 | 40 |
| 1.0-1.5 | 150 | 45 |
The above will work great if you have a known number of values for class_name, if you do not then, depending on your RDBMS there are ways to generate a dynamic version of this query.
In SQL Server a dynamic version will be similar to this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(CLASS_NAME)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT [range], ' + #cols + ' from
(
select CLASS_NAME, [RANGE], [COUNT]
from yourtable
) x
pivot
(
sum([COUNT])
for CLASS_NAME in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo
This pivot query can be used in all major DBMS. The trick is getting the bad column names 'range' and 'count' quoted property.
SQL Server (below) uses [], MySQL uses backticks (`), Oracle uses double quotes, SQLite can use any of the preceding.
select [range],
sum(case when class_name='pens' then [count] else 0 end) Pens,
sum(case when class_name='pencil' then [count] else 0 end) Pencils
from tbl
group by [range]
order by [range];
here is the dynamic version of the pivot:
IF OBJECT_ID('tempdb..#T') IS NOT NULL
DROP TABLE #T
CREATE TABLE #T(
[CLASS_NAME] VARCHAR(20) NOT NULL
, [range] VARCHAR(10) NOT NULL
, [count] INT NOT NULL
)
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pens', '0-0.5', '200')
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pencil', '0-0.5', '50')
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pens', '0.5-1.0', '300')
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pencil', '0.5-1.0', '40')
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pens', '1.0-1.5', '150')
INSERT INTO #T([CLASS_NAME], [range], [count]) VALUES ('pencil', '1.0-1.5', '45')
DECLARE #PivotColumnHeaders VARCHAR(MAX)
SELECT #PivotColumnHeaders = STUFF((
--SELECT DISTINCT TOP 100 PERCENT
SELECT DISTINCT '],[' + [CLASS_NAME]
FROM #T
ORDER BY '],[' + [CLASS_NAME]
FOR XML PATH('')
), 1, 2, '') + ']';
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
SELECT *
FROM (
SELECT *
FROM #T
) AS PivotData
PIVOT (
SUM([count])
FOR [CLASS_NAME] IN (
' + #PivotColumnHeaders + '
)
) AS PivotTable
'
EXECUTE(#PivotTableSQL)

Transforming shape of a SQL Table using Pivot

I have some data stored in a table in the following format
BatchID EntityChanged ChangeValue
EERS ABC DEF
EERS ABCD XYZ
EERS Something SomeValue
New Batch SomethingMore GHI
The list of values that can appear in the "EntityChanged" columns is finite, known beforehand and has no spaces etc in it. For the sake of argument let us say that this list is - ABC, ABCD, Something, SomethingMore
Then for the above dataset I would like an output of
BatchID ABC ABCD Something SomethingMore
EERS DEF XYZ SomeValue NULL
New Batch NULL NULL NULL GHI
Using Pivot I could only go so far.
Can someone please help me slice this data in the desired way?
You can use a PIVOT for this, either via Static PIVOT or a Dynamic PIVOT which might be good if you have a unknown number of columns.
Static (See SQL Fiddle with Demo):
create table t2
(
batchid varchar(10),
entitychanged varchar(20),
changevalue varchar(10)
)
insert into t2 values ('EERS', 'ABC', 'DEF')
insert into t2 values ('EERS', 'ABCD', 'XYZ')
insert into t2 values ('EERS', 'Something', 'SomeValue')
insert into t2 values ('New Batch', 'SomethingMore', 'GHI')
select *
from
(
select batchid, entitychanged, changevalue
from t2
) x
pivot
(
min(changevalue)
for entitychanged in ([ABC], [ABCD], [Something], [SomethingMore])
) p
Dynamic (see SQL Fiddle with Demo):
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(entitychanged)
from t2
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT batchid, ' + #cols + ' from
(
select batchid, entitychanged, changevalue
FROM t2
) x
pivot
(
min(changevalue)
for entitychanged in (' + #cols + ')
) p '
execute(#query)
Both will give you the same result.
Try this:
SELECT BatchID,
MAX(CASE WHEN EntityChanged = 'ABC' THEN ChangeValue END) 'ABC',
MAX(CASE WHEN EntityChanged = 'ABCD' THEN ChangeValue END) 'ABCD',
MAX(CASE WHEN EntityChanged = 'Something' THEN ChangeValue END) 'Something',
MAX(CASE WHEN EntityChanged = 'SomethingMore' THEN ChangeValue END) 'SomethingMore'
FROM YourTable t
GROUP BY BatchID
DEMO