选择满足条件的所有值以及其他一些值

时间:2019-10-23 09:09:45

标签: sql-server select conditional-statements

我有一个带有字段的表:

| Accompanying measures (bool) | Category (String) | Instrument (String) |

由于应用程序的设计并不能真正取代这些设计,因此我将表Instrument更改为字段ValidUntil(日期类型),该字段的日期已过时或{{ 1}}是否仍然有效。
视图显示旧数据和新数据的混合。旧数据可能包含已弃用的NULL,而新数据则不会。
如果仅显示新的工具Instruments,则会中断该页面,因为选择的ValidUntil IS NULL无法显示,因为未从数据库中检索到它们。

Tl; dr
编辑:如何选择所有Accompanying measures和所有ValidUntil IS NULL为真的条目。

ValidUntil != NULL, but HasBeenSelectedAsAccompanyingMeasure

1 个答案:

答案 0 :(得分:1)

如果我理解您的问题,则必须使用UNION ALL / UNION组合两个不同条件的数据集。

--ValidUntil IS NULL
SELECT
    a.AccompanyingMeasureID, a.InstrumentID, a.TaskID,         
    a.HasBeenSelectedAsAccompanyingMeasure, a.CategoryID
    , i.Name AS InstrumentName,     ic.Name AS CategoryName
FROM wc_AccompanyingMeasures AS a 
INNER JOIN wc_Instruments AS i ON a.InstrumentID = i.ID 
INNER JOIN wc_InstrumentCategories AS ic ON i.CategoryID = ic.ID
WHERE (a.TaskID = @TaskID) 
AND (i.ValidUntil IS NULL) 
UNION ALL
--ValidUntil != NULL, but HasBeenSelectedAsAccompanyingMeasure is true
SELECT
    a.AccompanyingMeasureID, a.InstrumentID, a.TaskID,         
    a.HasBeenSelectedAsAccompanyingMeasure, a.CategoryID
    , i.Name AS InstrumentName,     ic.Name AS CategoryName
FROM wc_AccompanyingMeasures AS a 
INNER JOIN wc_Instruments AS i ON a.InstrumentID = i.ID 
INNER JOIN wc_InstrumentCategories AS ic ON i.CategoryID = ic.ID
WHERE (a.TaskID = @TaskID) 
AND (i.ValidUntil IS NOT NULL AND HasBeenSelectedAsAccompanyingMeasure='TRUE')