I am trying to count matching values from customer column on table ‘Customers’ and update their values on the Count Column in table ‘Summary’. I also want to Check if the Date is <= Todays Date.
Table "Customers":
ID | Customer | Date |
---|---|---|
1 | John | 2022-01-01 |
2 | John | 2022-01-01 |
3 | Mary | 2022-01-01 |
4 | Mary | 2022-01-01 |
…….+2000 More Customers
Table "Summary":
ID | Customer | Count | DateInput |
---|---|---|---|
1 | John | 2 | 2021-01-01 |
2 | Mary | 2 | 2021-01-01 |
………+100 More Customers
I can update one row at a time like this:
update Summary
set Count = (SELECT COUNT(*)
FROM Customers
WHERE Customer = "John" AND Date <=CURRENT_DATE())
WHERE Customer = "John";
Is there a way to use the above query to update the count column for John, mary, etc, etc without doing Multiple individual requests?
3
Answers
Given that your count values will change, you should consider creating a view instead of updating a table:
If you really want to have a table and update it every time, you need such
UPDATE
statement:Is this something you are looking for?
If you are going to test the query, please test it on a small dataset before applying it to the entire table since it may not achieve the results you are expecting.
You can do it as follows :
I have used
inner join
to join a list of customers and their counts.and the relation is Customer.