根据其他列过滤列

时间:2015-07-30 21:47:47

标签: sql postgresql

我有一个表clicks,其中包含以下字段:

  • date
  • page_id
  • clicks

其数据如下:

date           page_id     clicks
2015-01-01        1          20
2015-01-02        2          10
2015-01-02        2          5
2015-01-01        4          10
2015-01-02        5          5

还有另一个包含页面元信息的表pages。有些页面是用英文写的,有些是用法文写的。英语的ID为1,2,3,法语的ID为2,3,4

我正在尝试创建一个数据集,将它们分成如下列:

date         french_page_clicks    english_page_clicks
2015-01-01         10                   20
2015-01-02         5                    15   

我发现的最接近的问题是:https://dba.stackexchange.com/questions/45532/create-multiple-columns-from-a-single-column-filtering-criteria使用COUNT(IF(revision = 'pending', 1, NULL)) as pending,他们可以在表格中插入1。但我需要插入实际的点击总和。

我得到的最远(不起作用)是:

SELECT
    date,
    SUM (clicks) AS english_page_clicks IF page_id in (1, 2, 3),
    SUM (clicks) AS french_page_clicks IF page_id in (4, 5, 6)
FROM
    clicks
GROUP BY date
ORDER BY date ASC

甚至更好,能够将页面表引用到SUM()中,如:

SELECT
    date,
    SUM (clicks) AS english_page_clicks IF pages.lang = 'english',
    SUM (clicks) AS french_page_clicks IF pages.lang = 'french'
FROM
    clicks
INNER JOIN pages ON clicks.page_id = pages.id
GROUP BY date
ORDER BY date ASC

如何过滤列以创建上面的摘要表?

1 个答案:

答案 0 :(得分:3)

您需要将表达式移动到聚合函数中。试试这个:

SELECT
    date,
    SUM(case when lang = 'English' then clicks else 0 end) AS english_page_clicks,
    SUM(case when lang = 'French'  then clicks else 0 end) AS french_page_clicks
FROM
    clicks
INNER JOIN pages ON clicks.page_id = pages.id
GROUP BY date
ORDER BY date ASC

Sample SQL Fiddle