A.B.
A.B.

Reputation: 2470

SQL Server : 2 Pivot Questions

All the pivot examples i saw till now use aggregate functions. So i have no idea how i can achieve the following:

I have this simple table for test purposes:

;WITH cte AS (
SELECT * FROM (VALUES
(1, 'Messi',    'Graz'),
(2, 'Ronaldo',  'Graz'),
(3, 'Weah',     'Wien'),
(4, 'Nedved',   'Wien'),
(5, 'Hagi',     'Wien'),
(6, 'Puskas',   'Istanbul'),
(7, 'Stoichkov', 'Dubai'),
(8, 'Di Baggio', 'Dubai')
) as t(cid, name, city))

I want to achieve the following:

  1. To rotate the table like this:

    enter image description here

  2. And I want to rotate the following query:

    SELECT city, COUNT(city) AS num_of_customers 
    FROM CUSTOMERS 
    GROUP BY city;
    

which produces the following result:

enter image description here

I want to display it like this:

enter image description here

I never worked with pivot tables until now and I would be grateful for any kind of help.

PS: table name is Customers.

Upvotes: 1

Views: 72

Answers (2)

Rahul
Rahul

Reputation: 77896

Second query can be achieved like below

select Dubai,Graz,Istanbul,Wien
from Customers
pivot
(
COUNT(city)
for city
in ([Dubai],[Graz],[Istanbul],[Wien])
)
as pivottab

Upvotes: 1

jpw
jpw

Reputation: 44891

Both queries are easy to do in a dynamic fashion, which is nice if you don't have a fixed number of rows and need the query to adapt to the number of rows.

The first query:

DECLARE @players AS VARCHAR(MAX)
SELECT @players = STUFF((SELECT DISTINCT ',['+CAST(cid AS VARCHAR(10))+']'
FROM customers FOR XML PATH('')),1,1,'')
DECLARE @dynamic_pivot_query AS VARCHAR(MAX)

SET @dynamic_pivot_query = 'SELECT '+@players+'
  FROM (SELECT cid, name FROM customers) AS S
  PIVOT (MAX(name) FOR cid IN ('+@players+')
) AS P'

EXEC(@dynamic_pivot_query)

Result:

1       2       3       4       5       6       7           8
Messi   Ronaldo Weah    Nedved  Hagi    Puskas  Stoichkov   Di Baggio

The second query:

DECLARE @cities AS VARCHAR(MAX)
SELECT @cities = STUFF((SELECT DISTINCT ',['+city+']'
FROM customers FOR XML PATH('')),1,1,'')

DECLARE @dynamic_pivot_query AS VARCHAR(MAX)
SET @dynamic_pivot_query = 'SELECT '+@cities+' 
   FROM (SELECT city FROM customers) as S
   PIVOT (COUNT(city) FOR city IN ('+@cities+')
) AS P'

EXEC(@dynamic_pivot_query)

Result:

Dubai       Graz        Istanbul    Wien
----------- ----------- ----------- -----------
2           2           1           3

Upvotes: 2

Related Questions