Click here to Skip to main content
15,991,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
How do I get a count per user for each month per status

I have a table that contains user, status, and DateCreated

I want to display the count per status per month for each user.

I am not that clued up on CTE and I want to combine the 2 queries to get the desired output below

I want my data to show as follows

| UserName | Completed | Incompleted | Month and Year |
| Paul     |    2      |      0      |    July 2024   |
| Paul     |    0      |      1      |    June 2024   |
| Paul     |    0      |      1      |    March 2024  |


What I have tried:

I have tried the below

<pre>CREATE TABLE UserProgress
(   
        id          INT         NOT NULL IDENTITY
    ,   UserName  DATETIME    NOT NULL
    ,   Status   VARCHAR(20) NOT NULL
    ,   DateCreated        DATETIME NOT NULL
);

INSERT INTO UserProgress (id, UserName, Status, DateCreated) VALUES
    (1, 'Paul', 'Completed', '2024-07-10 10:48:21.970'),
    (2, 'Paul', 'Finalized', '2024-07-10 10:48:21.970'),
    (3, 'Paul', 'In-progress', '2024-03-10 10:48:21.970'),
    (4, 'Paul', 'Autorised', '2024-06-10 10:48:21.970'),
;

-- completed
SELECT UserName
,COUNT(*) AS [COMLETED]
,DATEADD(MONTH, DATEDIFF(MONTH, 0, DateCreated), 0) AS [Month and Year]
FROM UserProgress
WHERE Status in ('Completed','Finalized')
GROUP BY UserName,DateCreated
ORDER BY a.UserName,DateCreated

-- not completed
select UserName
,count(*) as [COMLETED]
,DATEADD(MONTH, DATEDIFF(MONTH, 0, DateCreated), 0) AS [Month and Year]
from UserProgress
where Status in ('Completed','Finalized')
group by UserName,DateCreated
order by UserName,DateCreated
Posted

1 solution

Something like this should do the job:
SQL
SELECT
    P.UserName,
    SUM(CASE WHEN P.Status In ('Completed', 'Finalized') THEN 1 ELSE 0 END) As [Completed],
    SUM(CASE WHEN P.Status In ('Completed', 'Finalized') THEN 0 ELSE 1 END) As [Incompleted],
    M.MonthCreated
FROM
    UserProgress As P
    CROSS APPLY (SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, DateCreated), 0)) As M (MonthCreated)
GROUP BY
    P.UserName,
    M.MonthCreated
ORDER BY
    UserName,
    MonthCreated
;
 
Share this answer
 
Comments
[no name] 23-Jul-24 22:21pm    
@Slope Game Brilliant! It completely works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900