2017-06-23 183 views
0

我有這個表格,它顯示了每天從一個網站的200和404響應的數量。我需要重新排列它,因此每個日期每行顯示一次,並且狀態代碼成爲列。如何合併行並在SQL表中添加列?

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

回答

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

+0

每一天,所以你可能想按日期分組。 – Lostfields

+0

在'100'附近的語法錯誤? –

+0

@ ian-campbell查詢在演示中正常工作。你確定你有正確的表名等嗎? –

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' 
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; 
1

你真正需要的是所謂的「數據透視表」,通常它是通過使用「tablefunc」擴展https://www.postgresql.org/docs/current/static/tablefunc.html在Postgres的實現。

但在這個簡單的場景我會選擇用「手動旋轉」(喜歡這裏描述http://tapoueh.org/blog/2013/07/simple-case-for-pivoting-in-sql/)普通的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; 

公告,該款項()可以讓你有相同的多個記錄一天和同樣的狀態 - 但與您的表結構,這也將工作。