SQL Server:使用一个带有2个条件的Select语句

时间:2018-10-12 07:13:13

标签: sql-server if-statement

我有以下SQL查询,并且只需要运行一次df['date'] = pd.to_datetime(df['date'], dayfirst=True) df = df.set_index('date') df['new'] = df['value'].sub(df['value'].shift(freq='12MS')) print (df) value output new date 2012-01-01 20 NaN NaN 2012-02-01 10 NaN NaN 2012-03-01 40 NaN NaN 2012-06-01 30 NaN NaN 2013-01-01 20 0.0 0.0 2013-02-01 30 20.0 20.0 2014-02-01 60 30.0 30.0 2014-03-01 50 NaN NaN 语句即可。

我可以知道我应该进行哪些更改吗?

编辑:需要更改以仅使用一个SELECT语句。

SELECT

  

如果@hideInactiveCompany = 1,则显示BU.IsActive = 1的输出

     

如果@hideInactiveCompany = 0,则显示不带BU.IsActive的输出   过滤器。

4 个答案:

答案 0 :(得分:3)

我们可以尝试编写以下WHERE子句:

WHERE
    (hideInactiveCompany = 1  AND BU.IsActive IS NOT NULL) OR
    (hideInactiveCompany IS NULL AND BU.IsActive IS NULL) OR
    (hideInactiveCompany <> 1)

注意:自从我回答后,OP改变了几次问题。最新的答案似乎是这样:

WHERE
    (hideInactiveCompany = 1 AND BU.IsActive = 1) OR
    hideInactiveCompany IS NULL OR hideInactiveCompany <> 1

答案 1 :(得分:1)

如果我确实正确理解了您的要求,则整个查询应该只有一个SELECT子句

DECLARE
    @lang varchar(2) ='en',
    @hideInactiveCompany integer = 0

SELECT    <all columns>
FROM      Config.BusinessUnit BU
LEFT JOIN Config.Organization CO on BU.OrganizationId = CO.OrganizationId
LEFT JOIN Config.ParentBusinessUnit PBU on BU.ParentBusinessUnitId = PBU.ParentBusinessUnitId 
WHERE     (@hideInactiveCompany = 1 AND BU.IsActive = 1)
OR        (@hideInactiveCompany <> 1)
ORDER BY   CASE WHEN @lang = 'cn' THEN BU.Lang END,
           CASE WHEN @lang = 'en' THEN BU.Lang END DESC, 
           EntityName

WHERE上的说明 基本上只有两个条件:-

  • 条件1:@hideInactiveCompany = 1 AND BU.IsActive = 1
  • 条件2:@hideInactiveCompany <> 1

条件1与您指定的条件相同。当变量@hideInactiveCompany为1时,IsActive必须为1

条件2是变量@hideInactiveCompany不等于1

答案 2 :(得分:0)

您无法在SQL中执行这样的“有条件地构建我的选择”。您需要编写两次完整的选择查询,每个if的分支都要编写一次。

(SQL通常不是“可组合的”语言,您无法随意组合所需的元素。)

您也许可以使用case和其他表达式在单个查询中重建,或者将查询的公共部分放入临时表(或表值变量)中,然后仅将最后一部分进行两次。

答案 3 :(得分:0)

使用IF ELSE条件:

ALTER PROCEDURE [Config].[usp_ListBusinessUnit] 
@lang VARCHAR(2) = NULL,
@hideInactiveCompany INTEGER
AS
BEGIN


IF @hideInactiveCompany=1
    SELECT <all columns>
    FROM Config.BusinessUnit BU
    LEFT JOIN Config.Organization CO ON BU.OrganizationId = CO.OrganizationId
    LEFT JOIN Config.ParentBusinessUnit PBU ON BU.ParentBusinessUnitId = 
PBU.ParentBusinessUnitId 
    WHERE BU.IsActive IS NOT NULL
    ORDER BY 
        CASE WHEN @lang = 'cn' THEN BU.Lang END,
        CASE WHEN @lang = 'en' THEN BU.Lang END DESC, 
        EntityName

ELSE

   SELECT <all columns>
    FROM Config.BusinessUnit BU
    LEFT JOIN Config.Organization CO ON BU.OrganizationId = CO.OrganizationId
    LEFT JOIN Config.ParentBusinessUnit PBU ON BU.ParentBusinessUnitId = 
PBU.ParentBusinessUnitId 
    WHERE BU.IsActive IS NULL
    ORDER BY 
    CASE WHEN @lang = 'cn' THEN BU.Lang END,
    CASE WHEN @lang = 'en' THEN BU.Lang END DESC, 
    EntityName

END