如何使用 exists 获取产品的完整列表?

How to use exists for a complete list of a product?

这是查询特定汽车是否具有 W1、W2、WA、WH 条件的查询。我如何修改我的查询,以便我可以获得所有汽车的列表,这些汽车是或否?

注意:在这里,我输入了 v.[carnumber] = 't8302' 但我需要一个完整的列表。

SELECT 
    CASE 
    WHEN EXISTS (
        SELECT co.[alias]    
        FROM  [MTI_TAXI].[vehicle] v
        LEFT JOIN [MTI_SYSTEM].[Conditions] co with (nolock) on v.DispatchSystemID = co.DispatchSystemID and (v.Conditions & co.conditionvalue > 0)
        WHERE co.[alias] in ('W1', 'W2', 'WA', 'WH') and v.[DispatchSystemID] = 6 and v.[CarNumber] = 't8302')    
    THEN cast ('Yes' as varchar)   
    ELSE cast ('No' as varchar)    
    END AS [WATS]

输出 - (WATS - 否)

但是,这是所有的车,但我对 WATS 条件表示同意,这是不正确的

enter image description here

使用 count(*) 断言通过添加 1 行找到了确切的行:

group by co.[alias]
having count(*) = 1

所以整个查询变成:

SELECT 
  CASE 
    WHEN EXISTS (
      SELECT co.[alias]
      FROM [MTI_TAXI].[vehicle] v
      LEFT JOIN [MTI_SYSTEM].[Conditions] co with (nolock)
        on v.DispatchSystemID = co.DispatchSystemID
        and (v.Conditions & co.conditionvalue > 0)
      WHERE co.[alias] in ('W1', 'W2', 'WA', 'WH')
      and v.[DispatchSystemID] = 6
      and v.[CarNumber] = 't8302'
      group by co.[alias]
      having count(*) = 1
    ) THEN cast ('Yes' as varchar)
    ELSE cast ('No' as varchar)
  end AS [WATS]

只需利用您提供的过滤器并将 EXISTS 移动到 OUTER APPLY 语句中即可:

SELECT 
    CASE 
        WHEN [find_wats].[Found] = 1 
            THEN 'Yes' 
        ELSE 'No' 
    END AS [WATS]
FROM 
    [MTI_TAXI].[vehicle] AS v
    OUTER APPLY (SELECT TOP (1) 
                    1 AS [Found]
                FROM 
                    [MTI_SYSTEM].[Conditions] AS co
                WHERE 
                    v.DispatchSystemID = co.DispatchSystemID 
                    AND 
                    (v.Conditions & co.conditionvalue > 0)
                    AND 
                    co.[alias] IN ('W1', 'W2', 'WA', 'WH') 
                    AND 
                    v.[DispatchSystemID] = 6) AS [find_wats];

使用此设置,然后您可以使用 [find_wats].[Found] = 1 确定您在 table [MTI_TAXI].[vehicle] 中的记录在 [MTI_TAXI].[Conditions] 中找到了匹配项(使用您提供的条件) 同时仍然在最终结果集中为最初在 table [MTI_TAXI].[vehicle].

中的每条记录保留一条记录