Mysql使用日期之间的连接

时间:2013-10-15 07:33:05

标签: mysql sql

我有一个表analytics_metrics。我试图从过去x天的visitorStatistics和pageviewsStatistics算起来。日期范围可以改变。

id  metrics             count   date
67  visitorsStatistics  15779   2013-10-10
69  pageviewsStatistics 282141  2013-10-10
90  visitorsStatistics  14588   2013-10-11
92  pageviewsStatistics 265042  2013-10-11
108 pageviewsStatistics 278523  2013-10-12
106 visitorsStatistics  15015   2013-10-12
122 visitorsStatistics  16474   2013-10-13
124 pageviewsStatistics 312752  2013-10-13
138 visitorsStatistics  16829   2013-10-14
140 pageviewsStatistics 320614  2013-10-14
85  pageviewsStatistics 67976   2013-10-15
83  visitorsStatistics  5452    2013-10-15

我希望获得这样的输出:

visitorsStatistics   pageviewsStatistics
15779                282141 
14588                265042 
15015                278523 
16474                312752 
16829                320614 
5452                 67976  

我已经尝试了超过4个小时的不同查询现在我似乎无法找到正确的方法: - (。

这是我到目前为止所得到的:

SET @fromDate = '2013-10-10'; 
set @tillDate = '2013-10-11';

SELECT 
  *
   /* ga_visits.count as visits,
    ga_pageviews.count as pageviews
*/
 FROM analytics_metrics as ga_visits
    LEFT JOIN analytics_metrics as ga_pageviews on (ga_pageviews.date BETWEEN @fromDate AND @tillDate AND ga_pageviews.metrics = 'pageviewsStatistics')
    WHERE ga_visits.date BETWEEN @fromDate AND @tillDate AND ga_visits.metrics = 'visitsStatistics'

如果我使用此查询一天它可以正常工作但不适用于日期范围。

希望有人可以提供帮助。

提前谢谢

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
  sum(if(metrics = 'visitorsStatistics', `count`, 0)) visitorsStatistics,
  sum(if(metrics = 'pageviewsStatistics', `count`, 0)) pageviewsStatistics
FROM analytics_metrics am
WHERE <WHATEVER YOU NEED>
GROUP BY `date`

小提琴here

答案 1 :(得分:1)

如果我说得对,你想在一个日期内组合成对的行,例如:

SELECT
  l.count AS visitorsStatistics,
  r.count AS pageviewsStatistics
FROM
  (SELECT * FROM analytics_metrics WHERE metrics='visitorsStatistics') AS l
  LEFT JOIN
  (SELECT * FROM analytics_metrics WHERE metrics='pageviewsStatistics') AS r
    ON l.date=r.date
WHERE
  l.date BETWEEN @fromDate AND @tillDate

- 请参阅此fiddle

答案 2 :(得分:0)

像这样检查。

SELECT if(metrics='visitorsStatistics',count) AS visitorsStatistics,if(metrics='pageviewsStatistics',count) AS pageviewsStatistics
    FROM metrics_table
    WHERE date BETWEEN '2013-10-10' AND '2013-10-15'
    GROUP BY date

答案 3 :(得分:0)

试试这个

SELECT 
  *
   /* ga_visits.count as visits,
    ga_pageviews.count as pageviews
*/
 FROM analytics_metrics as ga_visits
    LEFT JOIN analytics_metrics as ga_pageviews on (ga_pageviews.date BETWEEN @fromDate AND @tillDate AND ga_pageviews.metrics = 'pageviewsStatistics')
    WHERE ga_visits.date BETWEEN DATE_ADD(fromDate, INTERVAL 1 DAY) and DATE_SUB(tillDate, INTERVAL 1 DAY) AND ga_visits.metrics = 'visitsStatistics'