關於MySQL中查詢語句行轉列分組的問題

2021-08-20 10:08:45 字數 3439 閱讀 2609

今天遇到乙個sql的小問題,首先需要按天查詢資料,並且需要統計每乙個不同位置的資料條數,處理的時候卡住了,特此記錄一下:
#首先,第一次寫的sql如下,先按天分組,後按指定條件分組:

select

id,date_format(created_date, '%y-%m-%d') selectday,

count_location countlocation,

count(distinct user_id) counts

from counter

where id = 32

group

by date_format(created_date, '%y-%m-%d'),count_location

order

by date_format(created_date, '%y-%m-%d') desc

查詢結果如下圖所示:

此時需要將每天的資料合併到同一天的資料中去,實際需要的結果如下圖所示:

所以接下來實際需要處理得問題就是將多行一列轉為一行多列:

可以利用子查詢查詢出初始結果,再使用case…when…end進行合併,sql如下:

select

select1.selectday,

ifnull(case select1.countlocation when

'downpay'

then select1.counts end,0) as

'downpay',

ifnull(case select1.countlocation when

'villadetail'

then select1.counts end,0) as

'villadetail',

ifnull(case select1.countlocation when

'materials'

then select1.counts end,0) as

'materials',

ifnull(case select1.countlocation when

'vr'

then select1.counts end,0) as

'vr',

ifnull(case select1.countlocation when

'godownpay'

then select1.counts end,0) as

'godownpay'

from

(select

id,date_format(created_date, '%y-%m-%d') selectday,

count_location countlocation,

count(distinct user_id) counts

from counter

where id = 32

group

by date_format(created_date, '%y-%m-%d'),count_location

order

by date_format(created_date, '%y-%m-%d') desc

) select1

group

by select1.selectday,select1.countlocation

order

by select1.selectday desc

但是,這時候會發現,結果還是不對,丟失了一些資料,再分組的時候,只取到了第一條資料,如圖所示:

加上另乙個條件進行分組,結果如下:

可以看出每一行資料都有乙個統計好的資料,就相當於,這些資料還是分行統計了,沒有合併到同一條,這時只需要加上乙個max()函式,取每一行的最大值即可,得到最終資料,sql如下:

select

select1.selectday,

max(ifnull(case select1.countlocation when

'downpay'

then select1.counts end,0)) as

'downpay',

max(ifnull(case select1.countlocation when

'villadetail'

then select1.counts end,0)) as

'villadetail',

max(ifnull(case select1.countlocation when

'materials'

then select1.counts end,0)) as

'materials',

max(ifnull(case select1.countlocation when

'vr'

then select1.counts end,0)) as

'vr',

max(ifnull(case select1.countlocation when

'godownpay'

then select1.counts end,0)) as

'godownpay'

from

(select

id,date_format(created_date, '%y-%m-%d') selectday,

count_location countlocation,

count(distinct user_id) counts

from

counter

where

id = 32

group

by date_format(created_date, '%y-%m-%d'),count_location

order

by date_format(created_date, '%y-%m-%d') desc

) select1

group

by select1.selectday

order

by select1.selectday desc

mysql 查詢行轉列 SQL語句實現行轉列查詢

表sales 查詢結果如下 1 建表 create table dbo sales id int identity 1,1 not null,year int null,jidu int null,jine int null,primary key clustered id asc with pad...

MySQL行轉列sql語句

create table test tb grade id int 10 notnull auto increment user name varchar 20 default null course varchar 20 default null score float default 0 pri...

mysql 動態行轉列 MySQL行轉列

比如乙個單子,多個收據單用逗號隔開,怎麼把這乙個單子所有收據單獨展示出來,行轉成列呢?方法一 這裡需要用到迴圈,首先建立乙個1 10的序列 select rownum rownum 1 as seq from select rownum 0 r,bills limit 0,10 其次依次運用 sub...