MySQL:获取满足特定条件增量的项目数
考虑一张显示各种水果及其数量的表格:MySQL:获取满足特定条件增量的项目数,mysql,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开始到MaxQuaty结束的特定数量的
x---------x-----x
| FRUIT | QTY |
x---------x-----x
| Apple | 4 |
| Orange | 5 |
| Mango | 4 |
| Grape | 1 |
| Plum | 2 |
| Peach | 2 |
x---------x-----x
从这个表中,我想查询水果的数量,即计算从0开始到MaxQuaty结束的特定数量的记录的数量,这样我的结果集将是:
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
如何实现这一点?您需要有一个序列表,以便可以与该表进行左连接并给出所有值 这里有一种方法可以做到这一点 数字的生成取自此帖子 试试这个:
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)
select * from (select QTY,count(FRUIT) as Count,group_concat(FRUIT) as Fruit_Name from table group by QTY )t Order By QTY
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)