SQL Server Pivot Table with Counts and Sums

后端 未结 1 368
夕颜
夕颜 2020-12-31 18:16

I am trying to get an SQL Server Pivot table to work that allows me to count and then sum a number of columns (6 in total). The purpose of the pivot table is to aggregate on

1条回答
  •  隐瞒了意图╮
    2020-12-31 18:40

    A much easier way to perform this query would be to apply both the UNPIVOT and then the PIVOT functions:

    select *
    from
    (
      select Production_Site, value 
      from t_Pqe_Grocery
      unpivot
      (
        value
        for col in (Grocery_Packaging_And_Coding, Grocery_Measurable,
                    Grocery_Appearance, Grocery_Aroma, 
                    Grocery_Flavour, Grocery_Texture)
      ) unp
    ) src
    pivot
    (
      count(value)
      for value in ([Target], [Action], [Fail])
    ) piv
    

    See SQL Fiddle with Demo

    The UNPIVOT takes your column list and transform it into multiple rows which makes it much easier to count:

    select Production_Site, value 
    from t_Pqe_Grocery
    unpivot
    (
      value
      for col in (Grocery_Packaging_And_Coding, Grocery_Measurable,
                  Grocery_Appearance, Grocery_Aroma, 
                  Grocery_Flavour, Grocery_Texture)
    ) unp
    

    Unpivot Result:

    | PRODUCTION_SITE |  VALUE |
    ----------------------------
    |          Site A | Target |
    |          Site A | Action |
    |          Site A |   Fail |
    |          Site A | Target |
    |          Site A | Target |
    |          Site A | Target |
    |          Site B | Target |
    |          Site B | Action |
    |          Site B |   Fail |
    |          Site B | Target |
    |          Site B | Target |
    |          Site B | Target |
    |          Site C | Target |
    |          Site C | Target |
    |          Site C | Target |
    |          Site C | Target |
    |          Site C | Target |
    |          Site C | Target |
    |          Site A | Target |
    |          Site A | Target |
    |          Site A | Target |
    |          Site A | Target |
    |          Site A | Target |
    |          Site A | Target |
    

    Then applying the PIVOT to this will get the count that you want for each of the PRODUCTION_SITEs. After adding the PIVOT the result is:

    | PRODUCTION_SITE | TARGET | ACTION | FAIL |
    --------------------------------------------
    |          Site A |     10 |      1 |    1 |
    |          Site B |      4 |      1 |    1 |
    |          Site C |      6 |      0 |    0 |
    

    0 讨论(0)
提交回复
热议问题