2011-02-03 49 views
1

我有這個表:需要幫助設計一個合適的SQL查詢

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

我想用一個單一的查詢來獲取(如果可能的話),這些細節: 日期,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 

現在我有麻煩了,我不確定在哪裏把我需要的最後信息的計數。

+0

根據你想要的記錄必須分組? - 我的意思是你需要將記錄與Debitdate或DebitTypeID分組。你不能把他們兩個。 – 2011-02-03 10:16:24

回答

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 
+0

我已經試過了,但是第一個40577線給我2,第二個40577線給我1. – Shay 2011-02-03 10:13:32

0

我認爲這可以幫到你。

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