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
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_SITE
s. 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 |