簡體   English   中英

Sql:列中行值的總和

[英]Sql:Sum of row values in columns

我有一個包含三列的表:

Guid | event | timestamp
1236| page-view | 1234
1236 | product-view | 1235
1236 | page-view | 1237
2025 | add-to-cart
2025 | purchase

我想編寫一個不使用 case 語句的查詢來顯示列中的事件及其出現的總和。 我不想為此使用案例,因為事件不斷增加,現在大約有 200 個。

我正在尋找的 Output 是這樣的:

GUid | page-view | product-view | add-to-cart | purchase 

1236 | 2 | 1 | 0 | 0 
2025 | 0 | 0 | 1 | 1 
SELECT  a.Guid ,
    ifnull ((SELECT count (Guid ) from table_a where  event in('page-view') and Guid = a.Guid  GROUP by Guid  ),0) as [page-view]  ,
    ifnull((SELECT count (Guid ) from table_a where  event in('product-view') and Guid = a.Guid  GROUP by Guid  ),0) as [product-view]  ,
    ifnull((SELECT count (Guid ) from table_a where  event in('add-to-cart') and Guid = a.Guid  GROUP by Guid  ),0) as [add-to-cart]  ,         
    ifnull((SELECT count (Guid ) from table_a where  event in('purchase') and Guid = a.Guid  GROUP by Guid  ),0) as [purchase ]  
        FROM table_a a
        GROUP by Guid 

這是使用pivot的干凈解決方案。

select   Guid
        ,count([page-view])    as 'page-view'
        ,count([product-view]) as 'product-view'
        ,count([add-to-cart])  as 'add-to-cart'
        ,count([purchase])     as 'purchase'
from    (
        select  * 
               ,rank() over (order by Guid) as rnk
         from t 
         ) tmp
         pivot
         (
         max(rnk)
         for event in([page-view],[product-view],[add-to-cart],[purchase])
         ) pvt
group by Guid
指導 頁面預覽 產品視圖 添加到購物車 購買
1236 2 1 0 0
2025 0 0 1 1

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM