按组计算并列出唯一组合

时间:2017-10-08 22:04:25

标签: tsql

我想得到一个可以带来以下结果的SQL,但我似乎无法理解这个特定场景。

我想知道USER有多少个ROLE组合的组合,并报告计数并列出角色名称。

以下是示例表:

/usr/lib64

有AAA和BBB与#34; Report-Inquiry-Manager"的角色组合,因此计数为2。

只有CCC有查询报告。

DDD和HHH具有报告的作用。

因此,所需的输出将是

USER ROLE
AAA  Report
AAA  Enquiry
AAA  Manager
BBB  Report
BBB  Enquiry
BBB  Manager
CCC  Enquiry
CCC  Report
DDD  Report
EEE  Report
EEE  Enquiry
EEE  Admin
FFF  Report
FFF  Enquiry
GGG  Report
GGG  Enquiry
GGG  Manager
GGG  PAYROLL
HHH  Report
III  Report
III  Enquiry

请有人指出我正确的方向。

谢谢你,

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY来获取计数并使用STUFF获取-个单独的角色值。

create table test
(
    [USER] varchar(10)
    ,[Role] varchar(100)
)
insert into test values
('AAA','Report')
,('AAA','Enquiry')
,('AAA','Manager')
,('BBB','Report')
,('BBB','Enquiry')
,('BBB','Manager')
,('CCC','Enquiry')
,('CCC','Report')
,('DDD','Report')
,('EEE','Report')
,('EEE','Enquiry')
,('EEE','Admin')
,('FFF','Report')
,('FFF','Enquiry')
,('GGG','Report')
,('GGG','Enquiry')
,('GGG','Manager')
,('GGG','PAYROLL')
,('HHH','Report')
,('III','Report')
,('III','Enquiry')


select COunt(1) as [COUNT], [Role-Combination] from 
(

select Count(1) as [Count], t.[User]
,STUFF((SELECT 
                        '-' + cm.[role] AS [text()]
                    FROM 
                    test cm
                    WHERE
                    cm.[user] = t.[user]
                    order by [role] desc
                        FOR XML PATH('')
                        , root('user'), TYPE).value('.','varchar(max)'), 1, 1, '' )AS [Role-Combination]
from test t
GROUP BY t.[User]

) result
group by result.[Role-Combination]

DROP TABLE test

答案 1 :(得分:0)

DECLARE @USER TABLE 
(
    xUSER VARCHAR(30),
    xROLE VARCHAR(30)
)
INSERT INTO @USER (xUSER,xROLE)
VALUES
('AAA','Report'),
('AAA','Enquiry'),
('AAA','Manager'),
('BBB','Report'),
('BBB','Enquiry'),
('BBB','Manager'),
('CCC','Enquiry'),
('CCC','Report'),
('DDD','Report'),
('EEE','Report'),
('EEE','Enquiry'),
('EEE','Admin'),
('FFF','Report'),
('FFF','Enquiry'),
('GGG','Report'),
('GGG','Enquiry'),
('GGG','Manager'),
('GGG','PAYROLL'),
('HHH','Report'),
('III','Report'),
('III','Enquiry')

; WITH x AS
(
    SELECT DISTINCT
        xUSER,
        STUFF((
            SELECT '- ' + xRole
            FROM @User
            WHERE xUser = a.xUSer           
            ORDER BY xRole
            FOR XML PATH ('')
        ), 1, 1, '') Groups
    FROM @User a
)
SELECT 
    [Cnt] = COUNT(xUser),   Groups as [Role-Cmbine]
FROM x
GROUP BY Groups
ORDER BY [Cnt] DESC