2016-08-30 70 views
1

假設我有一個表,因爲這:計數功能,通過查詢

TransActions(Id, ArticleId, DateBought, DateSold) 

,如果本次交易尚未售出DateSold可以爲空。對於每篇文章,我想列舉到目前爲止已經購買和銷售了多少交易。問題是這似乎是GROUP BY是不是我的情況下去。 我曾嘗試查詢:

SELECT `ArticleId`, count(!ISNULL(DateBought)) AS `Bought`, count(!ISNULL(DateSold)) AS `Sold` 
FROM `Transactions` AS `Transactions` 
GROUP BY `Transactions`.`ArticleId`; 

上述查詢的問題:

總是返回分組方式,該條款ArticleID行的數量。所以,即使我有22x DateSold = Null,它會返回22出售。以下是上述簡化問題的原始表格的屏幕截圖。條款ArticleID實際上是TradeSettingId:

enter image description here

回答

2

count返回傳遞給它表達式的值的數量是不爲空。在您的查詢中,每個值都是truefalse - 即不是null,因此所有行都被計數。爲了使長話短說,你只需要算日期自己,並留下繁重到count

SELECT `ArticleId`, 
     COUNT(`DateBought`) AS `Bought`, 
     COUNT(`DateSold`) AS `Sold` 
FROM  `Transactions` AS `Transactions` 
GROUP BY `Transactions`.`ArticleId`; 
0

你可以添加一個將在條件子句 -

WHERE DateBought IS NOT NULL或DateSold IS NOT NULL

+2

這並不能解決我的問題。 – kentor