优秀SQL总结

一。

有如下表:

month name money

月份  人员 收入

 7   a 1000

 8  a 2000

 9  a 3000

要求用统计每个人 当月,上月,下月 收入,统计表如下:

月份 当月收入 上月收入 下月收入

2 2000 1000 3000


答案如下:

select 

(select month as '月份' from foutable where month = cast(date_format(now(),'%m') as SIGNED INTEGER)) '月份' ,


(select money '当月收入' from foutable where month = cast(date_format(now(),'%m') as SIGNED INTEGER))  '当月收入',


(select  money  from foutable where month = cast(date_format(now(),'%m') as SIGNED INTEGER)-1) '上月收入',


(select  money  from foutable where month = cast(date_format(now(),'%m') as SIGNED INTEGER)+1) '下月收入'


from Dual;


其中:Dual为虚拟表

二。

有表如下:

id country city

1 中国 北京

2 中国 上海

3 中国 深圳

4 日本 东京

5 日本 大阪

要求统计出下面的表:

country city

中国 北京,上海,深圳

日本 东京,大阪

答案如下:

select country ,GROUP_CONCAT(city separator ',') from test group by country;

猜你喜欢

转载自413316ym.iteye.com/blog/1665636