簡體   English   中英

Postgresql Group By 並為不同的值創建列

[英]Postgresql Group By and create columns for different values

我正在使用 Postgresql 並擁有這張桌子:

設備ID 日期 變量的名稱 脈沖
1 2021-03-29 高度 10
1 2021-03-29 速度 20
1 2021-03-30 高度 30
1 2021-03-30 溫度 40
2 2021-03-29 高度 50
2 2021-03-29 加速度 60
2 2021-03-29 距離 70

並且想查詢所以我按設備ID和日期分組,並按變量名創建列,所以預期的表是:

設備ID 日期 高度 速度 溫度 加速度 距離
1 2021-03-29 10 20 0 0 0
1 2021-03-30 30 0 40 0 0
2 2021-03-29 50 0 0 60 70

知道如何做到這一點嗎?

除了crosstab,還有一種更直接的方式是通過case operator

Select device_id, date, 
       Sum(Case When variable_name='height' Then pulses Else 0 End) As height,
       Sum(Case When variable_name='speed' Then pulses Else 0 End) As speed,
       Sum(Case When variable_name='temperature' Then pulses Else 0 End) As temperature,
       Sum(Case When variable_name='acceleration' Then pulses Else 0 End) As acceleration,
       Sum(Case When variable_name='distance' Then pulses Else 0 End) As distance
From Tbl
Group by device_id, date
Order by device_id, date

數據 Output:

device_id| date                 | height | speed | temperature | acceleration | distance
_________|______________________|________|_______|_____________|______________|_________
        1| 2021-03-29 00:00:00  |      10|     20|            0|             0|        0
        1| 2021-03-30 00:00:00  |      30|      0|           40|             0|        0
        2| 2021-03-29 00:00:00  |      50|      0|            0|            60|       70

暫無
暫無

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

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