简体   繁体   中英

how to get unique values from all columns based on a primary key sql

I want to subset a table on each primary key ( A in this case), and then obtain a quick distribution for each of the remaining columns (in this case COL1: 2T,1Y,1E and for COL2: 3Z, 1B), then repeat for each primary key.

P   C1  C2
A   T   Z
A   T   Z
A   Y   Z
A   E   B
B   W   M
B   W   M

Is this possible to do in SQL (I am using WPS SQL currently)? Is it possible to loop through each primary key and then review the results, to get something along the lines of:

P C1       C2
A 2T,1Y,1E 3Z,1B
B 2W       2M
...

Note that my data has ~10k unique primary keys and 180 columns

You can use this.

DECLARE @Temp TABLE (P VARCHAR(5),  C1  VARCHAR(5), C2 VARCHAR(5))
INSERT INTO @Temp VALUES
('A','T','Z'),
('A','T','Z'),
('A','Y','Z'),
('A','E','B'),
('B','W','M'),
('B','W','M')


SELECT T.P, 
    STUFF(X1.C1,1,1,'') C1, 
    STUFF(X2.C2,1,1,'') C2 
FROM 
    (SELECT DISTINCT P FROM @Temp) AS T
    CROSS APPLY (SELECT ',' + CONVERT(VARCHAR,COUNT(*)) + C1  
                    FROM @Temp T1 
                    WHERE T.P = T1.P 
                    GROUP BY C1 
                    ORDER BY COUNT(*) DESC
                    FOR XML PATH('')) AS X1 (C1)
    CROSS APPLY (SELECT ',' + CONVERT(VARCHAR,COUNT(*)) + C2  
                    FROM @Temp T2 
                    WHERE T.P = T2.P 
                    GROUP BY C2 
                    ORDER BY COUNT(*) DESC
                    FOR XML PATH('')) AS X2 (C2)

Result

P     C1             C2        
----- -------------- ----------
A     2T,1Y,1E       3Z,1B
B     2W             2M

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM