I have one table and data in it. Below is the table
+----+-------+------+---------+-------------+-----------+
| Id | p_name| grade| promoted| created_on | review_by |
+----+-------+------+---------+-------------+-----------+
| 1 | Abc | A | Yes | 2023-Jun-14 | AK |
| 1 | Abc | A | Yes | 2023-Jun-17 | RSK |
| 1 | Abc | B | Yes | 2023-Jun-15 | PS |
| 1 | Abc | B | Yes | 2023-Jun-16 | ZX |
| 2 | Pqr | A | Yes | 2023-May-10 | CB |
| 2 | Pqr | B- | Yes | 2023-May-05 | MN |
| 2 | Pqr | B | Yes | 2023-May-07 | KL |
+----+-------+------+---------+-------------+-----------+
I need below result and it is based on conditions
+----+-------+--------------+-------------------+--------------+------------------+
| Id | p_name| Date for AA | review_by for AA | Date for BB | review_by for BB |
+----+-------+--------------+-------------------+--------------+------------------+
| 1 | Abc | 2023-Jun-17 | RSK | 2023-Jun-16 | ZX |
| 2 | Pqr | 2023-May-10 | CB | 2023-May-7 | KL |
+----+-------+--------------+-------------------+--------------+------------------+
conditions : –
-
When Grade in ( A,A-) and promoted = Yes then
select Latest Date(‘created on’ column) save value into "Date for AA" column
and (‘revew_by’ column as per latest date) save value into "review_by for AA" column -
When Grade in ( B,B-) and promoted = Yes then
select Latest_Date(‘created_on’ column) save value into "Date for BB" column
and (‘revew_by’ column as per latest date) save value into "review_by for BB" column
This condition is for each id(1,2) and get single result for each id as mention in
result table.
In details : – Latest Date When Grade A/A- is promoted to Yes in "Date for AA"
column and reviewby as per latest date of "created_on" column and it should be group by id.
And Latest Date When Grade B/B- is promoted to Yes in "Date for BB"
column and reviewby as per latest date of "created_on" column and it should be group by id
2
Answers
my old query is
After some little changes, i got my answer.Below is correct query
Your query returns the incorrect value for
review_by for BB
forId = 2
. This is because you are returningMAX(review_by)
per group, notreview_by
forMAX(created_on)
per group.Assuming you are using MySQL >= 8.0, you can use ROW_NUMBER() in a CTE, and then your conditional aggregation to pivot the remaining rows:
For older versions of MySQL, you can use an aggregate query to get the max dates as a derived table and then join back to the main table:
Here’s a db<>fiddle.