MySQL:获取满足条件特定增量的项目计数

时间:2014-12-08 04:43:00

标签: 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(QTY)结尾的特定数量的水果数(即计数记录数),以便我的结果集为:

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

如何实现这一目标?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

select * from (select QTY,count(FRUIT) as Count,group_concat(FRUIT) as Fruit_Name from table group by QTY )t Order By QTY

答案 2 :(得分: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)