2

以下のデータがあります。

TestName  Stage1  Stage2  Stage3  Stage4
Test1     John    Calra   John    Calre
Test2     Calra   null    John    Calra

以下の形式でデータを表示するクエリを実装する必要があります。

User    Stage1count  Stages2Count  Stages3count  Stages4Count
John         1             0             2             0
Calra        1             1             0             2

ありがとうジョン

4

2 に答える 2

2

a を使用しunionてデータを正規化できます。その後、通常のpivot戦略が機能します。

select  Name
,       sum(case when Stage = 1 then 1 end) as Stage1count
,       sum(case when Stage = 2 then 1 end) as Stage2count
,       sum(case when Stage = 3 then 1 end) as Stage3count
,       sum(case when Stage = 4 then 1 end) as Stage4count
from    (
        select  1 as Stage
        ,       Stage1 as Name
        from    YourTable
        union all
        select  2 as Stage
        ,       Stage2 as Name
        from    YourTable
        union all
        select  3 as Stage
        ,       Stage3 as Name
        from    YourTable
        union all
        select  4 as Stage
        ,       Stage4 as Name
        from    YourTable
        ) as SubQueryAlias
group by
        Name
于 2012-07-31T07:02:05.397 に答える
0

これを試して

 drop table tests
    CREATE TABLE tests(TestName varchar(10),Stage1 varchar(10),Stage2 varchar(10),Stage3 varchar(10),Stage4 varchar(10))
    INSERT INTO tests
    VALUES('Test1','John','Calra','John','Calra'),('Test2','Calra',null,'John','Calra')

select * from tests

    select 'John' as [User] 
          ,SUM(case when stage1='John' then 1 else 0 end) as stage1
          ,SUM(case when stage2='John' then 1 else 0 end) as stage2
          ,SUM(case when stage3='John' then 1 else 0 end) as stage3
          ,SUM(case when stage4='John' then 1 else 0 end) as stage4
    from tests 
    UNION 

    select 'Calra' as [User] 
          ,SUM(case when stage1='Calra' then 1 else 0 end) as stage1
          ,SUM(case when stage2='Calra' then 1 else 0 end) as stage2
          ,SUM(case when stage3='Calra' then 1 else 0 end) as stage3
          ,SUM(case when stage4='Calra' then 1 else 0 end) as stage4
    from tests 
于 2012-07-31T08:22:45.910 に答える