我有两张桌子 - Transaction
和TransactionEntry
。 Transaction
包含时间,TransactionEntry
包含已售出的商品。
一个Transaction
可以有多个TransactionEntry
我希望在2个日期内找到所有TransactionEntry.ItemID
&并且TransactionEntry.Quantity
。然后GROUP BY TransactionEntry.ItemID
。
此代码的工作原理并给出了预期的结果:
SELECT TransactionEntry.ItemID AS iID, SUM(TransactionEntry.Quantity)
FROM Transaction INNER JOIN TransactionEntry ON TransactionEntry.TransactionNumber = Transaction.TransactionNumber
WHERE Transaction.Time > '2015-07-27 00:00:00' AND Transaction.Time < '2015-08-02 23:59:59'
GROUP BY TransactionEntry.ItemID
ORDER BY SUM(TransactionEntry.Quantity) DESC
不知道如何创建一个表,所以我画了一个例子哈哈:
-----------------
| iID | SUM(T.. |
|-----------------|
| 30419 | 58 |
| 30420 | 50 |
| 55416 | 36 |
| ... | ... |
-----------------
我的问题是我想要第3列,它告诉我有多少交易构成了SUM。使用上面的例子,iID 30419卖了58次,但可能是58个不同的人或只有1个人。我想知道这一点。
以下SQL有效:
SELECT COUNT(TransactionEntry.ID)
FROM Transaction INNER JOIN TransactionEntry ON TransactionEntry.TransactionNumber = Transaction.TransactionNumber
WHERE Transaction.Time > '2015-07-27 00:00:00' AND Transaction.Time < '2015-08-02 23:59:59' AND TransactionEntry.ItemID = 10791
但我不确定如何合并2,如果这是有道理的。
我尝试了以下内容,但它超时了:
SELECT TransactionEntry.ItemID AS iID, SUM(TransactionEntry.Quantity), (SELECT COUNT(TransactionEntry.ID) FROM Transaction INNER JOIN TransactionEntry ON TransactionEntry.TransactionNumber = Transaction.TransactionNumber WHERE Transaction.Time > '2015-07-27 00:00:00' AND Transaction.Time < '2015-08-02 23:59:59' AND TransactionEntry.ItemID = iID) AS C
FROM Transaction INNER JOIN TransactionEntry ON TransactionEntry.TransactionNumber = Transaction.TransactionNumber
WHERE Transaction.Time > '2015-07-27 00:00:00' AND Transaction.Time < '2015-08-02 23:59:59'
GROUP BY TransactionEntry.ItemID
ORDER BY SUM(TransactionEntry.Quantity) DESC
我可以追求的是什么?
由于
答案 0 :(得分:1)
你能试试这个:
SELECT T.ItemID
, SUM(TE.Quantity)
, COUNT(TE.ID)
FROM Transaction T
INNER JOIN TransactionEntry TE ON TE.TransactionNumber = T.TransactionNumber
WHERE T.Time BETWEEN '2015-07-27 00:00:00' AND '2015-08-02 23:59:59'
GROUP BY T.ItemID