如果案例中的> b,则处理的最佳方式

时间:2014-09-04 11:59:39

标签: sql sql-server-2008

是否有更好的方法来编写以下查询块?

CASE WHEN ugt.Type = 'Permanent' 
            AND ISNULL(ug.lastpromotion,u.CreatedOn) < DATEADD(MM,-6,GETDATE())
        THEN 
            (
                SELECT  cast(sum(pc.CommissionPerc / 100) as numeric(3,1))
                FROM Placements p
                INNER JOIN PlacementConsultants pc on pc.PlacementId = p.PlacementID AND pc.UserId = @userid
                INNER JOIN PlacementInvoices PlI on PlI.PlacementID = P.Placementid
                WHERE p.CreatedUserId = @userid
                AND pli.CreatedOn 
                        BETWEEN DATEADD(MM,-6,GETDATE())
                        AND GETDATE()
            )
    WHEN ugt.Type = 'Permanent' 
            AND ISNULL(ug.lastpromotion,u.CreatedOn) > DATEADD(MM,-6,GETDATE())
        THEN 
            (
                SELECT cast(sum(pc.CommissionPerc / 100) as numeric(3,1))
                FROM Placements p
                INNER JOIN PlacementConsultants pc on pc.PlacementId = p.PlacementID AND pc.UserId = @userid
                INNER JOIN PlacementInvoices PlI on PlI.PlacementID = P.Placementid
                WHERE pc.UserId = @userid
                AND pli.CreatedOn 
                        BETWEEN ISNULL(ug.lastpromotion,u.CreatedOn)
                        AND GETDATE()
            )
END

随着所有变化,pli.createdon需要使用最近一次促销或6个月前的最新促销活动。 (即计算自最近一次促销以来或6个月前的交易数量,无论最近的什么)?

或者我坚持为每种类型做2例?

2 个答案:

答案 0 :(得分:3)

只需增强case子句中的逻辑,就可以在一个where中执行此操作:

CASE WHEN ugt.Type = 'Permanent' 
     THEN (SELECT  cast(sum(pc.CommissionPerc / 100) as numeric(3,1))
           FROM Placements p INNER JOIN
                PlacementConsultants pc
                on pc.PlacementId = p.PlacementID AND pc.UserId = @userid INNER JOIN
                PlacementInvoices PlI
                on PlI.PlacementID = P.Placementid
           WHERE p.CreatedUserId = @userid AND
                 pli.CreatedOn <= GETDATE() AND
                 ((pli.CreatedOn >= DATEADD(MM, -6, GETDATE()) AND
                   ISNULL(ug.lastpromotion, u.CreatedOn) < DATEADD(MM, -6, GETDATE())
                  ) OR
                  (pli.ISNULL(ug.lastpromotion, u.CreatedOn) AND
                   ISNULL(ug.lastpromotion, u.CreatedOn) >= DATEADD(MM, -6, GETDATE())
                  )
                 )

如果SQL Server支持least()greatest()

,那会不会很好

答案 1 :(得分:0)

您可以将案例移至WHERE子句:

 AND pli.CreatedOn BETWEEN 
   IFF(ISNULL(ug.lastpromotion,u.CreatedOn) < DATEADD(MM,-6,GETDATE()),
         DATEADD(MM,-6,GETDATE()), 
         ISNULL(ug.lastpromotion,u.CreatedOn))
     AND GETDATE()