使用其他表中的值更新列,不能使用不同的函数
我的原始数据在表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"?我上面的更新在这里不起作用,因为我无法在日期上使用聚合函数。我能够在单独的查询中使用以下代码获得我想要的结果:
SELECT DISTINCT Table1."item"
, Table2."date"
FROM Table1 INNER JOIN Table2
ON Table1."item" = Table2."item"
ORDER BY Table1."item"
但是如何使用此查询的结果来设置列的值?我正在使用 SQL Server 2008。
My original data is in Table2. I created Table1 from scratch. I populated Column A like this:
INSERT INTO Table1("item")
SELECT DISTINCT(Table2."item")
FROM Table2
I populated Table1.Totals (Column B) like this:
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"
How can I populate Table1."date"? My UPDATE above doesn't work here because I can't use an aggregate function on a date. I was able to get the results I wanted using the following code in a separate query:
SELECT DISTINCT Table1."item"
, Table2."date"
FROM Table1 INNER JOIN Table2
ON Table1."item" = Table2."item"
ORDER BY Table1."item"
But how do I use the results of this query to SET the value of the column? I'm using SQL Server 2008.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您无法按照 @Lamak 的建议重新进行插入,那么您可以通过以下方式执行
UPDATE
:If you can't do the insert all over again, as @Lamak suggested, then you could perform an
UPDATE
this way:对于 SQL Server,您可以使用单个
INSERT
语句:For SQL Server you coul've use a single
INSERT
statement:最简单的方法是使用简单的 CTAS(创建表作为选择):
The easiest way is to use a simple CTAS (create table as select):
您可以使用 @Lamak 的回答视图,而不是创建表。一个>。这样,您就不必在每次
Table2
更新时更新新行集。Instead of creating a table, you could create a view, using a select statement like in @Lamak's answer. That way you wouldn't have to update the new row set each time the
Table2
updates.