1

我有这张桌子:

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

我想通过一个查询(如果可能的话)获得这些详细信息:日期、借方 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

现在我遇到了麻烦,我不确定在哪里计算我需要的最后信息。

4

2 回答 2

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
于 2011-02-03T10:11:53.150 回答
0

我认为这可以帮助你。

SELECT      DebitDate,  SUM(DebitPrice*DebitQuantity) AS TotalSum, Count(DebitDate) as DebitDateCount
FROM        DebitsList where DebitTypeID = 1
GROUP BY    DebitDate
于 2011-02-03T10:19:16.900 回答