使用复杂查询选择表

时间:2014-07-25 11:20:33

标签: sql sql-server

enter image description here

我有2个表格,上面有字段。

我创建了以下查询

  SELECT DISTINCT H.HolidayId,H.HolidayDate,H.Description,CH.ClientId,
        case when CH.HolidayId is not null then 1 else 0 end as  IsHoliday
        FROM Holiday H LEFT JOIN ClientHolidays CH ON h.HolidayId = CH.HolidayId

enter image description here

但是我需要列出所有带有IsHoliday字段的假期,如果客户已添加为假期,则IsHoliday字段应为1,否则为0

使用ClientId查询时。它应该列出所有假期取决于clientId

我需要结果如下

enter image description here

在传递客户端ID时,我需要使用IsHoliday字段获得所有假期应为0或1

5 个答案:

答案 0 :(得分:2)

尝试以下查询,它将按照要求运行:)

SELECT h.HolidayId, HolidayDate,
CASE WHEN ClientID IS NULL THEN 0 ELSE 1 END AS IsHoliday
FROM HOLIDAY h
LEFT OUTER JOIN CLIENTHOLIDAYS ch ON ch.HolidayId = h.HolidayId
WHERE ClientId = 1 OR ClientID is null

答案 1 :(得分:0)

试试这个

SELECT DISTINCT H.HolidayId
    ,H.HolidayDate
    ,H.Description
    ,CH.ClientId
    ,CASE 
        WHEN CH.clientid IS NOT NULL
            THEN 1
        ELSE 0
        END AS IsHoliday
FROM Holiday H
LEFT JOIN ClientHolidays CH 
    ON h.HolidayId = CH.HolidayId

答案 2 :(得分:0)

试试这个:

SELECT  DISTINCT H.HolidayId,H.HolidayDate,H.Description,
        CASE WHEN CH.HolidayId IS NOT NULL THEN 1 ELSE 0 END AS IsHoliday
FROM    Holiday H LEFT JOIN 
        ClientHolidays CH ON h.HolidayId = CH.HolidayId
WHERE   CH.ClientId = 8 OR CH.ClientId IS NULL

答案 3 :(得分:0)

根据您的评论,我感觉您不想要所有假期。您只想为每个客户提供假期。如果是这种情况,您应该使用inner join。同样在这种情况下,isHoliday字段没有实际意义,因为您只获得客户实际采取假期的结果,因此假期将始终为1。

SELECT H.HolidayId,H.HolidayDate,H.Description,CH.ClientId,
       case when CH.HolidayId is not null then 1 else 0 end as  IsHoliday
FROM Holiday H inner JOIN 
ClientHolidays CH 
ON h.HolidayId = CH.HolidayId

答案 4 :(得分:0)

我在2天后使用了您的查询,但我发现了错误。然后我找到了解决方案。

以下是解决方案:

  SELECT h.HolidayId, HolidayDate,Description,CASE WHEN ClientID IS NULL THEN 0 WHEN ClientID != @ClientId THEN 0   ELSE 1 END AS IsHoliday
                        FROM HOLIDAY h LEFT OUTER JOIN CLIENTHOLIDAYS ch ON ch.HolidayId = h.HolidayId
                        WHERE ClientId = @ClientId OR ClientID is null or ClientID is not null

谢谢