在SQL中按多列分组

时间:2014-08-29 10:09:25

标签: mysql sql max distinct

我正在尝试通过site.Site_Name,为每个hive.hiveno和它的最大值(hiverdg.invdate)。运行下面的代码并不起作用,因为site.Site_Name没有被激活。如果我将site.Site_Name添加到Group By,则代码会运行,但是输出会显示重复的结果,每个站点都会显示一次.Site_Name

select site.Site_Name ,hive.hiveno, max(hiverdg.invdate)
from hiverdg 
        inner join hive
        on        hiveRdg.hive_Link = hive.hive_Link
        inner join Customer
        on        customer.Customer_Link = hive.Customer_Link
        inner join site
        on        site.Customer_Link = customer.Customer_Link        
where 
(hiverdg.xtype = 'N'
and customer.CustomerName = 'Cust1')
or
(hiverdg.xtype = 'A'
and customer.CustomerName = 'Cust1')
group by hive.hiveno

1 个答案:

答案 0 :(得分:1)

使用您的查询执行此操作的最简单方法是substring_index() / group_concat()诀窍:

select substring_index(group_concat(s.Site_Name order by rdg.invdate desc separator '|'
                                   ), '|', 1
                      ) as SiteName,
       h.hiveno, max(rdg.invdate)
from hiverdg rdg inner join
     hive h
     on rdg.hive_Link = h.hive_Link inner join
     Customer c
     on c.Customer_Link = h.Customer_Link inner join
     site s
     on s.Customer_Link = c.Customer_Link        
where rdg.xtype in ('N', 'A') and c.CustomerName = 'Cust1')
group by h.hiveno;

我还对您的查询进行了以下更改:

  • 引入了表别名,使查询更易于编写和阅读。
  • where更改为使用in,简化了逻辑。