我正在处理一个查询,该查询应该返回将由报表使用的数据集。假设我有一个表dbo.payments
,其数据如下所示:
-----------------------------------------------
Customer |Commission| Trade Date | Trade Type |
-----------------------------------------------
AMIRALIS | 20.00 | 22/01/2018 | SALE |
BRUSSASH | 30.00 | 22/01/2018 | PURCHASE |
AMIRALIS | 10.00 | 22/01/2018 | SALE |
AKBMOBIL | 50.00 | 22/01/2018 | PURCHASE |
AMIRALIS | 10.00 | 23/01/2018 | PURCHASE |
BRUSSASH | 10.00 | 23/01/2018 | PURCHASE |
BRUSSASH | 30.00 | 23/01/2018 | SALE |
BRUSSASH | 10.00 | 23/01/2018 | PURCHASE |
AMIRALIS | 60.00 | 24/01/2018 | PURCHASE |
BRUSSASH | 10.00 | 24/01/2018 | SALE |
方案1:我想编写一个查询,该查询将为我提供如下所示的结果。请注意,无论where子句如何,该百分比都始终与SUM(Commission)
的{{1}}相对。
240.00
是SQL新手,我能走的最远的是:。
-----------------------------------------------------
Customer |Total Commission| Trade Date |%Commission |
-----------------------------------------------------
AMIRALIS | 30.00 | 22/01/2018 | 0.125 |
BRUSSASH | 30.00 | 22/01/2018 | 0.125 |
AKBMOBIL | 50.00 | 22/01/2018 | 0.208 |
AMIRALIS | 10.00 | 23/01/2018 | 0.041 |
BRUSSASH | 50.00 | 23/01/2018 | 0.208 |
AMIRALIS | 60.00 | 24/01/2018 | 0.250 |
BRUSSASH | 10.00 | 24/01/2018 | 0.041 |
无论WHERE子句如何,我如何达到期望的结果: SELECT [TRADE DATE] AS DATE, CUSTOMER, SUM([COMMISSION]) AS TOTAL, ([COMMISSION] / (SELECT SUM([COMMISSION]) FROM DBO.PAYMENTS)) AS '%COMMISSION' FROM DBO.PAYMENTS GROUP BY [TRADE DATE], CUSTOMER, COMMISSION
将总数减少到WHERE [Trade Date] BETWEEN '21/01/2018' AND '24/01/2018'
答案 0 :(得分:2)
这可以使用SQL Server窗口函数来解决,例如:
SELECT DISTINCT
t.Customer,
SUM(t.Commission) OVER (PARTITION BY Customer, Trade_Date) Total_Commission,
t.Trade_Date,
SUM(t.Commission) OVER (PARTITION BY Customer, Trade_Date) / SUM(t.Commission) OVER() "%Commission"
FROM mytable t
ORDER BY 1, 3
Customer | Total_Commission | Trade_Date | %Commission :------- | :--------------- | :------------------ | :---------- AKBMOBIL | 50.00 | 22/01/2018 00:00:00 | 0.208333 AMIRALIS | 30.00 | 22/01/2018 00:00:00 | 0.125000 AMIRALIS | 10.00 | 23/01/2018 00:00:00 | 0.041666 AMIRALIS | 60.00 | 24/01/2018 00:00:00 | 0.250000 BRUSSASH | 30.00 | 22/01/2018 00:00:00 | 0.125000 BRUSSASH | 50.00 | 23/01/2018 00:00:00 | 0.208333 BRUSSASH | 10.00 | 24/01/2018 00:00:00 | 0.041666
PS:如果您需要按日期过滤输出,则只需在查询中添加WHERE
子句即可。这将过滤两个计算。
答案 1 :(得分:1)
您可以使用聚合查询。在这种情况下,您可以使用窗口函数来计算总佣金:
select Customer, TradeDate,
sum(Commission) as total_Commission,
sum(Commission) / sum(sum(Commission)) over () as percent_commission
from dbo.payments p
group by Customer, TradeDate