如何计算SQL组中两个值的比率?

时间:2019-01-25 01:44:25

标签: sql sql-server

我的输入是: enter image description here

我想要的输出是: enter image description here

我无法弄清楚如何计算属于该特定项目的两行的现金/现金券数量比率。

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

示例

Select * 
      ,Ratio = convert(decimal(10,2),
               sum(case when [Payment_Mode]='Cash' then [Quantity]+0.0 end) over (Partition By [Item])
              /sum(case when [Payment_Mode]='Coupons' then [Quantity]  end) over (Partition By [Item])
              )
 From YourTable

返回

Item    Payment_Mode    Quantity    Ratio
Apples  Cash            20          2.00
Apples  Coupons         10          2.00
Grapes  Cash            45          15.00
Grapes  Coupons         3           15.00
Oranges Cash            300         20.00
Oranges Coupons         15          20.00

编辑-另一个选项是简单的加入和条件聚合

Select A.*
      ,B.Ratio
 From  YourTable A
 Join  (
        Select Item
              ,Ratio = sum(case when [Payment_Mode]='Cash'  then [Quantity]+0.0 end) /NullIF(sum(case when [Payment_Mode]='Coupons' then [Quantity] end),0)
         From  YourTable
         Group By Item
       ) B  on A.Item=B.Item

答案 1 :(得分:1)

使用max作为窗口函数。

select t.*,
       1.0*max(case when payment = 'Cash' then Payment end) over(partition by Item) / 
       max(case when payment = 'Coupon' then Payment end) over(partition by Item)
from tbl t

答案 2 :(得分:0)

完全格式化:

SELECT  ix.Item,
    ix.Seq,
    ix.Payment_Mode,
    ix.Quantity,
    ix.PrevQuantity,
    ix.NextQuantity,
    CASE WHEN ix.PrevQuantity = 0 THEN ix.Quantity/ix.NextQuantity ELSE ix.PrevQuantity/ix.Quantity END [Ratio]
FROM
(
    SELECT  ROW_NUMBER() OVER 
                (
                    PARTITION BY
                        i.Item
                    ORDER BY i.Item, i.Payment_Mode
                ) AS Seq,
            i.Item,
            i.Payment_Mode,
            i.Quantity,
            LEAD(Quantity, 1, 0) OVER (PARTITION BY i.Item ORDER BY i.Item ASC) AS NextQuantity,
            LAG(Quantity, 1, 0) OVER (PARTITION BY i.Item ORDER BY i.Item ASC) AS PrevQuantity
    FROM    #ITEMS i
) AS ix