在同一表的总和值中查找百分比

时间:2018-10-25 04:40:17

标签: sql sql-server

我在SQL表中有一个零售交易列表。该表包含有关客户编号,产品编号,交易类型,交易日期和金额的详细信息。

最终,我需要生成一条记录,其中包含客户编号,产品编号,交易类型,交易金额之和和%。该百分比表示该客户/产品组合的所有交易中具有给定交易类型的比例。

例如,我的表中的数据如下:


╔══════════╦═════════╦═════════╦════════════╦═══════════╗
║ Customer ║ Product ║ TxnType ║  TxnDate   ║ TxnAmount ║
╠══════════╬═════════╬═════════╬════════════╬═══════════╣
║ Smith    ║    1234 ║ Cash    ║ 01/01/2018 ║        10 ║
║ Smith    ║    1234 ║ Credit  ║ 02/01/2018 ║        20 ║
║ Smith    ║    1234 ║ Cash    ║ 03/01/2018 ║        10 ║
║ Smith    ║    1234 ║ Cash    ║ 04/01/2018 ║        20 ║
║ Smith    ║    3456 ║ Cash    ║ 01/01/2018 ║        10 ║
║ Smith    ║    3456 ║ Credit  ║ 02/01/2018 ║        20 ║
║ Smith    ║    3456 ║ Cash    ║ 03/01/2018 ║        10 ║
║ Jones    ║    3456 ║ Credit  ║ 01/01/2018 ║        10 ║
║ Jones    ║    3456 ║ Cash    ║ 02/01/2018 ║        10 ║
║ Jones    ║    3456 ║ Credit  ║ 01/01/2018 ║        20 ║
║ Jones    ║    1234 ║ Credit  ║ 01/01/2018 ║        10 ║
║ Jones    ║    1234 ║ Credit  ║ 02/01/2018 ║        20 ║
║ Jones    ║    1234 ║ Credit  ║ 03/01/2018 ║        20 ║
║ Jones    ║    1234 ║ Credit  ║ 04/01/2018 ║        40 ║
╚══════════╩═════════╩═════════╩════════════╩═══════════╝

我需要这样的结果:


╔══════════╦═════════╦═════════╦══════════════╦════════════╗
║ Customer ║ Product ║ TxnType ║ SumTxnAmount ║ %ofTxnType ║
╠══════════╬═════════╬═════════╬══════════════╬════════════╣
║ Smith    ║    1234 ║ Cash    ║           40 ║ 66%        ║
║ Smith    ║    1234 ║ Credit  ║           20 ║ 33%        ║
║ Smith    ║    3456 ║ Cash    ║           20 ║ 50%        ║
║ Smith    ║    3456 ║ Credit  ║           20 ║ 50%        ║
║ Jones    ║    3456 ║ Cash    ║           10 ║ 25%        ║
║ Jones    ║    3456 ║ Credit  ║           30 ║ 75%        ║
║ Jones    ║    1234 ║ Credit  ║           90 ║ 100%       ║
╚══════════╩═════════╩═════════╩══════════════╩════════════╝

1 个答案:

答案 0 :(得分:1)

您可以在下面尝试

DEMO

select 
  customer,product,TxnType,
  sum(TxnAmount) as SumTxnAmount,cast((sum(TxnAmount)*100.00)/(select 
  sum(TxnAmount) from cte1 b where a.customer=b.customer and a.product=b.product) as decimal(16,2)) as '%ofTxnType'

来自cte1 a 按客户,产品,TxnType分组

输出:

customer    product TxnType  SumTxnAmount   %ofTxnType
Smith       1234    Cash      40              66.67
Smith       1234    Credit    20              33.33