如何在SQL Server的where子句中使用新的输出

时间:2019-04-16 14:38:13

标签: sql sql-server

我正在执行此查询,我想添加where Age > 120,但是由于Age不是一列,所以我不能这样做。

你能帮我做到吗

select 
    a.NUM_CHASSIS, a.MARQUE, a.MODELE, a.FINITION,
    b.CMD_Vente_Incadea, b.Fact_Av_Incadea,
    a.DATE_FIN_OF, DATEDIFF(DAY, a.DATE_FIN_OF, GETDATE()) as Age   
from
    [DashboardPowerBi].[dbo].[BI_SVC_PROD_FIN_OF] as a
join 
    BI_SVC_INCADEA_STOCK_VN as b on a.NUM_CHASSIS = b.VIN
where 
    b.CMD_Vente_Incadea = 0 
    and b.Fact_Av_Incadea = 1

3 个答案:

答案 0 :(得分:3)

您可以将表达式添加到WHERE

SELECT PF.NUM_CHASSIS,
       PF.MARQUE,
       PF.MODELE,
       PF.FINITION,
       ISV.CMD_Vente_Incadea,
       ISV.Fact_Av_Incadea,
       PF.DATE_FIN_OF,
       DATEDIFF(DAY, PF.DATE_FIN_OF, GETDATE()) AS Age
FROM [DashboardPowerBi].[dbo].[BI_SVC_PROD_FIN_OF] AS PF
     JOIN BI_SVC_INCADEA_STOCK_VN AS ISV ON PF.NUM_CHASSIS = ISV.VIN
WHERE ISV.CMD_Vente_Incadea = 0
  AND ISV.Fact_Av_Incadea = 1
  AND DATEDIFF(DAY, PF.DATE_FIN_OF, GETDATE()) > 120;

或使用CTE /子查询:

WITH CTE AS(
    SELECT PF.NUM_CHASSIS,
           PF.MARQUE,
           PF.MODELE,
           PF.FINITION,
           ISV.CMD_Vente_Incadea,
           ISV.Fact_Av_Incadea,
           PF.DATE_FIN_OF,
           DATEDIFF(DAY, PF.DATE_FIN_OF, GETDATE()) AS Age
    FROM [DashboardPowerBi].[dbo].[BI_SVC_PROD_FIN_OF] AS PF
         JOIN BI_SVC_INCADEA_STOCK_VN AS ISV ON PF.NUM_CHASSIS = ISV.VIN
    WHERE ISV.CMD_Vente_Incadea = 0
      AND ISV.Fact_Av_Incadea = 1)
SELECT *
FROM CTE
WHERE CTE.Age > 120;

此外,请注意,我将您的别名更改为更相关的名称。使用代表对象名称的别名非常重要,因为这会使您的代码更具可读性。亚伦·伯特兰(Aaron Bertrand)在以下主题上写了一篇很棒的文章:Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3)

答案 1 :(得分:2)

cross apply在这种情况下很方便:

select bfo.NUM_CHASSIS, bfo.MARQUE, bfo.MODELE, bfo.FINITION,
       s.CMD_Vente_Incadea, s.Fact_Av_Incadea, bfo.DATE_FIN_OF,
       v.Age
from [DashboardPowerBi].[dbo].[BI_SVC_PROD_FIN_OF] bfo join
     BI_SVC_INCADEA_STOCK_VN s
     on bfo.NUM_CHASSIS = s.VIN cross apply
     (values (DATEDIFF(DAY, bfo.DATE_FIN_OF, GETDATE())) v(age)
where s.CMD_Vente_Incadea = 0 and s.Fact_Av_Incadea = 1 and
      v.age > 120;

请注意,我还更改了表别名,以便您的查询更易于遵循。

答案 2 :(得分:1)

  select a.NUM_CHASSIS,a.MARQUE,a.MODELE,a.FINITION,b.CMD_Vente_Incadea,b.Fact_Av_Incadea,a.DATE_FIN_OF ,DATEDIFF(DAY, a.DATE_FIN_OF, GETDATE()) as Age    from [DashboardPowerBi].[dbo].[BI_SVC_PROD_FIN_OF] as a
      join BI_SVC_INCADEA_STOCK_VN as b 
      on a.NUM_CHASSIS = b.VIN
      where b.CMD_Vente_Incadea = 0 and b.Fact_Av_Incadea =1 AND DATEDIFF(DAY, a.DATE_FIN_OF, GETDATE())>120