2013-10-15 52 views
1

百分比我有一个查询在那里我得到一个结果集的日期,商店及类型分组的交易总计。我卡住的地方是:我也想计算百分比,我只是在Excel中完成它,但由于错误的命名约定,每个商店的行数不一致,结果集相当大。如何计算一个分组结果集的集合列的SQL Server中

这里是我的查询,而无需百分比:

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 

这工作完全正常,现在我只需要确定每类事务的百分比的最佳途径。例如占总数的60%,价值22%的2013年

9月期间在指定的商店类型“信用”的你也许对我有什么建议吗?将不胜感激。

编辑:

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

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

等(很明显,其他几个值和百分比)

+0

你能尝试寻找任何这些的,看起来很相似:在SQL Server堆栈溢出百分比计(http://stackoverflow.com/questions/10134905/sql-percentage -count)然而,在SQL Server的另一百分比计(http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement/5846102#5846102) –

+0

我有一个看看其中的许多人(尝试了其中的一些解决方案)。我认为我的问题更多的是我的分组,并获得正确的(关系)总数来计算百分比。 –

回答

3

使用CTE提供你的过滤结果(NB:加入语法而不是加入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 

然后从这些结果,一个简单的百分比计算

+0

感谢您的答案,但不会(从cte中选择count(T))和(从cte中选择sum(amount))给我所有行的相同总值? –

+0

@HannoOpperman会,是 - 计算% – podiluska

+0

总需求,是关系到商店和日期,虽然,这就是为什么我一直在用我的CTE挣扎(它返回所有行的总一样,我需要总的年,月,存储和所有类型的,以计算百分比。在CTE的情况下,它给了我所有的行相同的总) –

相关问题