oracle - mysql如何將group by的行數(shù)據(jù)轉(zhuǎn)為列
問題描述
原始數(shù)據(jù)表如下
idnamemoneytime1mike62016-09-01 12:58:002mike102016-09-01 13:52:563leo102016-09-02 00:05:054mike62016-09-03 08:06:05希望轉(zhuǎn)制后的數(shù)據(jù)表如下
name2016-09-012016-09-022016-09-03mike1606leo0100以demo為例,可以說說這類問題的解決思路嗎?比如統(tǒng)計兩個月的數(shù)據(jù),那么就會有60行轉(zhuǎn)為60列,是否存在效率的瓶頸
問題解答
回答1:select sum(money) s,name,date_format(time,’%Y-%m-%d’) d from table group by name,d;然后根據(jù)這里轉(zhuǎn)換
回答2:非要用sql做的話,得寫存儲過程,然后創(chuàng)建個臨時表了。沒必要,把數(shù)據(jù)取出來后用服務(wù)端去做吧。效率高很多。
回答3:create table tt1(id int ,name VARCHAR(100),money FLOAT,time DATETIME)insert into tt1select 1,’mike’,6,’2016-09-01 12:58:00’ UNIONselect 2,’mike’,10,’2016-09-01 13:52:56’ UNIONselect 3,’leo’,10,’2016-09-02 00:05:05’ UNIONselect 4,’mike’,6,’2016-09-03 08:06:05’select name,sum(case when datediff(time,’2016-09-01’)=0 then money else 0 end) as ’2016-09-01’ ,sum(case when datediff(time,’2016-09-02’)=0 then money else 0 end) as ’2016-09-02’ ,sum(case when datediff(time,’2016-09-03’)=0 then money else 0 end) as ’2016-09-03’from tt1 GROUP BY name回答4:
@ch21st 給的就是典型的行轉(zhuǎn)列SQL寫法因為只需要表掃描一次,因此一般情況下不存在性能問題,除非是特別大的表。
這種寫法本身只是一個解決思路,如果列不固定的話,可以在應(yīng)用端通過php或java動態(tài)生成sql語句。
回答5:寫個生成腳本的sql就完了嘛
select 'select name,' union select concat('sum(case when datediff(time,’',date(time),'’)=0 then money else 0 end) as ’',date(time),'’,') a from tt1 group by a union select ' from tt1 group by name;';PS:union中間段最后一個逗號記得去掉回答6:
SELECT name, sum( if(date_format(time,’%Y-%m-%d’) = ’2016-09-01’, money, 0 ) ) AS ’2016-09-01’, sum( if(date_format(time,’%Y-%m-%d’) = ’2016-09-02’, money, 0 ) ) AS ’2016-09-02’, sum( if(date_format(time,’%Y-%m-%d’) = ’2016-09-03’, money, 0 ) ) AS ’2016-09-03’FROM money_table GROUP BY name;
相關(guān)文章:
1. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題2. PHP求助,求幫忙謝謝各位3. extra沒有加載出來4. mysql - php 如何網(wǎng)址中出現(xiàn)該頁標(biāo)題?5. javascript - 天貓首頁首屏數(shù)據(jù)來源6. javascript - 釘釘?shù)膃xcel, word文件預(yù)覽是直接用的微軟的office web app,不犯法嗎?7. 關(guān)于Mysql數(shù)據(jù)表行轉(zhuǎn)列8. django進行數(shù)據(jù)庫的查詢9. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?10. mysql - 為什么where條件中or加索引不起作用?
