我的原始数据在表2中。我从头开始创建Table1。我填写了这样的A栏:
INSERT INTO Table1("item")
SELECT DISTINCT(Table2."item")
FROM Table2
我填充了Table1.Totals(B列),如下所示:
UPDATE Table1
SET totals = t2.q
FROM Table1 INNER JOIN
(
SELECT t2."item"
, SUM(t2.quantity) AS q
FROM t2
GROUP BY t2."item"
) AS t2
ON Table1."item" = t2."item"
如何填充Table1。“date”?我上面的UPDATE在这里不起作用,因为我不能在日期上使用聚合函数。我能够在单独的查询中使用以下代码获得我想要的结果:
SELECT DISTINCT Table1."item"
, Table2."date"
FROM Table1 INNER JOIN Table2
ON Table1."item" = Table2."item"
ORDER BY Table1."item"
但是如何使用此查询的结果来设置列的值?我正在使用SQL Server 2008。
答案 0 :(得分:6)
如果你不能像@Lamak建议的那样重新插入,那么你可以用这种方式执行UPDATE
:
UPDATE t1
SET t1.Date = s.Date
FROM Table1 AS t1
INNER JOIN
(
SELECT Item, [Date] = MAX([Date]) -- or MIN()
FROM Table2
GROUP BY Item
) AS s
ON t1.Item = s.Item;
答案 1 :(得分:4)
对于SQL Server,您可以使用单个INSERT
语句:
INSERT INTO Table1(Item, Totals, [Date])
SELECT Item, SUM(Quantity), MIN([Date]) -- It could be MAX([Date])
FROM Table2
GROUP BY Item
答案 2 :(得分:0)
最简单的方法是使用简单的CTAS(create table as select):
select item as item, SUM(quantity) as Q, MIN(date) as d into table2
from table1
group by item
答案 3 :(得分:0)
您可以使用@Lamak's answer中的select语句创建视图,而不是创建表格。这样,每次Table2
更新时,您都不必更新新的行集。