如何在一个查询中包含每天多个COUNT个?

时间:2016-05-11 15:12:47

标签: mysql sql join count

尝试获取由列名称确定的2-3种条目的计数' adsource'过去8天的价值。到目前为止,我只能抓住一种类型并添加到结果中。数据库MySql。

我现在得到的结果(只有一种类型):

days_ago     monthday        type1
---------------------------------
1            2016-05-11      2
2            2016-05-10      34
3            2016-05-09      11
4            2016-05-08      1
5            2016-05-07      0
6            2016-05-06      16
7            2016-05-05      42
8            2016-05-04      76

结果I'之后 - > 2-3种类型(广告栏):

monthday        type1        type2
-----------------------------------------
2016-05-11      1            2
2016-05-10      6            0
2016-05-09      6            6
2016-05-08      1            65
2016-05-07      4            23
2016-05-06      1            12
2016-05-05      3            9
2016-05-04      6            11        

我不需要第一列days_ago,不知道如何将其从显示中删除。我需要能够显示结果:

adsource = 9 as type1
adsource = 12 as type2
adsource = 3 as type3

这是我使用的查询:

SELECT *
FROM (
SELECT DATEDIFF(NOW(), edate) AS days_ago, DATE(edate) AS monthday, 
COUNT(DISTINCT entries.email) AS type1
FROM entries
WHERE iplocation = 'mx' AND adsource = 9
GROUP BY DATE(edate)) AS temp
WHERE days_ago <= 8
GROUP BY monthday
ORDER BY monthday DESC

感谢您提供任何输入:)

3 个答案:

答案 0 :(得分:2)

尝试这样的事情......

SELECT *
FROM (
SELECT DATEDIFF(NOW(), edate) AS days_ago, DATE(edate) AS monthday, 
COUNT(DISTINCT (case when adsource=9 then entries.email end)) AS type1,
COUNT(DISTINCT (case when adsource=12 then entries.email end)) AS type2,
COUNT(DISTINCT (case when adsource=3 then entries.email end)) AS type3
FROM entries
WHERE iplocation = 'mx'
GROUP BY DATE(edate)) AS temp
WHERE days_ago <= 8
GROUP BY monthday
ORDER BY monthday DESC

答案 1 :(得分:1)

第二栏是什么?只需将其添加到查询中:

SELECT  DATE(edate) AS monthday, COUNT(DISTINCT entries.email) AS type1, COUNT(DISTINCT entries.type2) AS type2
FROM entries
WHERE iplocation = 'mx' AND adsource = 9 AND DATEDIFF(DATE(edate), now())     BETWEEN 0 and 7
GROUP BY DATE(edate)) AS temp

答案 2 :(得分:1)

我不确定您使用的是哪个数据库,但这应该可以在任何数据库中使用。

SELECT A.monthday, A.type1, B.type2 FROM
  (SELECT DATE(edate) as monthday, COUNT(type1) AS type1
    FROM entries 
    WHERE iplocation = 'mx' AND adsource = 9 AND DATEDIFF(DATE(edate), now()) BETWEEN 0 AND 7
    GROUP BY DATE(edate)) AS A
  (SELECT DATE(edate) as monthday, COUNT(type2) AS type2
    FROM entries
    WHERE iplocation = 'mx' AND adsource = 12 AND DATEDIFF(DATE(edate), now()) BETWEEN 0 AND 7
    GROUP BY DATE(edate)) AS B
WHERE A.monthday = B.monthday

这样您就可以使用多种不同的条件进行计数。