不同日期的MySQL select语句

时间:2018-08-23 22:09:52

标签: mysql sql mysql-python

我有一个看起来像这样的表:

Month/Year id url     kw_count IMP CLK POS CTR 
Aug-2018    1 /url-1       222 444 122   4 1.2 
Sept-2018   2 /url-1       232 534 123   4 1.2 
Oct-2018    3 /url-1       224 445 124   4 1.2 
Nov-2018    4 /url-1       212 478 125   4 1.2 
Aug-2018    5 /url-2       233 434 126   4 1.2 
Sept-2018   6 /url-2       311 433 128   4 1.2 
Oct-2018    7 /url-2       299 423 123   4 1.2 
Nov-2018    8 /url-2       232 411 122   4 1.2 
Dec-2018    9 /url-2       231 465 156   5 1.1 

我想选择两个单独月份中的所有唯一网址及其指标。像这样的东西 2018年8月和9月…

/url-1, kw_count (aug), kw_count (sept), imp (aug), img (sept)...等,然后对url-2相同

我不会事先知道这些URL,而只是根据选择的日期进行选择。

我无法为自己的一生弄清楚该怎么做。我曾与group by和其他人一起玩,但是我很挣扎。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

这样的事情应该做你想要的:

SELECT url, 
    SUM(CASE WHEN `Month\Year` = 'Aug-2018' THEN kw_count END) AS `kw_count (Aug)`,
    SUM(CASE WHEN `Month\Year` = 'Sep-2018' THEN kw_count END) AS `kw_count (Sep)`,
    SUM(CASE WHEN `Month\Year` = 'Aug-2018' THEN IMP END) AS `IMP (Aug)`,
    SUM(CASE WHEN `Month\Year` = 'Sep-2018' THEN IMP END) AS `IMP (Sep)`,
    SUM(CASE WHEN `Month\Year` = 'Aug-2018' THEN CLK END) AS `CLK (Aug)`,
    SUM(CASE WHEN `Month\Year` = 'Sep-2018' THEN CLK END) AS `CLK (Sep)`,
    SUM(CASE WHEN `Month\Year` = 'Aug-2018' THEN POS END) AS `POS (Aug)`,
    SUM(CASE WHEN `Month\Year` = 'Sep-2018' THEN POS END) AS `POS (Sep)`,
    SUM(CASE WHEN `Month\Year` = 'Aug-2018' THEN CTR END) AS `CTR (Aug)`,
    SUM(CASE WHEN `Month\Year` = 'Sep-2018' THEN CTR END) AS `CTR (Sep)`
FROM metrics
GROUP BY url

输出(用于您的示例数据):

url     kw_count (Aug)  kw_count (Sep)  IMP (Aug)   IMP (Sep)   CLK (Aug)   CLK (Sep)   POS (Aug)   POS (Sep)   CTR (Aug)   CTR (Sep)
/url-1  222             232             444         534         122         123         4           4           1           1
/url-2  233             311             434         433         126         128         4           4           1           1

构建查询时,将需要适当地调整日期和列名。我已经创建了一个演示SQLFiddle进行演示(如果您发布文本而不是数据图像会更容易!)。

答案 1 :(得分:1)

您的表包含每月记录和url。现在选择一个月,选择另一个月,将两个数据集合并,就可以了。那应该是:

select *
from (select * from mytable where month_year = 'Aug-2018') m201808
full outer join (select * from mytable where month_year = 'Sept-2018') m201809 using (url);

由于MySQL不支持完整的外部联接,因此我们必须先获取URL,然后再获取两个月的外部联接:

select *
from (select distinct url from mytable where month_year in ('Aug-2018', 'Sept-2018')) urls
left join (select * from mytable where month_year = 'Aug-2018') m201808 using (url)
left join (select * from mytable where month_year = 'Sept-2018') m201809 using (url);

当然您应该将select *替换为列名:

select
  url,
  m201808.kw_count as kw_count_201808,
  m201809.kw_count as kw_count_201809,
  ...