我有以下数据结构:
P_ID EVSSMIN EVSSMAX TDMIN TDMAX WARD SYRINGE_ID COMBINE_WITH CUSTOM_CONCENTRATION
1003 0 20 125 250 2ZKG 1021038
44444444 5
1003 20 60 125 250 2ZKG 1021037
44444444 5
通常我使用以下查询结果。
[QUERY 1]
SELECT *
FROM [definities]
WHERE 160 BETWEEN [TDMIN] AND [TDMAX] AND [WARD] = '2ZKG' AND [P_ID]=` 1003;
表格中的最后一列可以包含一个高于0的值。高于它。
通常我想运行下面的查询而不是上面的查询。
[QUERY 2]
SELECT * FROM [definities]
WHERE 160 BETWEEN [TDMIN] AND [TDMAX]
AND CAST(160 as decimal) / [CUSTOM_CONCENTRATION]) BETWEEN EVSSMIN AND EVSMAX
AND [WARD] = '2ZKG' -- AND [P_ID]= 1003;
如您所见,查询通过将值除以[CUSTOM_CONCENTRATION])值来计算值160。比它在EVVSMIN和EVSSMAX之间匹配,并且值160在TDMIN和TDMAX之间匹配。通常,当[CUSTOM_CONCENTRATION]列包含值为higer然后为0时,查询2将正常工作。
问题是当[CUSTOM_CONCENTRATION]列不包含高于0的值时,查询无法返回记录。这意味着必须根据[CUSTOM_CONCENTRATION]值更改查询或其他内容。我可以在C#代码中解决这个问题,但简洁的方法是能够将此作为一个查询,根据值返回我的确切记录,而不是我需要迭代的多个记录并使用if语句检查它。
答案 0 :(得分:1)
假设您想要[CUSTOM_CONCENTRATION]
值为零或更低时的第一个查询,否则需要第二个查询,您可以使用UNION ALL
对两个查询都有另一个限制:
SELECT * FROM [definities]
WHERE 160 BETWEEN [TDMIN] AND [TDMAX] AND [WARD] = '2ZKG' AND [P_ID]=` 1003
AND [CUSTOM_CONCENTRATION] <= 0
UNION ALL
SELECT * FROM [definities]
WHERE 160 BETWEEN [TDMIN] AND [TDMAX]
AND CAST(160 as decimal) / [CUSTOM_CONCENTRATION]) BETWEEN EVSSMIN AND EVSMAX
AND [WARD] = '2ZKG' -- AND [P_ID]= 1003
AND [CUSTOM_CONCENTRATION] > 0;
另一种解决方案,更优雅的是:
SELECT * FROM [definities]
WHERE 160 BETWEEN [TDMIN] AND [TDMAX] AND [WARD] = '2ZKG'
AND (([P_ID]=` 1003
AND [CUSTOM_CONCENTRATION] <= 0)
OR
(CAST(160 as decimal) / [CUSTOM_CONCENTRATION]) BETWEEN EVSSMIN AND EVSMAX
AND AND [CUSTOM_CONCENTRATION] > 0));
答案 1 :(得分:1)
也许是这样的:
SELECT * FROM [definities] WHERE 160 BETWEEN [TDMIN] AND [TDMAX] AND
( case when [CUSTOM_CONCENTRATION] = 0 then EVSSMIN
else CAST(160 as decimal) / [CUSTOM_CONCENTRATION]) end
BETWEEN EVSSMIN AND EVSMAX )
AND [WARD] = '2ZKG'