sql Pivot我该怎么做呢

时间:2014-01-05 17:29:57

标签: sql sql-server sql-server-2008 tsql sql-server-2005

I have 3 tables
------------------------
users
1 ->    mark
2 ->    adel
3 ->    khali
4 ->    piter
5 ->    adam

------------------------
groups 
1 ->    group 1 
2 ->    group 2 
3 ->    group 3  
4 ->    group 4 
---------------------- 
usersGroups

1 ->    4
3 ->    2
4 ->    3
1 ->    2

I want to display 
if username has a group then 1 if it hasn't then 0 
 like this whith pivot but I dont know how ??? 


-- username     group1  group2  group3  group4
----------------------------------------------------
--  mark        0       1       0       1
--  adel        0       1       0       0
--  adam        0       0       1       0   



  I try this please help me


 SELECT username, [group1] AS 'group1', [group2] AS 'group2', [group3] AS 'group3', [group4] AS 'group4'    
    FROM 
    (
    SELECT  ug.groupid, ug.userid, g.description, u.username FROM users u 
                    INNER JOIN usersgroups ug ON u.userid = ug.userid 
                    INNER JOIN groups g ON ug.groupid = g.groupid 
    )AS q
    PIVOT
    (COUNT(groupid) FOR [description] IN ([group1],[group2],[group3],[group4])) AS pvt 

2 个答案:

答案 0 :(得分:1)

测试数据

DECLARE @users TABLE (userid INT, username NVARCHAR(100))
INSERT INTO @users
VALUES (1,'mark'),(2,'adel'),(3,'khali'),(4,'piter'),(5,'adam')

DECLARE @groups TABLE (groupid INT, [description] NVARCHAR(100))
INSERT INTO @groups
VALUES 
(1,'group 1'),(2,'group 2'),(3,'group 3'),(4,'group 4')

DECLARE @usersGroups TABLE (userid INT, groupid INT)
INSERT INTO @usersGroups
VALUES (1,4),(3,2),(4,3),(1,2)

<强>查询

SELECT username
     , CASE WHEN  [group 1] IS NOT NULL THEN 1 ELSE 0 END AS 'group1'
     , CASE WHEN  [group 2] IS NOT NULL THEN 1 ELSE 0 END AS 'group2'
     , CASE WHEN  [group 3] IS NOT NULL THEN 1 ELSE 0 END AS 'group3'
     , CASE WHEN  [group 4] IS NOT NULL THEN 1 ELSE 0 END AS 'group4'    
    FROM 
    (
        SELECT  ug.groupid, ug.userid, g.description, u.username 
        FROM @users u INNER JOIN @usersGroups ug 
        ON u.userid = ug.userid 
        INNER JOIN @groups g 
        ON ug.groupid = g.groupid 
    )AS q
    PIVOT
    (MIN(groupid) 
    FOR [description] 
    IN ([group 1],[group 2],[group 3],[group 4])
    ) AS pvt 

结果集

╔══════════╦════════╦════════╦════════╦════════╗
║ username ║ group1 ║ group2 ║ group3 ║ group4 ║
╠══════════╬════════╬════════╬════════╬════════╣
║ mark     ║      0 ║      1 ║      0 ║      1 ║
║ khali    ║      0 ║      1 ║      0 ║      0 ║
║ piter    ║      0 ║      0 ║      1 ║      0 ║
╚══════════╩════════╩════════╩════════╩════════╝

答案 1 :(得分:0)

SELECT  case when ug.groupid is null then 0 else 1 end as groupid, 
        ug.userid, g.description, u.username FROM users u 
LEFT JOIN usersgroups ug ON u.userid = ug.userid 
INNER JOIN groups g ON ug.groupid = g.groupid 

然后将汇总COUNT(groupid)更改为MAX(groupid)