我正在尝试按项目对下面的示例表进行分组,价格增量为 0.25,数量总和。
| item_id | qoute | qty | --output table--> | item_id | qoute | qty | |---------|-------|-----| |---------|-------|-----| | 10 | 10.99 | 10 | | 10 | 10.00 | 20 | | 10 | 10.00 | 20 | | 10 | 10.75 | 10 | | 10 | 11.00 | 1 | | 10 | 11.00 | 1 | | 10 | 11.27 | 5 | | 10 | 11.25 | 10 | | 10 | 11.33 | 5 | | 10 | 11.50 | 10 | | 10 | 11.50 | 10 | * Notice how the two quotes of 11.27 and 11.33 are grouped together into 11.25 in the output table
我不知道是否可以用 SQL 来做到这一点。这最终将实现到 Doctrine2 DQL 中,但我应该能够轻松地将任何 SQL 移植到其中。
我真的很想用 SQL 来做到这一点。但如果不可能,我也许可以想出一种用算法来实现的方法。
最佳答案
这是一种方法,使用 SQL Server 中的语法:
select item_id, floor(quote * 4.0)/4.0 as roundquote, sum(qty) as qty
from t
group by item_id, floor(quote * 4.0)
order by 1, 2
这会将值乘以 4,截断为较小的整数,然后除以 4。这应四舍五入到最接近的 0.25 美元。
关于SQL GROUP BY 项目,价格递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178565/