我正在尝试使用以下查询更新表的列。但是我收到错误
聚合可能不会出现在UPDATE语句的集合列表中
代码:
UPDATE Test.dbo.Table1
SET InDate = MIN(b.Date)
FROM
Test.dbo.Table1 a
LEFT OUTER JOIN
Test.dbo.Table2 b
ON
a.ID1 = b.ID2
WHERE b.Code = 'IN';
我想更新表格中的InDate列,其中包含Table2(b.Date)列中最早的日期,其中(b.code)是' IN'
这里有什么问题?
答案 0 :(得分:0)
您需要将聚合放在临时表或子查询中,并且需要显式的GROUP BY
语句。
UPDATE Test.dbo.Table1
SET InDate = min_date
FROM Test.dbo.Table1 c inner join
(SELECT a.id1, MIN(b.Date) min_date
FROM Test.dbo.Table1 a
LEFT OUTER JOIN Test.dbo.Table2 b
ON a.ID1 = b.ID2
Group by a.id1) d
ON c.ID1 = d.ID1
WHERE c.Code = 'IN';
答案 1 :(得分:0)
我认为这会做你想要的。我删除了别名以使其尽可能清晰:
UPDATE Table1
SET InDate = (
SELECT MIN(Table2.Date)
FROM Table2
WHERE Table1.ID1 = Table2.ID2
AND Table2.Code = 'IN'
)
答案 2 :(得分:0)
您可以使用apply获取最小日期,然后在更新语句中使用它:
UPDATE a
SET a.InDate = b.MinBDate
FROM Table1 a
OUTER APPLY
(
SELECT MIN(b.InDate) MinBDate
FROM Table2 b
WHERE b.Id = a.Id
AND b.Code = 'IN'
) b
答案 3 :(得分:0)
也许这个?
UPDATE Test.dbo.Table1
SET InDate = b.Date
FROM
Test.dbo.Table1 a
INNER JOIN (
select
b.ID2,
MIN(b.Date) Date
from Test.dbo.Table2 b
where
WHERE b.Code = 'IN'
group by
b.ID2
) b
ON
a.ID1 = b.ID2
答案 4 :(得分:0)
假设您的数据模型类似于以下内容,那么加入派生表应该可以解决这个问题:
--Data Setup:
DECLARE @Table1 TABLE (ID1 INT, InDate DATETIME)
DECLARE @Table2 TABLE (ID2 INT, ID1 INT, Date DATETIME, Code VARCHAR(12))
INSERT INTO @Table1 (ID1)
VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
INSERT INTO @Table2 (ID2, ID1, Date, Code)
VALUES
(1, 1, '1/1/2014', 'OUT'),
(2, 1, '5/1/2014', 'IN'),
(3, 1, '3/1/2013', 'IN'),
(4, 2, '1/1/2014', 'OUT'),
(5, 2, '1/1/2014', 'IN'),
(6, 3, '1/1/2014', 'IN'),
(7, 4, '1/1/2014', 'IN'),
(8, 5, '1/1/2014', 'IN'),
(9, 6, '2/1/2014', 'OUT'),
(10, 7, '3/1/2014', 'IN'),
(11, 8, '4/1/2014', 'IN'),
(12, 9, '2/1/2014', 'IN'),
(12, 9, '2/1/2014', 'IN'),
(12, 10, '1/2/2014', 'IN'),
(12, 10, '1/3/2014', 'IN'),
(12, 10, '1/4/2014', 'IN'),
(12, 10, '1/1/2014', 'OUT')
--Actual Update:
UPDATE T1
SET InDate = T2.MinDate
FROM @Table1 T1
JOIN (SELECT T2.ID1, MIN(Date) AS MinDate
FROM @Table2 T2
WHERE T2.Code = 'IN'
GROUP BY T2.ID1) T2 ON T2.ID1 = T1.ID1
--Results
SELECT *
FROM @Table1