日期:2014-05-16  浏览次数:21047 次

求教:每个分类各取10条数据,相同时间上的数据显示在一条记录上,这样的SELECT语句怎么写?
数据库MYSQL表如下: 
表名:stockdata
ID TIME STOCK_NAME DATA1 DATA2 DATA3 
1 9:30 银行 aaa bbb ccc 
2 9:31 银行 ddd eee fff
.. ...... ... .... .... ....  
11 9:30 证券 2aaa 2bbb 2ccc 
12 9:31 证券 2ddd 2eee 2fff
.. .... .... .... .... ....  
我想要的结果是:按STOCK_NAME这个字段个都取出最新的10条信息。每条记录包含在这个时间上的所有STOCK_NAME的三个数据都展示在一条记录上。请问怎么写。
  银行 证券  
TIME DATA1 DATA2 DATA3 DATA1 DATA2 DATA3  
9:31 ddd eee fff 2ddd 2eee 2fff  
9: 30 aaa bbb ccc 2aaa 2bbb 2ccc 
... ... ... ... ... ... ...  
查询出来的表就是按这样的以时间排序,一条记录上显示每个分类的相同的字段名(DATA1 ,DATA2,DATA3)的数据。


------解决方案--------------------
无环境 未测试:
SQL code
select id, stock_code, real_time, 
    sum(if(stock_code=991156, buycount, 0)) as buycount,
    sum(if(stock_code=991156, bigbuycount, 0)) as bigbuycount,
    sum(if(stock_code=991156, waitbuycount, 0)) as waitbuycount,
    sum(if(stock_code=881155, buycount, 0)) as buycount,
    sum(if(stock_code=881155, bigbuycount, 0)) as bigbuycount,
    sum(if(stock_code=881155, waitbuycount, 0)) as waitbuycount
from stock_data
group by real_time
order by real_time desc

------解决方案--------------------
select real_time, 
MAX(if(stock_code=991156, buycount, 0)) as buycount,
MAX(if(stock_code=991156, bigbuycount, 0)) as bigbuycount,
MAX(if(stock_code=991156, waitbuycount, 0)) as waitbuycount,
MAX(if(stock_code=881155, buycount, 0)) as buycount,
MAX(if(stock_code=881155, bigbuycount, 0)) as bigbuycount,
MAX(if(stock_code=881155, waitbuycount, 0)) as waitbuycount
from stock_data group by real_time order by stock_code desc