[英]Set Count Values from one table to Another
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 .......+2000 更多客户
Table " Summary ":表“摘要”:
ID ![]() |
Customer![]() |
Count![]() |
DateInput![]() |
---|---|---|---|
1 ![]() |
John![]() |
2 ![]() |
2021-01-01 ![]() |
2 ![]() |
Mary![]() |
2 ![]() |
2021-01-01 ![]() |
.........+100 More Customers .........+100 更多客户
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?有没有一种方法可以使用上述查询来更新 John、mary 等的计数列,而无需执行多个单独的请求?
Given that your count values will change, you should consider creating a view instead of updating a table:鉴于您的计数值会发生变化,您应该考虑创建视图而不是更新表:
CREATE VIEW summary AS
SELECT ID, Customer, COALESCE(COUNT(CASE WHEN Date <= CURRENT_DATE() THEN 1 END), 0) AS cnt
FROM Customers
GROUP BY ID, Customer
If you really want to have a table and update it every time, you need such UPDATE
statement:如果你真的想要一个表并且每次都更新它,你需要这样的
UPDATE
语句:
WITH cte AS (
SELECT ID, Customer, COUNT(*) AS count
FROM Customers
WHERE Date <= CURRENT_DATE()
GROUP BY ID, Customer
)
UPDATE Summary
INNER JOIN cte ON Summary.ID = cte.ID AND Summary.Customer = cte.Customer
SET Summary.count = cte.count
Is this something you are looking for?这是您要找的东西吗?
UPDATE
Summary s
INNER JOIN Customers c ON s.Customer = c.Customer
SET
s.Count = (
SELECT
COUNT(*)
FROM
Customers c2
WHERE
c2.Customer = s.Customer
AND c2.Date <= CURRENT_DATE()
)
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:您可以按如下方式进行:
UPDATE Summary s
INNER JOIN (
SELECT Customer, count(1) as _count
FROM Customers
where Date <=CURRENT_DATE()
group by Customer
) as c on s.Customer = c.Customer
set s.Count = c._count ;
I have used inner join
to join a list of customers and their counts.我已经使用
inner join
来加入客户列表及其计数。 and the relation is Customer.关系是客户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.