如何查询子类别

时间:2017-08-03 09:46:38

标签: sql

TABLEA

name    |  date         |  con
------------------------------
tv      | 2017-07-01    |   1
tv      | 2017-07-02    |   1
tv      | 2017-07-03    |   1
tv      | 2017-07-03    |   2
mobil   | 2017-07-03    |   1
mobil   | 2017-07-04    |   1
tablet  | 2017-07-03    |   1
tablet  | 2017-07-03    |   2
tablet  | 2017-07-03    |   3

tableB的

name     |  date         |  was
------------------------------
tv       | 2017-07-01    |   15
mobil    | 2017-07-03    |   50
mobil    | 2017-07-04    |   15
tablet   | 2017-07-04    |   30

结果表A(没问题):

select  name,
Group_concat( cons) as conA
from(
select  name,
count(con) as cons
from tableA 
where 
date between '2017-07-01' and '2017-07-31'
GROUP BY con, name 
HAVING con>0) q
GROUP BY name; 

如何合并tableA& tableB? 左连接 - >我没试过? 子类别 - >我没试过? 我应该怎么做

期望的输出:

name   |  conA   |  wasB |
------- --------  -------- 
tv     |   3,1   |  15   |
mobil  |   4     |  65   |
tablet |   9,1,1 |  30   |

1 个答案:

答案 0 :(得分:0)

你应该在subselelect中使用count(*),而在

中使用sum
select q.name,
  Group_concat( q.cons) as conA, wasB
  from( 
    select name,
    count(*) as cons
    from tableA 
    where 
    date between '2017-07-01' and '2017-07-31'
    GROUP BY con, name 
    HAVING con>0) q
  left  JOIN (
    select name, sum(was)  wasB
    from tableB
    group by name
  ) b on q.name = b.name
  GROUP BY name