I currently have a table with all the data, using this data i want to create another table which could be used for auditing purpose (similar layout like pivot table)
Example Below:
Raw Data
Name Places Visited
----------------------------
Will London
John Toronto
Dave New York
Will London
What I want (similar to Pivot Table but I can use letters):
Name/Places Visted London Toronto New York
Will Y N Y
John N Y N
Dave N N Y
Any help to produce this will be much appreciated!
I hope i've explained myself well but let me know if you would like to clarify anything.
Many Thanks!!
Solution for SQL Server 2005/2008:
DECLARE @Temp TABLE
(
Name NVARCHAR(100) NOT NULL
,Place NVARCHAR(100) NOT NULL
);
INSERT @Temp
SELECT 'Will','London'
UNION ALL
SELECT 'John','Toronto'
UNION ALL
SELECT 'Dave','New York'
UNION ALL
SELECT 'Will','London';
SELECT
pvt.Name [Name/Places Visted]
,CASE WHEN [London] IS NOT NULL THEN 'Y' ELSE 'N' END [London]
,CASE WHEN [Toronto] IS NOT NULL THEN 'Y' ELSE 'N' END [Toronto]
,CASE WHEN [New York] IS NOT NULL THEN 'Y' ELSE 'N' END [New York]
FROM @Temp src
PIVOT( MAX(src.Place) FOR src.Place IN([London], [Toronto], [New York]) ) pvt
ORDER BY pvt.Name DESC;
Results:
Name/Places Visted London Toronto New York
------------------- ------ ------- --------
Will Y N N
John N Y N
Dave N N Y
Note: Columns resulting from PIVOT
operation are static. This means that if you add records with Place='PARIS'
you should modify the query like this: PIVOT( MAX(src.Place) FOR src.Place IN([London], [Toronto], [New York], [Paris])
. So, you could use PIVOT
operator if you have a limited number of cities .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.