我有以下查询,其中将两个表的计数相除,并显示其他列值。
两个表都通过月/年连接。
select
(a.count_one / b.count_two) as final_count, a.orders,
a.Months, b.Sum
from
(
select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders
from first_table
GROUP BY Months)
) a
INNER JOIN
(
select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
from second_table
GROUP BY Months)
) b
ON a.Months = b.Months
输出:
**Month and Year** **Final_Count**
January 2016 126
February 2016 123
March 2016 45
.... ....
... ....
... ....
What is required?
存在第三个表,其键在first_Table和second_table中。我需要根据第三个表放置一个WHERE子句,即WHERE thirdtable.name ='Any name'
因此,无论出现与thirdtable.name相关的ID的什么地方,这些结果都应显示,但我无法实现。
我尝试了什么?
我尝试了第三次INNER加入AS:
INNER JOIN third_table ON a.shid= third_table.id WHERE thirdtable.name='Any name'
但是,在这种情况下,不会显示任何结果。
有什么建议吗?
答案 0 :(得分:2)
子查询不会选择id
列,因此没有a.shid
要比较。而且,由于子查询是按月分组的,因此您无法在其中选择id
列。
您需要与子查询中的第三个表联接。
select
(a.count_one / b.count_two) as final_count, a.orders,
a.Months, b.Sum
from
(
select count(*) as count_one, DATE_FORMAT(`date`, "%M %Y") AS `Months`, orders
from first_table
JOIN third_table ON first_table.shid = third_table.id
WHERE third_table.name = 'Any name'
GROUP BY Months)
) a
INNER JOIN
(
select count(*) as count_two, DATE_FORMAT(`date`, "%M %Y") AS `Months`, sum(a) AS Sum
from second_table
JOIN third_table ON second_table.shid = third_table.id
WHERE third_table.name = 'Any name'
GROUP BY Months)
) b
ON a.Months = b.Months