假设我有一张桌子:
TransActions(Id, ArticleId, DateBought, DateSold)
如果此交易尚未售出,则DateSold可能为null。对于每个ArticleId,我想列出到目前为止已经购买和销售了多少交易。问题是GROUP BY
似乎不是我的理由。 我尝试过的查询:
SELECT `ArticleId`, count(!ISNULL(DateBought)) AS `Bought`, count(!ISNULL(DateSold)) AS `Sold`
FROM `Transactions` AS `Transactions`
GROUP BY `Transactions`.`ArticleId`;
以上问题的问题:
它总是返回ArticleId的GROUPED行数。因此,即使我有22x DateSold = Null,它也会返回22作为已售出。以下是上述简化问题的原始表格的屏幕截图。 ArticleId实际上是TradeSettingId:
答案 0 :(得分:2)
count
返回传递给它的表达式的值非空。对于您的查询,每个值都是true
或false
- 即不是null
,因此所有行都会计算在内。总而言之,您只需要自己计算日期,并将繁重的工作留给count
:
SELECT `ArticleId`,
COUNT(`DateBought`) AS `Bought`,
COUNT(`DateSold`) AS `Sold`
FROM `Transactions` AS `Transactions`
GROUP BY `Transactions`.`ArticleId`;
答案 1 :(得分:0)
您可以添加带条件的WHERE子句 -
WHERE DateBought IS NOT NULL或DateSold IS NOT NULL