我如何使用 Join 而不是子查询来进行后续查询?

How i can use Join instead of sub-queries for following query?

您好, 正如许多 post 在这里和那里看到的那样,子查询比连接慢...

但我找不到使用任何连接方法进行以下查询的方法。所以,我使用了子查询。

任何人都可以告诉我如何在以下情况下正确使用连接:

表 1:

customerID, Name
1, abc
2, xyz
3, qwe
4, zxc
5, asd
and so on

表 2:

customerID, Month, OrderNumbers
1, jan, 5
1, feb, 6
2, jan, 8
3, feb, 5
4, mar, 3
and so on..

我需要这样报告:

customer id, name, jan order, feb order, mar order
1, abc, 5, 6, 0
2. xyz, 8, 0, 0
3. qwe, 0, 5, 0
and so on

我正在使用这个查询:

select table1.customerID,
       table1.Name,
       (select table2.Month as jan
         where table2.Month = jan),
       (select table2.Month as feb
         where table2.Month = feb),
       (select table2.Month as mar
         where table2.Month = mar)
  from table1 

但这并不能正常工作...

那么,我该如何实现呢?

这是我在msql中多次使用的解决方案...

select customerID,Name,sum(jan) as jan,sum(feb) as feb from(
select table1.customerID,Name,(case when Month = 'jan' then OrderNumbers else 0 end) as jan, select table1.customerID,Name,(case when Month = 'feb' then OrderNumbers else 0 end) as febfrom table1
left join table2 on table2.customerID = table1.customerID
) as src group by customerID,Name

基本上你使用 select 案例来只用销售额或 0 填充月份,这给你类似

1,abc,5,0,0
1,abc,0,3,0
2,ddd,0,0,5

然后您只需对结果进行分组并对月份求和。

您的查询本质上需要从长到宽的整形或数据透视转换,这可以通过条件聚合来完成:

SELECT 
    table1.customerID,
    table1.`name`,      

    SUM(CASE WHEN table2.`Month` = 'jan' THEN table2.`OrderNumbers` END) As 'jan order',
    SUM(CASE WHEN table2.`Month` = 'feb' THEN table2.`OrderNumbers` END) As 'feb order',
    SUM(CASE WHEN table2.`Month` = 'mar' THEN table2.`OrderNumbers` END) As 'mar order',
    SUM(CASE WHEN table2.`Month` = 'apr' THEN table2.`OrderNumbers` END) As 'arp order',
    SUM(CASE WHEN table2.`Month` = 'may' THEN table2.`OrderNumbers` END) As 'may order',
    SUM(CASE WHEN table2.`Month` = 'jun' THEN table2.`OrderNumbers` END) As 'jun order',
    SUM(CASE WHEN table2.`Month` = 'jul' THEN table2.`OrderNumbers` END) As 'jul order',
    SUM(CASE WHEN table2.`Month` = 'aug' THEN table2.`OrderNumbers` END) As 'aug order',   
    SUM(CASE WHEN table2.`Month` = 'sep' THEN table2.`OrderNumbers` END) As 'sep order',
    SUM(CASE WHEN table2.`Month` = 'oct' THEN table2.`OrderNumbers` END) As 'oct order',
    SUM(CASE WHEN table2.`Month` = 'nov' THEN table2.`OrderNumbers` END) As 'nov order',
    SUM(CASE WHEN table2.`Month` = 'dec' THEN table2.`OrderNumbers` END) As 'dec order'

FROM
    table1
LEFT OUTER JOIN 
    tabl2 ON table1.customerID = table2.customerID
GROUP BY 
    table1.customerID,
    table1.`name`