1

我有以下数据结构:

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

通常我使用以下查询来获取结果。

[问题 1]

SELECT * 
FROM [definities] 
WHERE 160 BETWEEN [TDMIN] AND [TDMAX] AND [WARD] = '2ZKG' AND [P_ID]=` 1003;

表中的最后一列可以包含大于 0 的值。高于 5。

通常我想运行下面的查询而不是上面的查询。

[问题 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] 列包含大于 0 的值时,查询 2 将正常工作。

问题是当 [CUSTOM_CONCENTRATION] 列不包含高于 0 的值时,查询无法返回记录。这意味着必须更改查询或基于 [CUSTOM_CONCENTRATION] 值的某些内容。我可以在 C# 代码中解决这个问题,但巧妙的方法是能够将其作为一个查询来执行,该查询根据值返回我的确切记录,而不是我需要迭代并使用 if 语句检查它的多个记录。

4

2 回答 2

1

[CUSTOM_CONCENTRATION]假设您在值为零或更低时想要第一个查询,否则第二个查询,您可以UNION ALL对两个查询使用带有另一个限制的 a:

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));
于 2012-06-21T08:34:57.173 回答
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'
于 2012-06-21T08:38:09.267 回答