[英]SQL Update based on aggregate record set
I have a table with purchase orders: 我有一张带有采购订单的表:
po_line table
+--------+---------+-----------+
| po_num | po_line | date |
+--------+---------+-----------+
| 1 | 1 | 9/22/2013 |
| 1 | 2 | 9/22/2013 |
| 1 | 3 | 9/22/2013 |
| 2 | 1 | 9/21/2013 |
| 2 | 2 | NULL |
+--------+---------+-----------+
po table
+--------+-----------+
| po_num | confirmed |
+--------+-----------+
| 1 | NULL |
| 2 | NULL |
+--------+-----------+
For a given po, example po_num 1, I am wanting to update a value in table 2 to 'confirmed' if all the records have a date in them for those lines. 对于给定的po,例如po_num 1,如果所有记录中都有针对这些行的日期,我想将表2中的值更新为“ confirmed”。 Example 1 would populate confirmed. 示例1将被确认。 PO 2 would fail the criteria since line 2 has no date. 由于第2行没有日期,因此PO 2将不符合条件。
Do I need to use a cursor to do this? 我需要使用游标执行此操作吗? Running sql 2008 r2. 运行sql 2008 r2。
UPDATE po SET confirmed = 'confirmed'
FROM po T
WHERE
NOT T.po_num IN
(
SELECT po_num FROM po_line
WHERE po_date IS NULL
)
Alternatively, if you want to make sure that are entries for each po
in the po_line
table before confirming, you can use: 或者,如果要在确认之前确保po_line
表中每个po
条目,则可以使用:
update po set confirmed = 'confirmed'
where po.po_num in (select po_num from
(select po_num, count(po_date) dated, count(*) total from po_line group by po_num) q
where dated=total)
as shown in http://sqlfiddle.com/#!6/b16988/8/0 如http://sqlfiddle.com/#!6/b16988/8/0中所示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.