如何组合行并在SQL表中添加列?

时间:2017-06-23 05:24:21

标签: sql postgresql

我有这张表,显示每天网站的200和404回复数。我需要重新排列它,以便每行显示一次,状态代码成为列。

    status     |           date         |  num  
---------------+------------------------+-------
 200 OK        | 2016-07-31 00:00:00+00 | 45516
 404 NOT FOUND | 2016-07-31 00:00:00+00 |   329
 200 OK        | 2016-07-30 00:00:00+00 | 54676
 404 NOT FOUND | 2016-07-30 00:00:00+00 |   397
 200 OK        | 2016-07-29 00:00:00+00 | 54569
 404 NOT FOUND | 2016-07-29 00:00:00+00 |   382
 200 OK        | 2016-07-28 00:00:00+00 | 54404
 404 NOT FOUND | 2016-07-28 00:00:00+00 |   393

我最终想要找出的是每天404的回复百分比。像select (date.200 / date.404) from mytable

这样的东西

4 个答案:

答案 0 :(得分:1)

SELECT
    "date"::date,
    100.0 * SUM(CASE WHEN status LIKE '404%' THEN num ELSE 0 END) / SUM(num) AS percentage
FROM yourTable
GROUP BY "date"::date

<强>输出:

enter image description here

在这里演示:

Rextester

答案 1 :(得分:1)

你真正需要的是&#34; Pivot Table&#34;通常使用&#34; tablefunc&#34;在Postgres中实现它。分机https://www.postgresql.org/docs/current/static/tablefunc.html

但是在这个简单的场景中,我选择了简单的SQL方法&#34;手动转动&#34; (如此处所述http://tapoueh.org/blog/2013/07/simple-case-for-pivoting-in-sql/):

select
  date,
  sum(case when left(status, 3) = '200' then num end) as status200,
  sum(case when left(status, 3) = '404' then num end) as status404
from
  log
group by 1
order by 1 desc;

请注意,sum()允许您拥有同一天和相同状态的多个记录 - 但是使用您的表结构,这也可以。

答案 2 :(得分:0)

您可以使用联接

 select a.date, a.num num_200, b.num num_404, a.num num_200/b.num num_404 rate
 from my_table a
 left join my_table b on a.date = b.date  and b.status= '404 NOT FOUND'
 where a.status= '200 OK'

答案 3 :(得分:0)

尝试此查询 -

;WITH PivotData
AS (
    SELECT [Date], -- grouping element
        [Status], -- spreading element
        Number -- aggregating element
    FROM StatusEntries
    )
SELECT [Date]
    ,[200 OK]
    ,[404 NOT FOUND]
FROM PivotData
Pivot(Sum(Number) FOR [Status] IN (
            [200 OK]
            ,[404 NOT FOUND]
            )) AS P;