2014-12-08 112 views
0

的特定的增量項目計數考慮一個圖表,顯示各種水果的數量,它們在存在:MySQL的:獲取的是滿足條件

x---------x-----x  
| FRUIT | QTY |  
x---------x-----x 
| Apple | 4 | 
| Orange | 5 | 
| Mango | 4 | 
| Grape | 1 | 
| Plum | 2 | 
| Peach | 2 | 
x---------x-----x 

從這個表我要查詢水果的數量(即算一算具有特定數量從0開始,並在MAX(數量)結束的記錄數),所以我的結果集是:

x-----x-------x  
| QTY | COUNT |  
x-----x-------x 
| 0 | 0 | //0 fruits have 0 quantity 
| 1 | 1 | //1 fruit (Grape) has 1 quantity 
| 2 | 2 | //2 fruits (Plum, Peach) have 2 quantity 
| 3 | 0 | //0 fruits have 3 quantity 
| 4 | 2 | //2 fruits (Apple, Mango) have 4 quantity 
| 5 | 1 | //1 fruit (Orange) has 5 quantity 
x-----x-------x 

如何才能實現這一目標?

回答

0

你需要有一個順序表,這樣就可以做左加入,與該表,並給所有值

這裏是要做到這一點

世代號的方法之一是從這個帖子採取Generating a range of numbers in MySQL

select T1.SeqValue as Qty, isnull(T2.totalCount,0) as Count 
from 

(

SELECT 
    (TWO_1.SeqValue + TWO_2.SeqValue + TWO_4.SeqValue + TWO_8.SeqValue + TWO_16.SeqValue) SeqValue 
FROM 
    (SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue) TWO_1 
    CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 2 SeqValue) TWO_2 
    CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 4 SeqValue) TWO_4 
    CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 8 SeqValue) TWO_8 
    CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 16 SeqValue) TWO_16 

)T1 
left join 
(
    select count(*) as totalCount, qty 
    from table1 
group by qty 
)T2 
on T1.SeqValue = T2.qty 
0
select * from (select QTY,count(FRUIT) as Count,group_concat(FRUIT) as Fruit_Name from table group by QTY)t Order By QTY 
0

試試這個:

Declare @sSQL as Varchar(1000), @sTemp as Varchar(4) 
Declare @iLoop as int, @iMax as int 
Set @iMax = (Select max(Qty) from table1) 
Set @iLoop = 0 
Set @sSQL = '' 
While @iLoop <= @iMax 
Begin 
    Set @sTemp = (Select count(Qty) from table1 Where Qty = @iLoop Group By Qty) 
    If @sTemp is Null 
    Begin 
     Set @sTemp = 0 
    End 
    Set @sSQL = @sSQL + ' Select '+Cast(@iLoop as Varchar(4))+' as QTY,' + @sTemp+' as [COUNT] Union' 

    Set @iLoop = @iLoop + 1 
End 
Set @sSQL = Left(@sSQL, Len(@sSQL)-5) 
Exec(@sSQL)