求助mysql一条sql的写法

  • 一窍都不通
    表table_01 里面有两个字段 col1,col2,分别代表“店铺”、“购买时间”我想按店铺统计,本月购买的人当中,是2018和2017年老顾客的人数
    1. select b.count as 2018年人数, c.count as 2017年人数, a.col1 as 店铺 from table_01 aleft join (select count(1) as count, a.col1 as col1 from table_01 awhere exists (select 1 from table_01 b where a.id = b.id and date_format(a.col2,'%Y') = '2018') group by a.col1) bon a.col1 = b.col1left join (select count(1) as count, a.col1 as col1 from table_01 awhere exists (select 1 from table_01 b where a.id = b.id and date_format(a.col2,'%Y') = '2017') group by a.col1) con a.col1 = c.col1group by a.col1
    复制代码


    请问我这种写法可以吗?有没有更简洁的写法?
    我想要的效果是这样的11823978-EBBE-46b1-961F-8A3F4F74560E.png
  • p
    pepsing
    只是看老用户的话不要count,写一条exists子查询就好了 ynwa
  • 一窍都不通
    我要统计老顾客的人数啊,能不count吗 iOS fly ~
  • 一窍都不通
    iOS fly ~
  • b
    beiwei
    嗯,一窍都不通
  • l
    lumi
    先按年份和店铺分组,外包一层case就行。

    oracle有更优的方案,不过估计mysql不支持