简体   繁体   中英

SQL count how many times a item is sold from invoice table

We lost our count of how many times a product have been sold since day one and I need to update the item table's Sold column. There is only one item per line in the invoiceItem table.

Items table:

ItemNumber Char(8)
Sold       Integer

InvoiceItem table

InvoiceNumber  Integer  
ItemNumber Char(8)

I know how to get the count of one item, but I don't know how to go through all rows of the InvoiceItem table.

Update Items set Sold=
(Select Count(ItemNumber) from InvoiceItem
where ItemNumber = 'B12456')
Where ItemNumber = 'B12456';

Thanks for any help. KimHJ

You should be able to use a correlated subquery:

Update Items
    set Sold = (Select Count(*) from InvoiceItem ii where ii.ItemNumber = items.ItemNumber);

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