Skip to content
Advertisement

SQL Pivot count incomplete and complete

First of let me start by saying that my SQL know how is pretty limited. So I have below table table

Now I would like to create a pivot in SQL that looks like so
pivot

Now PN from second column can repeat from time to time.
While I managed to count complete and incomplete, can’t seem to figure out how to say PN and EntryDate combo (concatenation) is unique and want to count based on that (see green and yellow rows as same PN).
Basically if “Completed” row has data is complete and if null is incomplete.

Database is MS SQL
All help is appreciated,
Thank you

Advertisement

Answer

Try this below logic using Aggregation-

SELECT PN,
SUM(CASE WHEN completed IS NOT NULL THEN 1 ELSE 0 END) Completed,
SUM(CASE WHEN completed IS NULL THEN 1 ELSE 0 END) Incomplete,
COUNT(*) Total
FROM your_table
GROUP BY PN

OR

SELECT PN,
COUNT(completed) Completed,
COUNT(*) - COUNT(completed) Incomplete,
COUNT(*) Total
FROM your_table
GROUP BY PN

As you commented and wants separate records by EntryDate as well, you can do this folowing-

SELECT PN,
SUM(CASE WHEN completed IS NOT NULL THEN 1 ELSE 0 END) Completed,
SUM(CASE WHEN completed IS NULL THEN 1 ELSE 0 END) Incomplete,
COUNT(*) Total
FROM your_table
GROUP BY PN, EntryDate
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement