如何计算SQL Server中分组结果集的聚合列的百分比

时间:2013-10-15 08:27:09

标签: sql sql-server

我有一个查询,我在其中获得按日期,商店和类型分组的交易总计的结果集。我被困的地方是:我也想计算百分比,我只是在Excel中完成它,但是由于命名约定不好,我每个商店的行数不一致,而且我的结果集非常大。 / p>

这是我没有百分比的查询:

    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

哪种方法非常好,现在我只需要最好的方法来确定每种类型的交易百分比。例如在2013年第9个月,指定商店中60%的总价值和22%的价值属于“信用”类型。

你对我有什么建议吗?非常感谢。

编辑:

我正在寻找的结果看起来有点像这样:

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

等。 (显然还有其他几个值和百分比)

1 个答案:

答案 0 :(得分: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

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