I have made this query where I get a list of items by their statuses and get the quantities for each status. Here is the query:
SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity
FROM projects
GROUP BY status
ORDER BY Quantity DESC
And here are the results:
Status Quantity
'PRO', 238
'TER', 75
'SUS', 14
'REI', 3
Now for those that have a 'TER' status, I want to get those 'TER' statuses that were updated or modified this year and add them to the results (excluding those 'TER' from previous years). To do this, I have this column updated_at
(so to speak).
How can I filter those values?
For example, I have tried:
SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity,
IF(status='TER',SELECT * FROM projects WHERE year(updated_at)=YEAR(CURDATE()))
FROM projects
GROUP BY status
ORDER BY Quantity DESC
But it didn't work.
Any ideas?
Thanks for the ideas.
Posible solution:
I have figured out another solution by using UNION:
(SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity,
IF(status='TER',SELECT * FROM projects WHERE year(updated_at)=YEAR(CURDATE()))
FROM projects
GROUP BY status
ORDER BY Quantity DESC)
UNION
(
SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity,
IF(status='TER',SELECT * FROM projects WHERE year(updated_at)=YEAR(CURDATE()))
FROM projects
WHERE year(updated_at) = YEAR(curdate())
AND status IN ('TER')
GROUP BY status
ORDER BY Quantity DESC
)
So now I get those projects in 'TER' status and only those within the current year.
So the filter results for 'TER' are now (and should be less results):
Status Quantity
'PRO', 238
'SUS', 14
'REI', 3
'TER', 45
The problem now is that I need to reorder the results, I mean, 'TER' should be in second place... well, I have just found out here.
So my final query is:
SELECT * FROM (
(SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity,
IF(status='TER',SELECT * FROM projects WHERE year(updated_at)=YEAR(CURDATE()))
FROM projects
GROUP BY status
ORDER BY Quantity DESC)
UNION
(
SELECT DISTINCT (status) AS Status, COUNT(status) AS Quantity,
IF(status='TER',SELECT * FROM projects WHERE year(updated_at)=YEAR(CURDATE()))
FROM projects
WHERE year(updated_at) = YEAR(curdate())
AND status IN ('TER')
GROUP BY status
ORDER BY Quantity DESC
)
) a
GROUP BY status
ORDER BY Quantity DESC
And now I get the results I want and ordered desc:
Status Quantity
'PRO', 238
'TER', 45
'SUS', 14
'REI', 3
Or is there a better way out there?