找到3个值中的至少3个,不包括零

时间:2011-06-30 11:38:39

标签: sql sql-server

我正在寻找至少三列(Market, LiFo, Wgtd_Avg)。我可以做,但排除等于零的三个中的任何一个 我只想找到最少的> zero

SELECT Market, LiFo, Wgtd_Avg,
(
    CASE
        WHEN Market < LiFo AND Market < Wgtd_Avg AND Market > 0 THEN Market
        WHEN LiFo  < Wgtd_Avg AND LiFo > 0 THEN LiFo
        WHEN Wgtd_Avg > 0 THEN Wgtd_Avg
        ELSE 0
    END
) AS LeastOfThree
FROM VF_CasINV_Cost

2 个答案:

答案 0 :(得分:2)

原始答案:

SELECT min(Value) FROM
(
SELECT Market as Value FROM VF_CasINV_Cost WHERE Market > 0
UNION
SELECT Wgtd_Avg as Value FROM VF_CasINV_Cost WHERE Wgtd_Avg > 0
UNION
SELECT LiFo as Value FROM VF_CasINV_Cost WHERE LiFo > 0
) union_table

评论后编辑:

SELECT Market, Wgtd_Avg, LiFo, min(least) AS leastOfThree FROM
(
SELECT min(market) as market, min(Market) as least FROM VF_CasINV_Cost WHERE Market > 0
UNION
SELECT min(Wgtd_avg) as Wgtd_Avg, min(Wgtd_Avg) as least FROM VF_CasINV_Cost WHERE Wgtd_Avg > 0
UNION
SELECT min(lifo) as LiFo, min(lifo) as least FROM VF_CasINV_Cost WHERE LiFo > 0
) as union_table

我远离带有sql服务器的计算机,所以暂时无法测试,但它应该接近工作......我会测试它并在我回来时立即编辑。< / p>

答案 1 :(得分:1)

SELECT
  MIN(
    CASE x.f
      WHEN 1 THEN t.Market
      WHEN 2 THEN t.Wgtd_Avg
      WHEN 3 THEN t.LiFo
    END
  ) AS MinValue
FROM VF_Cas_INV_Cost t
  INNER JOIN (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) x (f)
    ON CASE x.f
      WHEN 1 THEN t.Market
      WHEN 2 THEN t.Wgtd_Avg
      WHEN 3 THEN t.LiFo
    END > 0