需要帮助设计正确的SQL查询

时间:2011-02-03 10:03:27

标签: sql join self

我有这张桌子:

DebitDate | DebitTypeID | DebitPrice | DebitQuantity
----------------------------------------------------
40577       1             50           3
40577       1             100          1
40577       2             75           2
40578       1             50           2
40578       2             150          2

我想获得一个查询(如果可能的话),这些细节: date,debit_id,total_sum_of_same_debit,how_many_debits_per_day

所以从上面的例子我会得到:

40577, 1, (50*3)+(100*1), 2 (because 40577 has 1 and 2 so total of 2 debits per this day)
40577, 2, (75*2), 2 (because 40577 has 1 and 2 so total of 2 debits per this day)
40578, 1, (50*2), 2 (because 40578 has 1 and 2 so total of 2 debits per this day)
40578, 2, (150*2), 2 (because 40578 has 1 and 2 so total of 2 debits per this day)

所以我有这个SQL查询:

SELECT      DebitDate, DebitTypeID, SUM(DebitPrice*DebitQuantity) AS TotalSum
FROM        DebitsList
GROUP BY    DebitDate, DebitTypeID, DebitPrice, DebitQuantity

现在我遇到了麻烦,我不知道在哪里可以计算我需要的最后信息。

2 个答案:

答案 0 :(得分:1)

您需要一个相关子查询来获取此新列。您还需要从GROUP BY子句删除 DebitPrice和DebitQuantity才能使用它。

SELECT   DebitDate,
         DebitTypeID,
         SUM(DebitPrice*DebitQuantity) AS TotalSum,
         (   select Count(distinct E.DebitTypeID)
             from DebitsList E
             where E.DebitDate=D.DebitDate) as CountDebits
FROM     DebitsList D
GROUP BY DebitDate, DebitTypeID

答案 1 :(得分:0)

我认为这可以帮助你。

SELECT      DebitDate,  SUM(DebitPrice*DebitQuantity) AS TotalSum, Count(DebitDate) as DebitDateCount
FROM        DebitsList where DebitTypeID = 1
GROUP BY    DebitDate