在SQLServer的视图创建脚本中使用变量

r7s23pms  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(730)

我现在在sql server中有一个中间视图和一个最终视图,如下所示:
中间视图:

SELECT
    ....
    ElapsedDays = DATEDIFF(d, ri.DateReceived, GETDATE()),
    .....
FROM 
    RegionalInventory AS ri

最终视图:

SELECT
    ....
    PenaltyBucket = COALESCE(CASE WHEN inv.ElapsedDays <= 30 THEN 'Not Late' END,
                             CASE WHEN inv.ElapsedDays > 30 THEN 'Late' END)
    ....
FROM 
    Inventory AS inv

我想知道是否有一种方法可以将两个视图合并为一个视图,但是我不知道如何声明一个变量来保存 ElapsedDays ,然后使用它设置 ElapsedDays 列进行逻辑测试,以创建 PenaltyBucket 列并用正确的值填充它。

u5rb5r59

u5rb5r591#

假设您真的只有一个表(称为 RegionalInventory ,这是一个方便横向连接的地方:

SELECT . . ., v.ElapsedDays,
       (CASE WHEN v.ElapsedDays <= 30 THEN 'Not Late'
             WHEN v.ElapsedDays > 30 THEN 'Late'
        END) as PenaltyBucket
FROM RegionalInventory ri CROSS APPLY
     (VALUES (DATEDIFF(day, ri.DateReceived, GETDATE()))
     ) v(ElapsedDays);

注:
没有必要使用 COALESCE() 有两个 CASE 表达。1 CASE 可以处理多种情况。
详细说明 day 使用时 DATEDIFF() . 这只是一个好习惯(想想:是吗 m 是几分钟还是几个月?)

w6lpcovy

w6lpcovy2#

你只需要在 SELECT 条款:

SELECT
    ...,
    DATEDIFF(d, ri.DateReceived, GETDATE()) AS ElapsedDays,
    CASE 
        WHEN DATEDIFF(d, ri.DateReceived, GETDATE()) <= 30 then 'Not Late'
        ELSE 'Late' 
    END AS PenaltyBucket 
    ...
FROM RegionalInventory as ri

或者,可以使用子查询:

SELECT
    t.*,
    CASE 
        WHEN ElapsedDays  <= 30 then 'Not Late'
        ELSE 'Late' 
    END AS PenaltyBucket 
FROM (
    SELECT
        ...,
        DATEDIFF(d, ri.DateReceived, GETDATE()) AS ElapsedDays,
        ...
    FROM RegionalInventory as ri
) t
5lwkijsr

5lwkijsr3#

您可以将内部视图定义为cte,然后再次引用它。
创建视图[架构名称]查看_name[(column_name[,…n])]为<select_statement>[;]<选择语句>::=
[使用<common\u table\u expression>[,…n]]
选择<select\u criteria>
下面是演示代码供您参考。

create view vw_test
as 
WITH cte_1 as
(
select 1 as a
)
SELECT t.testname
from (values (1,'test1'),(2,'test2')) as t(a,testname)
join cte_1 as c
on c.a = t.a

select * from vw_test

你能做的就是。示例代码供您参考。

CREATE VIEW outerView
AS
WITH cte_innerview
as
(
SELECT
    ....
    ElapsedDays = DATEDIFF(d, ri.DateReceived, GETDATE()),
    .....
FROM 
    RegionalInventory AS ri
)
SELECT
    ....
    PenaltyBucket = COALESCE(CASE WHEN inv.ElapsedDays <= 30 THEN 'Not Late' END,
                             CASE WHEN inv.ElapsedDays > 30 THEN 'Late' END)
    ....
FROM 
    Inventory AS inv
INNER JOIN cte_innerview as c
on c.InventoryId = inv.InventoryId

相关问题