简体   繁体   中英

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. Example 1 would populate confirmed. PO 2 would fail the criteria since line 2 has no date.

Do I need to use a cursor to do this? Running 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM