我试图仅将每个客户的余额相加一次。通常情况下,我会使用SUM DISTINCT表达式,但是,一列会将其抛弃而行不再是"区别"。
例如:
Customer Number - Customer Name - Exception Type - Balance
CIF13443 - Paul - 1 - 125
CIF13452 - Ryan - 2 - 85
CIF13443 - Paul - 3 - 125
CIF13765 - Linda - 1 - 90
在这种情况下,如果我使用SUM DISTINCT,Paul的余额将被归结两次,因为他有一个不同的异常类型,实际上我只希望SSRS对每个客户求和一次。一种方法是使平衡"平衡"只有DISTINCT客户编号。可能通过分组客户编号?这可能在SSRS上吗?我宁愿不要触摸SQL数据集。
谢谢!
赞赏任何意见。
答案 0 :(得分:-1)
你可以使用union来复制重复的行:
查询1(使用联盟):
;WITH testdata(CustomerNumber,CustomerName,ExceptionType,Balance)AS(
SELECT 'CIF13443','Paul','1',125 UNION all
SELECT 'CIF13452','Ryan ','2',85 UNION all
SELECT 'CIF13443','Paul','3',125 UNION all
SELECT 'CIF13765','Linda','1',90
)
SELECT CustomerNumber,CustomerName,Balance FROM testdata UNION SELECT NULL,NULL,NULL WHERE 1!=1
/*
SELECT CustomerNumber,CustomerName,SUM(t.Balance) AS total_balance
FROM (
SELECT CustomerNumber,CustomerName,Balance FROM testdata UNION SELECT NULL,NULL,NULL
) AS t WHERE CustomerNumber IS NOT null
GROUP BY CustomerNumber,CustomerName
*/
CustomerNumber CustomerName Balance -------------- ------------ ----------- CIF13443 Paul 125 CIF13452 Ryan 85 CIF13765 Linda 90
使用Windows函数为重复行选择一行:
;WITH testdata(CustomerNumber,CustomerName,ExceptionType,Balance)AS(
SELECT 'CIF13443','Paul','1',125 UNION all
SELECT 'CIF13452','Ryan ','2',85 UNION all
SELECT 'CIF13443','Paul','3',125 UNION all
SELECT 'CIF13765','Linda','1',90
)
SELECT CustomerNumber,CustomerName,SUM(t.Balance) AS total_balance
FROM (
SELECT CustomerNumber,CustomerName,Balance,ROW_NUMBER()OVER(PARTITION BY CustomerNumber,CustomerName,Balance ORDER BY testdata.ExceptionType) seq FROM testdata
) AS t WHERE t.seq=1
GROUP BY CustomerNumber,CustomerName