【问题标题】:How to calculate the percentage of an aggregated column of a grouped resultset in SQL Server如何计算 SQL Server 中分组结果集的聚合列的百分比
【发布时间】:2013-10-22 23:26:19
【问题描述】:

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

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

    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%

等等。 (显然还有一些其他的值和百分比)

【问题讨论】:

标签: sql sql-server


【解决方案1】:

使用 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

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

【讨论】:

  • 感谢您的回答,但 (select count(T) from cte) 和 (select sum(amount) from cte) 不会为我的所有行提供相同的总值吗?跨度>
  • 虽然总数需要与商店和日期相关,这就是为什么我一直在努力解决我的 CTE(它为所有行返回相同的总数,我需要一年的总数,month,store 和所有类型,以便计算百分比。在 CTE 的情况下,它给我所有行的相同总数)
  • 老兄!现在我感到很尴尬,这么简单的解决方案。谢谢一百万!
猜你喜欢
  • 2021-03-16
  • 2014-12-24
  • 1970-01-01
  • 2021-03-18
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多