I have a table of events. I would like to eliminate certain values which appear multiple times, e.g.
CreateDate EventCode
------------------------
2023-03-20 EMA
2023-03-21 EMD
2023-03-22 EMD
2023-03-22 EMF
2023-03-23 EMI
2023-03-24 EMI
The EMI
must only appear once and only the first EMI from 23 March. Other duplicates like EMD can remain.
So the result should be
CreateDate EventCode
------------------------
2023-03-20 EMA
2023-03-21 EMD
2023-03-22 EMD
2023-03-22 EMF
2023-03-23 EMI
A simple group by will eliminate the duplicate EMDs
Here my attempt with sample SQL:
DROP TABLE IF EXISTS #Movements
CREATE TABLE #Movements
(
CreateDate datetime2,
EventCode nvarchar(3)
)
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-20', 'EMA')
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-21', 'EMD')
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-22', 'EMD')
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-22', 'EMF')
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-23', 'EMI')
INSERT INTO #Movements (CreateDate, EventCode) VALUES ('2023-03-24', 'EMI')
SELECT * FROM #Movements
SELECT EventCode
FROM #Movements
GROUP BY EventCode
3条答案
按热度按时间x6yk4ghg1#
This will handle the cases where the EMI can be found 2 times or more :
Demo here
92dk7w1h2#
It can be just
nmpmafwu3#
You just need to group by both columns, but null out
CreateDate
for rows whereEventCode = 'EMI'
. Then takeMIN(CreateDate)
for those rows instead.db<>fiddle