如何在SQL中减去IN子句的内部?

时间:2017-02-14 19:42:25

标签: sql sql-server tsql

我继承了一个ASP应用程序,我正在转向PHP代码库。

我正在努力解决的一个问题如下

select *
from (
    select TERM_REPORTING,
        LEVEL_GROUPING_DESC,
        New_primary_college_Desc,
        ID_count
    from Enrollment
    ) a
pivot(sum(ID_count) for TERM_REPORTING in (
    [" & 201609 - 400 & "], 
    [" & 201609 - 300 & "],
    [" & 201609 - 200 & "],
    [" & 201609 - 100 & "],
    [" & 201609 & "]
    )
) as total_credit

我不确定他们是如何使用这个& 201609 - 400&在IN语句中进行数学运算的语法。如何在纯粹使用Microsoft SQL的IN语句中获得相同的结果,过去5个术语的列表。

我不仅仅想要岁月。这不是这个问题的答案。我想知道如何在IN语句中进行这种减法。

1 个答案:

答案 0 :(得分:2)

看起来他们在哪里构建一些动态SQL

最终结果如下所示

select *
from (
    select TERM_REPORTING,
        LEVEL_GROUPING_DESC,
        New_primary_college_Desc,
        ID_count
    from Enrollment
    ) a
pivot(sum(ID_count) for TERM_REPORTING in (
    [201209], 
    [201309],
    [201409],
    [201509],
    [201609]
    )
) as total_credit
  

以动态SQL编辑

Declare @Base int = 21609
Declare @SQL varchar(max)='
select *
from (
    select TERM_REPORTING,
        LEVEL_GROUPING_DESC,
        New_primary_college_Desc,
        ID_count
    from Enrollment
    ) a
pivot(sum(ID_count) for TERM_REPORTING in (
    [' + cast(@Base - 400 as varchar(25)) +'], 
    [' + cast(@Base - 300 as varchar(25)) +'],
    [' + cast(@Base - 200 as varchar(25)) +'],
    [' + cast(@Base  - 100 as varchar(25)) +'],
    [' + cast(@Base as varchar(25)) +']
    )
) as total_credit
'
Exec(@SQL)