0

给定下表作为 SQL 结果:

当前结果

我想使用上面生成的表格并生成一个表格,其中包含给定信息:

要求的结果

我有多个 areaName 和多个 functionNames 和多个用户。请让我知道这是否可能以及如何?

我已经尝试了几件事,但我现在筋疲力尽,需要一个方向。任何帮助表示赞赏。

即使您可以提供伪代码,我也可以尝试使用它。从作为给定表的 SQL 结果开始。

4

2 回答 2

0

Use correlated sub-queries to achieve the desired result. I've provided an example below. Test it for the first summary column, and then add in your other summary columns if it does. Hopefully this makes sense, and helps. Alternatively you could use a CTE (common table expression) to achieve similar results.

SELECT a.areaName, a.functionName
       , (SELECT count(DISTINCT b.UserKey) 
             from AREAS b 
             where a.areaName = b.areaName 
             and a.functionName = b.functionName 
             and b.[1-add] = 1) as UsersinAdd
-- Lather/rinse/repeat for other summary columns

FROM AREAS a
group by a.areaName, a.functionName
于 2013-10-18T21:17:03.130 回答
0

您的问题源于表格的非规范化结构。列[1-add],...,[8-correction]应该是列中的值,而不是列。正如您所发现的,这会导致更复杂的查询。

unpivot命令允许您更正此错误。

select areaname, functionname, rights, count(distinct userkey)
    from 
    (
    select * from yourtable
        unpivot (permission for rights in ([1-add], [2-update/display],[4-update/display all] , [8-correction] )) u
    ) v
    group by areaname, functionname, rights
于 2013-10-19T09:19:13.803 回答