1

I have a query where I get a result set of transaction totals grouped by a date, a store and a type. Where I'm stuck is: I want to calculate the percentages as well, I would've simply done it in Excel, but due to bad naming conventions, my number of rows per store is inconsistent and my result set is pretty big.

Here is my query without the percentages:

    SELECT DATEPART(Year,datecreated) as [Year],
           DATEPART(Month,datecreated) as [Month],
           b.Name as [Store]
           Type as [Type],
           Count(Transaction) as [Total],
           SUM(Amount) as [Value],
       -- one or two other aggregate functions
   FROM MyTransactions a, MyStores b
   WHERE a.Status = 'Paid'
   AND a.ID = b.ID
   -- AND Date -- daterange
   GROUP BY  
   datepart(year,datecreated),datepart(month,datecreated),Type
   ORDER BY year desc,month desc,type desc, store desc

Which works perfectly fine, now I just need the best way to determine the percentage of transactions per type. e.g. 60% of the total and 22% of the value is of the type 'Credit' at the specified store during Month 9 of 2013.

Do you perhaps have any suggestions for me? Would be greatly appreciated.

EDIT:

The result I am looking for looks a bit like this:

2012 | 10 | Store1 | Credit | 100 | 50%
2012 | 10 | Store1 | Debit  | 100 | 50%
2012 | 10 | Store2 | Credit | 400 | 40%
2012 | 10 | Store2 | Debit  | 600 | 60%

etc. (obviously with a few other values and percentages)

4

1 回答 1

3

使用 CTE 提供过滤结果(注意:连接语法而不是加入 where 子句)...

;with cte as (
      select 
           datepart(yyyy,datecreated) dateyear,
           datepart(mm,datecreated) datemonth,
           b.name as store,
           type,
           [transaction] as t,
           amount 
from
     myTransactions a inner join mystores b
          on a.id = b.id
where a.status='paid'
 )
 select 
      dateyear,
      datemonth,
      [Store],
      [Type],
      Count(T) as [Total],
      SUM(Amount) as [Value],
      100.0*count(T) / 
           (Select count(T) from cte c1 where c1.store=cte.store and c1.dateyear = cte.dateyear and c1.datemonth=cte.datemonth),
      100.0*Sum(Amount) / 
           (Select sum(amount) from cte c1 where c1.store=cte.store and c1.dateyear = cte.dateyear and c1.datemonth=cte.datemonth)
 from cte
 group by
      dateyear, datemonth,Type, store

然后根据这些结果,进行简单的百分比计算

于 2013-10-15T08:57:02.260 回答