how to query in sql the previous date of max date of an item and if only one date is there for an item return that date as result. Attaching sample Image for refference
Your question was a little crude and was lacking own attempts to solve this but here you go
create table d(
item VARCHAR(1),
expiry_date DATETIME
);
INSERT INTO d(item, expiry_date)
VALUES
('A','2018-03-08'),
('A','2018-03-11'),
('A','2018-03-31'),
('A','2019-01-12'),
('A','2019-03-01'),
('A','2019-03-21'),
('A','2020-03-01'),
('B','2021-03-26'),
('C','2019-03-01'),
('C','2019-03-21'),
('C','2020-03-01');
;WITH maxdates AS (
SELECT
item,
MAX(expiry_date) max_expiry_minus_1
FROM d
WHERE d.expiry_date != (SELECT MAX(expiry_date) FROM d d2 WHERE d.item = d2.item)
GROUP BY item
)
SELECT
d.item,
d.expiry_date,
ISNULL(maxdates.max_expiry_minus_1, expiry_date) expecting_result
FROM d
LEFT OUTER JOIN maxdates
ON d.item = maxdates.item
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.