Group by latest date with conditions
1
vote
1
answer
4751
views
I need your help!
Let's say I have this table:
Instance|Date |MetricID|Value
|--| --- | --- |---|---|
|Marc | 09/14/21|1|5
|Marc |09/14/21|2|2
|Marc |09/14/21|3|1
|John | 09/14/21|1|10
|John |09/14/21|2|1
|John |09/14/21|3|1
|Marc | 09/15/21|1|15
|Marc |09/15/21|2|0
|Marc |09/15/21|3|1
|John |09/15/21|1|10
|John |09/15/21|2|1
|John |09/15/21|3|0
And I want this:
Instance|LatestDateMetric1 |LatestDateMetric2|LatestDateMetric3
|--| --- | --- |---|---|
|Marc | 09/15/21|09/14/21|09/15/21
|John |09/15/21|09/15/21|09/14/21
I tried this code, It looks a bit like I want except It takes the value even if it is null and the result is by line not column.
SELECT "Instance", "MetricID", MAX("Date") as "LatestDate"
FROM "API_Metric2"
GROUP BY "Instance", "MetricID"
This is the result I got:
Instance|MetricID|LatestDate
|--| --- | --- |---|---|
|Marc |1|09/15/21|1
|Marc |2|09/15/21|2
|Marc |3|09/15/21|3
|John |1| 09/15/21|1
|John |2|09/15/21|2|
|John |3|09/15/21|3
And I also tried this:
SELECT "Instance",
CASE WHEN "MetricID"=1 AND "Value" NOT NULL THEN MAX("Date") ELSE 0 END) AS "LatestDateMetric1",
CASE WHEN "MetricID"=2 AND "Value" NOT NULL THEN MAX("Date") ELSE 0 END) AS "LatestDateMetric2",
CASE WHEN "MetricID"=3 AND "Value" NOT NULL THEN MAX("Date") ELSE 0 END) AS "LatestDateMetric3"
FROM "StackExemple"
GROUP BY "Instance", "Date", "MetricID"
But I get this error message:
> Parse error at line 2, column 66. Encountered: "Value"
***Edit***: I also got this code which seems to be working but It's not taking the null values into account. It only display 09/15/21 as the LatestDate for all metrics.
SELECT "InstanceName",
MAX(CASE WHEN "MetricID" = 4 THEN "Date" END) as "LatestProjectCreated",
MAX(CASE WHEN "MetricID" = 5 THEN "Date" END) as "LatestActionCreated",
MAX(CASE WHEN "MetricID" = 8 THEN "Date" END) as "LatestUserCreated"
FROM "API_InstanceMetric"
GROUP BY "InstanceName";
***Edit2***: The issue persists even with adding the "Value IS NOT NULL" as below
SELECT "Instance",
MAX(CASE WHEN "MetricID" = 1 AND "Value" IS NOT NULL THEN "Date" END) as "LatestProjectCreated",
MAX(CASE WHEN "MetricID" = 2 AND "Value" IS NOT NULL THEN "Date" END) as "LatestActionCreated",
MAX(CASE WHEN "MetricID" = 3 AND "Value" IS NOT NULL THEN "Date" END) as "LatestUserCreated" FROM "StackExemple" GROUP BY "Instance";
Asked by no name sry
(11 rep)
Sep 15, 2021, 10:05 AM
Last activity: Aug 6, 2025, 04:09 PM
Last activity: Aug 6, 2025, 04:09 PM