需要通过比较两个表来显示 Total Customer 的 MAX COUNT
Posted
技术标签:
【中文标题】需要通过比较两个表来显示 Total Customer 的 MAX COUNT【英文标题】:Need to show MAX COUNT of Total Customer by comparing two tables 【发布时间】:2021-10-27 23:36:54 【问题描述】:目前客户总数来自 mq_billing 表,但我们需要从 mq_billing 和 mq_paymentlist 表中搜索并显示最大计数。对于 Total Customer,这两个表的列名称相同 Customer_Nbr。
这是我的 SQL:
SELECT b.Entity_Name,
b.`Total Customer`,
b.`Invoice Amount`,
p.`Online Payment`,
p.`Cash Payment`,
p.`Total Payment`
FROM (
SELECT Entity_Name,
COUNT(Customer_Nbr) AS `Total Customer`,
SUM(Invoice_Amount) AS `Invoice Amount`
FROM mq_billing
GROUP BY Entity_Name
) b INNER JOIN (
SELECT Entity_Name,
SUM(CASE WHEN Payment_Mode = 'Online Payment' THEN Amount ELSE 0 END) AS `Online Payment`,
SUM(CASE WHEN Payment_Mode = 'Cash' THEN Amount ELSE 0 END) AS `Cash Payment`,
SUM(Amount) AS `Total Payment`
FROM mq_paymentlist
GROUP BY Entity_Name
) p ON b.Entity_Name = p.Entity_Name
ORDER BY b.Entity_Name;
【问题讨论】:
【参考方案1】:就像您在第一个子查询中选择 COUNT(Customer_Nbr)
一样,在第二个子查询中也选择它:
SELECT Entity_Name,
COUNT(Customer_Nbr) AS `Total Customer`,
SUM(CASE WHEN Payment_Mode = 'Online Payment' THEN Amount ELSE 0 END) AS `Online Payment`,
SUM(CASE WHEN Payment_Mode = 'Cash' THEN Amount ELSE 0 END) AS `Cash Payment`,
SUM(Amount) AS `Total Payment`
FROM mq_paymentlist
GROUP BY Entity_Name
在主查询中使用GREATEST()
选择最大值:
SELECT b.Entity_Name,
GREATEST(b.`Total Customer`, p.`Total Customer`) AS `Total Customer`
.........................
【讨论】:
错误代码:1054。“字段列表”中的未知列“b.Total Customer” 你能帮我解决另一个问题吗? ***.com/questions/68970325/… INNER JOIN 仅获取常见的 Entity_Name,但我还需要获取不常见的 Entity_Name。请问可以修改吗? @RaceTech 问题不在 cmets 部分提出。我的回答是关于您发布的问题。如果您有新要求,您可以发布一个新问题,说明您想要什么。 请查看新问题***.com/questions/68970325/…以上是关于需要通过比较两个表来显示 Total Customer 的 MAX COUNT的主要内容,如果未能解决你的问题,请参考以下文章