如何计算sql

时间:2017-01-24 15:46:08

标签: sql sql-server

我在同一张表中有两列,需要求和并获得差异,然后计算百分比?

SELECT sum([BillCount]) - sum([IssueCount]) as [Difference]
FROM Invoice
where [Year] = '2015'

在上面的查询中,我得到差异的结果为244234.现在我需要通过将差值除以实际的Billcount 260918来计算百分比。

示例数据:

SELECT sum(BillCount) as bills, sum(IssueCount) as issues
FROM Invoice
where [Year] = '2015'

结果:     票据:260918     问题:16684     差异:244234     除以实际票据的差额:244234/260918 = 0.93     百分比:0.93 * 100 = 93.60

我使用了从0到1的已更改除数。但是我得到了很多行的百分比结果,比如每个人的账单数。有没有什么方法可以像我们在计算器中计算的那样获得一行中的确切百分比? 感谢。

3 个答案:

答案 0 :(得分:1)

喜欢这个吗?

SELECT sum([BillCount]) - sum([IssueCount]) as [Difference],
    (sum(IssueCount) - sum(BillCount)) / nullif(sum(BillCount), 0) as ptcdiff
FROM Invoice
where [Year] = '2015'

你会注意到我改变了减法的顺序。这使它成为负面变化而不是积极变化。如果你需要一个绝对的。改变,你可以在结果周围抛出abs()。如果

有意义,你也可以将它烘焙成一个函数
declare 
    @pctOld float = 260918,
    @pctNew float = 16684  

select PctDiff = case when @PctNew is null or @PctOld is null then null
                       when @PctNew = null or @PctOld = null then null
                       when @PctNew = 0 and @PctOld = 0 then 0    
                       when @PctNew = 0 and @PctOld > 0 then -100.00
                       when @PctNew >= 0 and @PctOld < 0 then null
                       when @PctNew < 0 and @PctOld > 0 then null
                       when @PctOld = 0 then null
                       else ((@PctNew - @PctOld) / abs(@PctOld)) * 100.0
                  end

答案 1 :(得分:0)

将当前表达式除以SUM([BillCount])汇总值

像这样的东西

select (sum([BillCount]) - sum([IssueCount])) / NULLIF(sum([BillCount]),0) * 100
FROM Invoice
where [Year] = '2015'

答案 2 :(得分:0)

像这样的子查询

Select Difference/nullif(sum(BIllCount), 1) From (SELECT sum([BillCount]) - sum([IssueCount]) as [Difference],
FROM Invoice
where [Year] = '2015') Per