SQL nvarchar对sum运算符无效

时间:2016-11-13 14:18:11

标签: sql sql-server

我正在学习SQL,我的表格看起来像这样:

Id  Name   Payd  Note
1   John   5.00  R:8days;U:5$
2   Adam   5.00  R:8days;
3   John   10.00 R:8days;
4   John   10.00 R:8days;
5   Adam   15.00 R:30days;

我想做这样的事情:

  Id  Name Usage     5.00 10.00 15.00 Sum
    1   John  5      5.00 20.00 0     25.00
    2   Adam         5.00 0     15.00 20.00

如果有' U:5 $'我想查看该备注栏。在其中,然后为该客户添加5,其中包含' U:5 $'在注释列中,如果它没有,它不会添加任何内容。

我的代码如下所示:

;with cte as (
select Customer, PaydAmount, PaydAmount as Payd, Note as Usage
from t1
)
select 
    Customer, Usage
    ,[4.00] = ISNULL([4.00],0)
    ,[5.00] = ISNULL([5.00],0)
    ,[9.00] = ISNULL([9.00],0)
    ,[10.00] = ISNULL([10.00],0)
    ,[15.00] = ISNULL([15.00],0)
    ,[18.00] = ISNULL([18.00],0)
    ,[20.00] = ISNULL([20.00],0)
    ,[25.00] = ISNULL([25.00],0)
    ,[50.00] = ISNULL([50.00],0)
    ,[Payd] =ISNULL([4.00],0) + ISNULL([5.00],0) + ISNULL([9.00],0) + ISNULL([10.00],0) + ISNULL([15.00],0) + ISNULL([18.00],0) + ISNULL([20.00],0) + ISNULL([25.00],0) + ISNULL([50.00],0)
    from cte
    pivot (
        sum(PaydAmount) for Payd in ([4.00],[5.00],[9.00], [10.00], [15.00],[18.00], [20.00], [25.00], [50.00]))pvt
        order by Customer;

1 个答案:

答案 0 :(得分:2)

我不确定你的全部输出代表什么。但是使用条件聚合很容易获得前三列:

select row_number() over (order by (select null)) as id,
       name,
       max(case when note like '%U:5$' then 5 end) as usage,
       sum(case when payd = 5.00 then payd else 0 end) as [5.00],
       sum(case when payd = 10.00 then payd else 0 end) as [10.00],
       sum(case when payd = 15.00 then payd else 0 end) as [15.00],
       sum(payd) as total
from cte
group by name;

请注意,5,10和15的列假设payd中的值是十进制/数字类型。不建议对花车进行平等比较。