使用 CASE 语句进行 MySQL 查询帮助

发布于 2024-08-28 14:54:54 字数 973 浏览 4 评论 0原文

我正在尝试根据“总部”或“母公司”位置将许多客户分组在一起。

这工作正常,除了一个我在开发系统时没有预见到的缺陷...对于没有“Parent”(独立业务)的客户,我将parent_id默认为0。因此,我的数据看起来像这是:

id  parent_id   customer  
1    0          CustName#1 
2    4          CustName#2 - Melbourne 
3    4          CustName#2 - Sydney 
4    0          CustName#2 (Head Office)

我想要做的是将我的结果分组在一起,以便我有一行 CustName#1 和一行 CustName#2 但我的问题是没有parent_id=0 的父记录,并且这些行在以下情况下被排除使用内连接。

我尝试过使用 case 语句,但这也不起作用(父母仍然被忽略)

任何帮助将不胜感激。 这是我的查询(我的案例基本上是尝试根据parent_id从客户表中获取business_name,除非parent_id = 0,然后仅使用job_summary表中列出的customer_name):

SELECT 
js.month_of_year,
(CASE js.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) as customer,
SUM(js.jobs), 
SUM(js.total_cost),
sum(js.total_sell)
FROM JOB_SUMMARY js INNER JOIN 
customer c on js.parent_id=c.id
group by 
js.month_of_year,
(CASE c.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) 
ORDER BY `customer` ASC

I am trying to group a number of customers together based on their "Head Office" or "Parent" location.

THis works ok except for a flaw which I didn't forsee when I was developing my system... For customers that did not have a "Parent" (standalone business) I defaulted the parent_id to 0. Therefore, my data would look like this:

id  parent_id   customer  
1    0          CustName#1 
2    4          CustName#2 - Melbourne 
3    4          CustName#2 - Sydney 
4    0          CustName#2 (Head Office)

What I want to do is Group my results together so that I have one row for CustName#1 and one row for CustName#2 BUT my problem is that there is no parent record for parent_id=0 and these rows are being excluded when using an inner join.

I've tried using a case statement but that is not working either (parents are still being ignored)

Any help would be greatly appreciated.
Here is my query (My CASE is basically trying to get the business_name from the customer table based on the parent_id EXCEPT when the parent_id = 0, THEN just use the customer_name that is listed in the job_summary table):

SELECT 
js.month_of_year,
(CASE js.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) as customer,
SUM(js.jobs), 
SUM(js.total_cost),
sum(js.total_sell)
FROM JOB_SUMMARY js INNER JOIN 
customer c on js.parent_id=c.id
group by 
js.month_of_year,
(CASE c.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) 
ORDER BY `customer` ASC

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深白境迁sunset 2024-09-04 14:54:54

尝试使用 LEFT OUTER JOIN 而不是 INNER JOIN

on js.parent_id=c.id 可能会过滤掉没有父项的行。

Try a LEFT OUTER JOIN instead of INNER JOIN.

on js.parent_id=c.id is presumably filtering out rows where there are no parents.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文