[英]Filter the values from the source in merge query in mssql
I have the tableA with Key1 , datetime columns when I use merge query to insert I have get the duplicate rows in source. 当我使用合并查询插入时,我有带有Key1的tableA和datetime列,我在源中得到了重复的行。
How can we filer the source inside the query by datetime has maximum 我们如何才能按日期时间对查询中的源进行归档
MERGE tableA AS t
USING (VALUES
('datakeyA1', 'datetime value'),
('datakeyB1', 'datetime value'),
('datakeyA1', 'max datetime value')
) AS s (Key1, datetime)
ON s.Key1 = t.Key1
WHEN MATCHED THEN
UPDATE
SET Val = s.datetime
WHEN NOT MATCHED THEN
INSERT (Key1, datetime)
VALUES (s.Key1, s.datetime);
When run the above query I get the: 运行上面的查询时,我得到:
The MERGE statement attempted to UPDATE or DELETE the same row more than once. MERGE语句尝试多次更新或删除同一行。
Is there any way to query only these rows (' datakeyB1 ', ' datetime value '),(' datakeyA1 ', ' max datetime value ') from all the values without using the intermediate table? 有没有办法从所有值中仅查询这些行(“ datakeyB1 ”,“ datetime value ”),(“ datakeyA1 ”,“ max datetime value ”),而不使用中间表?
Expected results only insert/update the datakeyB1 , datakeyA1 values. 预期结果仅插入/更新datakeyB1 , datakeyA1值。 If the date is same in both the data get only one row. 如果两个数据中的日期相同,则仅获得一行。
MERGE tableA AS t
USING (VALUES
('datakeyB1', 'datetime value'),
('datakeyA1', 'max datetime value')
) AS s (Key1, datetime)
ON s.Key1 = t.Key1
WHEN MATCHED THEN
UPDATE
SET Val = s.datetime
WHEN NOT MATCHED THEN
INSERT (Key1, datetime)
VALUES (s.Key1, s.datetime);
You could wrap the values
clause with a select statement, using top 1 with ties
and order by row_number...
- like this: 您可以使用select语句包装values
子句,并使用top 1 with ties
和order by row_number...
像这样:
MERGE tableA AS t
USING (
SELECT TOP 1 WITH TIES *
FROM
(VALUES
('datakeyA1', 'datetime value'),
('datakeyB1', 'datetime value'),
('datakeyA1', 'max datetime value')
) AS s (Key1, datetime)
ORDER BY ROW_NUMBER() OVER(PARTITION BY Key1 ORDER BY datetime DESC)
) s
ON s.Key1 = t.Key1
WHEN MATCHED THEN
UPDATE
SET Val = s.datetime
WHEN NOT MATCHED THEN
INSERT (Key1, datetime)
VALUES (s.Key1, s.datetime);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.