如何对一行进行分组和计数?
为了简化,我有树表:products
、products-vs-orders
、orders
products
字段:'ProductID ', 'Name', 'isGratis', ...products-vs-orders
字段:'ProductID'、'OrderID'orders
字段:'OrderID'、'Title ',...
实际上,我有一个这样的查询:
SELECT orders.OrderID, orders.Title, COUNT(`products`.`isGratis`) AS "Quantity", `products`.`isGratis`
FROM `orders`, `products-vs-orders`, `products`
WHERE `orders`.`OrderID` = `products-vs-orders`.`OrderID` AND `products-vs-orders`.`ProductID` = `products`.`ProductID`
GROUP BY `products`.`PackID`, `products`.`isGratis`
此查询有效并返回结果:
OrderID, Title, Quantity, isGratis
1 My Order 20 0
1 My Order 3 1
2 An other 8 0
2 An other 1 1
如何将产品“免费”和“付费”的计数检索到单独的列中?
OrderID, Title, Qt Paid, Qt Gratis
1 My Order 20 3
2 An other 8 1
To simplify, I have tree tables: products
, products-vs-orders
, orders
products
fields : 'ProductID', 'Name', 'isGratis', ...products-vs-orders
fields : 'ProductID', 'OrderID'orders
fields : 'OrderID', 'Title', ...
Actually, I have a query like this:
SELECT orders.OrderID, orders.Title, COUNT(`products`.`isGratis`) AS "Quantity", `products`.`isGratis`
FROM `orders`, `products-vs-orders`, `products`
WHERE `orders`.`OrderID` = `products-vs-orders`.`OrderID` AND `products-vs-orders`.`ProductID` = `products`.`ProductID`
GROUP BY `products`.`PackID`, `products`.`isGratis`
This query works and return this surch of result:
OrderID, Title, Quantity, isGratis
1 My Order 20 0
1 My Order 3 1
2 An other 8 0
2 An other 1 1
How can I retrieve the count of products 'gratis' and 'paid' in to separate cols ?
OrderID, Title, Qt Paid, Qt Gratis
1 My Order 20 3
2 An other 8 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
SUM(products.isGratis)
取决于数据库在内部将布尔值表示为单个数字位的事实,因此 false = 0 且 true = 1。ALL中的情况可能并非如此数据库实现。因此,对布尔字段进行 SUM 可能会导致依赖于实现的行为。
在求和之前将布尔值转换为实际的 0 和 1 值应该更合适:
SUM(products.isGratis)
depends on the fact that a boolean value is internally represented by the database as a single numeric bit, so false = 0 and true = 1.This may not be the case in ALL DB implementations. Therefore,
SUM
over a boolean field may cause implementation-dependent behavior.Converting the boolean into actual 0 and 1 values before summing should be more proper: