2011-02-03 50 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