将多个SQL组合成一个Query

时间:2014-08-18 21:48:56

标签: sql sql-server

我在SQL Server 2005中有一个表,如下所示

DECLARE @Promotions TABLE (PromoCode VARCHAR(10),
                          DeptID VARCHAR(10),
                          VerticalID VARCHAR(10),
                          BuildingID VARCHAR(10)
                          primary key (DeptID, VerticalID, BuildingID)
                        )

INSERT INTO @Promotions VALUES ('P1_20%','101','501','1001')
INSERT INTO @Promotions VALUES ('P2_10%','101','501','All')
INSERT INTO @Promotions VALUES ('P3_5%','101','All','All')
INSERT INTO @Promotions VALUES ('P1_50%','111','606','1002')

我们需要根据DeptIDVerticalIDBuildingID列中的匹配值找出促销代码值。如果与这3列不匹配,请查找与DeptIDVerticalID的输入值和BuildingID的默认值(“全部”)匹配的匹配项。如果找不到结果,请考虑输入DeptIDVerticalID的默认值(“全部”)和BuildingID的默认值(“全部”)来查找匹配项。< / p>

以下查询工作正常 - 但它使用的是3部分方法。我们可以在单个SQL查询中实现这一点吗?

现有代码

DECLARE @PromoCode VARCHAR(10)

--Part 1
SELECT @PromoCode = PromoCode
FROM @Promotions
WHERE DeptID = @inputDeptID
  AND VerticalID = @inputVerticalID
  AND BuildingID = @inputBuildingID

--Part 2
IF @PromoCode IS NULL 
BEGIN
    SELECT @PromoCode = PromoCode
    FROM @Promotions
    WHERE DeptID = @inputDeptID
      AND VerticalID = @inputVerticalID
      AND BuildingID = 'All'
END

--Part 3
IF @PromoCode IS NULL 
BEGIN
    SELECT @PromoCode = PromoCode
    FROM @Promotions
    WHERE DeptID = @inputDeptID
      AND VerticalID = 'All'
      AND BuildingID = 'All'
END

--Result
SELECT @PromoCode

测试

DECLARE @inputDeptID VARCHAR(10)
DECLARE @inputVerticalID VARCHAR(10)
DECLARE @inputBuildingID VARCHAR(10)

SET @inputDeptID = '101'
SET @inputVerticalID = '501'
SET @inputBuildingID = '3003'

预期结果

P2_10%

1 个答案:

答案 0 :(得分:3)

您可以将其视为“优先级”。也就是说,查找所有可能的匹配项,然后使用order bytop选择最合适的匹配项:

set @PromoCode = (SELECT top 1 PromoCode
                  FROM @Promotions
                  WHERE DeptID = @inputDeptID AND
                        (VerticalID = @inputVerticalID OR VerticalId = 'ALL') AND
                        (BuildingID = @inputBuildingID OR BuildingID = 'ALL')
                  ORDER BY (case when Building = 'ALL' then 1 else 0 end),
                           (case when VerticalId = 'ALL' then 1 else 0 end)
                 );

还有其他方法可以表达这一点。如果性能存在问题并且列上有索引,那么使用union all order by方法可能比or子句中的where更好。