I am trying to take a very large product table that has one row per product status and date, and get down to a table that demonstrates the latest status for each product they own.
I think if I concatenate the account and product columns and then use that to find the max date but I'm stumbling with my code. Would appreciate any insight!
Example table
Account | Product | EffectiveDate | Status |
---|---|---|---|
10000 | Product A | 5/1/2021 | Live |
10000 | Product A | 9/1/2020 | Decomissioned |
10000 | Product B | 12/1/2021 | Implementing |
My goal output would be:
Account | Product | EffectiveDate | Status |
---|---|---|---|
10000 | Product A | 5/1/2021 | Live |
10000 | Product B | 12/1/2021 | Implementing |
SELECT X.Account,X.Product,X.EffectiveDate,X.Status FROM
(
SELECT E.Account,E.Product,E.EffectiveDate,E.Status,
ROW_NUMBER()OVER(PARTITION BY E.Product ORDER BY E.EffectiveDate DESC)AS XCOL
FROM Example_table AS E
)X WHERE X.XCOL=1
May be something like this will be suitable
For some DBMS you can use a window function and qualify
. On others (SQL Server) you can use top
and a window function.
create table T1 (Account int, Product varchar(255), EffectiveDate date, status varchar(255));
insert into T1 (Account, Product , EffectiveDate , "STATUS" ) values
(10000, 'Product A', '2021-05-01', 'Live'),
(10000, 'Product A', '2020-09-01', 'Decomissioned'),
(10000, 'Product B', '2021-12-01', 'Implementing');
-- Snowflake, Teradata, Oracle, others...
select Account, Product, EffectiveDate, Status
from T1
qualify row_number() over (partition by Account, Product order by EffectiveDate desc) = 1
;
-- SQL Server
select top 1 with ties Account, Product, EffectiveDate, Status
from T1
order by row_number() over (partition by Account, Product order by EffectiveDate desc);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.