MySQL计数时加入表格&分组

时间:2014-01-03 16:38:12

标签: mysql sql

我想加入2个表:

source_table
 ----------------------------------
| source_id    label               |
|----------------------------------|
| 1            Contact Form        |
| 2            E-Mail              |
| 3            Inbound Call        |
| 4            Referral            |
 ----------------------------------

related_table
 ---------------------------------------
| id           created_at       source  |
|---------------------------------------|
| 1            2013-12-26       2       |
| 2            2013-12-26       2       |
| 3            2013-12-26       4       |
| 4            2013-12-25       1       |
| 5            2013-12-18       2       |
| 6            2013-12-16       4       |
| 7            2013-11-30       2       |
 ---------------------------------------

所以它看起来像这样:

 ---------------------------------------
| created_at   source           amount  |
|---------------------------------------|
| 2013-12-26   E-Mail           2       |
| 2013-12-26   Referral         1       |
| 2013-12-25   Contact Form     1       |
| 2013-12-18   E-Mail           1       |
| 2013-12-16   Referral         1       |
 ---------------------------------------

我想计算范围内每个日期按来源分组的related_table中每个来源的出现次数。

但我不确定如何编写查询。

这是我到目前为止所拥有的:

SELECT DISTINCT
  source_table.source_id,
  source_table.label AS source, 
  related_table.created_at,
  COUNT(*) AS amount

FROM source_table
  INNER JOIN related_table
    ON related_table.source=source_table.source_id AND
    related_table.created_at>='2013-12-01' AND 
    related_table.created_at<='2013-12-31'

GROUP BY `source` 
ORDER BY `created_at` ASC

我对SQL不是很了解,所以上面的查询可能与我需要的内容相差甚远。我所知道的是它没有按预期工作。

2 个答案:

答案 0 :(得分:0)

SELECT 
  created_at
  ,label as source
  ,COUNT(*) AS amount
FROM source_table
INNER JOIN related_table
ON source_table.source_id = related_table.source 
GROUP BY label, created_at
ORDER BY created_at DESC

答案 1 :(得分:0)

我的实施:

select created_at, s.label, amount
from 
(
    select count(r.Source) as amount, r.source, r.created_at
    from  related_table r
    group by r.source, r.created_at) a  inner join source_table s
   on a.source = s.source_id
where created_at between '2013-12-01' and '2013-12-31'
order by amount desc, created_at desc

http://sqlfiddle.com/#!2/841bd/2
根据你的例子调整了演示......