1 行轉列 資料分組

2021-10-19 06:53:58 字數 2005 閱讀 8301

1)基礎資料

2)要求結果

3)**實現(其實你的資料不是這樣,我沒看到,應該有順序的,會更簡單)

with ctedata as (

select 1 as alarmtype,

'text1' as value

union all

select 1 as alarmtype,

'time1' as value

union all

select 1 as alarmtype,

'priority1' as value

union all

select 1 as alarmtype,

'endpoint1' as value

union all

select 2 as alarmtype,

'text2' as value

union all

select 2 as alarmtype,

'time2' as value

union all

select 2 as alarmtype,

'priority2' as value

union all

select 2 as alarmtype,

'endpoint2' as value

), ctedataex1 as (

/*1)新增資料行號*/

select x.*,

row_number

() over (order by (select 0

)) as fno

from ctedata x

), ctedataex2 as (

/*2)新增分組序號*/

select x.*,

row_number

() over (partition by x.alarmtype order by x.fno) as fgno

from ctedataex1 x

), ctepout as (

select x0.alarmtype as alarmtype,

x1.value as vendertext,

x2.value as lasttime,

x3.value as lastpriority,

x4.value as endpoint

from (

select x.alarmtype as alarmtype

from ctedataex2 x

group by x.alarmtype

) x0

select x.value

from ctedataex2 x

where x.alarmtype = x0.alarmtype and

x.fgno =

1) x1

select x.value

from ctedataex2 x

where x.alarmtype = x0.alarmtype and

x.fgno =

2) x2

select x.value

from ctedataex2 x

where x.alarmtype = x0.alarmtype and

x.fgno =

3) x3

select x.value

from ctedataex2 x

where x.alarmtype = x0.alarmtype and

x.fgno =

4) x4

)select *

from ctepout;

Oracle 分組 行轉列操作

1 原始資料 這個資料是下面sql 查出的資料 月份營業部 使用者型別 開戶獎調整 提成調整 薪酬支出調集成計 select a.trademonth trademonth,a.broker branch brokerbranch,decode b.user type,3 2 5 2 b.user ...

mysql單錶行轉列 mysql資料行轉列

在你找工作的經歷當中,是否有面試官問過你 資料庫行轉列如何實現?乙個典型的例子如下 有這樣乙個訂單表 om order 一條記錄包含訂單號 建立日期 訂單總金額 讓你統計不同年份對應各月份的銷售情況,要求每一年的銷售情況一行展示,效果如下 年份 一月 二月 三月 四月 五月 六月 七月 八月 九月 ...

資料行轉列例項

在系統開發中常常遇到進行資料的統計,並將資料行轉列的情景,例如表中的表示。但是在資料庫中呈現出來的資料往往是橫行的樣式。這就需要乙個轉換。轉換的方式有兩種方式。1.利用cross join去進行轉換。2.利用case when函式去轉換。資料庫查詢出的結果 張三170 李四90 王五180 需要資料...