0

I have query as mentioned below

SELECT Project
    ,STATUS
    ,count(*) AS [count]
FROM Defect
GROUP BY Project
    ,STATUS
ORDER BY Project

which will return a table like

enter image description here

I'm trying to PIVOT this result as below

enter image description here

Dale K
  • 25,246
  • 15
  • 42
  • 71
thejustv
  • 2,009
  • 26
  • 42
  • 1
    Does this answer your question? [Convert Rows to columns using 'Pivot' in SQL Server](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – rinz1er Jul 12 '20 at 07:02

3 Answers3

2

You can try the below way -

SELECT * FROM   
(
    SELECT Project,STATUS,count(*) AS cnt FROM Defect GROUP BY Project,STATUS
) t 
PIVOT(
    sum(cnt) 
    FOR STATUS IN (
        [Build Assigned], 
        [Build Delivered], 
        [Closed], 
        [Eng. Build Delivered], 
        [New], 
        [Non-Issue], 
        [Open],[Pending])
) AS pivot_table
Fahmi
  • 37,315
  • 5
  • 22
  • 31
1

would be

with base as
(
SELECT Project
    ,STATUS
    ,count(*) AS [count]
FROM Defect
GROUP BY Project
    ,STATUS
)
select *
from base
pivot (
sum([count])
for base.status in ([Build Delivered],[New],[...],[...])
) as x
order by project
;
0

You can use aggregated function sum with case expressions as following

select
  project,
  sum(case when status = 'Build Assigned' then count else 0 end) as Build_Assigned,
  sum(case when status = 'Build Delivered' then count else 0 end) as Build_Delivered
from yourTable
group by
  project
zealous
  • 7,336
  • 4
  • 16
  • 36