从一行中选择一个字段作为另一个SQL的字段

时间:2013-06-19 15:10:40

标签: sql

很抱歉这个令人困惑的标题。我在寻找我正在寻找的解决方案时遇到了麻烦,因为我不知道如何用几句话来概括它。

我有一个表table_name,其中包含Indicator,ID和Num列。指标为0或1,ID最多可存在2次。如果ID号存在两次,则其中一个指示符为0,另一个为1,如果ID存在一次,则其指示符为0.如果行的指示符为0,则查询需要能够返回0如果指标为1,则匹配ID与指标0。

Indicator----ID-----Num

1-------------01----3000

0-------------01----4000

0-------------02----5000

0-------------03----100

1-------------04----400

0-------------04----200

查询结果

4000

0

0

0

200

0

3 个答案:

答案 0 :(得分:0)

select case when oneId.id is null the 0 else zero.num end case
from table1 zero 
left join table1 oneId
on zero.id = oneId.id
and 1 = oneId.indicator
where zero.indicator = 0

答案 1 :(得分:0)

试试这个:

SELECT IF(t1.indicator = 0 OR t2.Num IS NULL, 0, t2.Num)
FROM table_name as t1
LEFT JOIN table_name as t2 ON(
  t1.ID = t2.ID
  AND t1.indicator != t2.indicator
)

http://sqlfiddle.com/#!2/61623a/3

答案 2 :(得分:0)

这很棘手,因为你想确保不丢失任何行。出于这个原因,我使用嵌套的select语句执行此操作:

select (case when indicator = 0 then 0
             else (select t2.num from table_name t2 where t2.id = t.id and t2.indicator = 0)
        end) as Val
from table_name t

以下是一个工作示例(假设您的数据库支持with):

with table_name as (
      select 1 as indicator, 1 as id, 3000 as num union all
      select 0, 1, 4000 union all
      select 0, 2, 5000 union all
      select 0, 3, 100 union all
      select 1, 4, 400 union all
      select 0, 4, 200
     )
select (case when indicator = 0 then 0
             else (select t2.num from table_name t2 where t2.id = t.id and t2.indicator = 0)
        end) as Val
from table_name t