来自2个具有唯一行的表的结果,具体取决于字段值

时间:2013-10-31 20:22:13

标签: sql sql-server-2008-r2

我有Table1与table1id上的Table2相关。

表1

id, telephone, name
1, 5555555555, joe smith
2, 5555555556, jack j
3, 5555555557, h. guy

表2

id, table1id, street, status
1, 1, 1234 A street, GOOD
2, 2, 888 B street, BAD
3, 2, 54 A street, UNKNOWN
4, 3, 7th ave, BAD
5, 3, 1212 A street, suite 2, GOOD
6, 3, 5678 B street, BAD

Table2.status的可能值为GOOD,BAD和UNKNOWN

我正在寻找一个根据Table2.status返回不同的Table1.telephone和名称的查询。因此,如果table2.status为GOOD,则result.active = yes,否则result.active = no

table1.id, telephone, name, street, active
1, 5555555555, joe smith, 1234 A street, yes
2, 5555555556, jack j, 888 B street, no
5, 5555555557, h. guy, 1212 A street, yes

更新:修正结果

2 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

select distinct t1.id, 
t1.telephone, 
t1.name, 
t2.street, 
case when t2.status = 'GOOD' then 'Yes'
     when t2.status = 'BAD' then 'No'
     else 'No' as active
end
from table1 t1
inner join table2 t2 on t2.table1id = t1.id

答案 1 :(得分:0)

基于您发布的示例答案,您似乎不希望包含表2中的行,其中同一个table1ID恰好具有多个Table2ID。例如,Table1ID 3不在您的结果集中。

基于这个假设

    SELECT t1.id, t1.telephone, t1.NAME,t2.address1,t2.address2
            , CASE 
                    WHEN t2.STATUS = 'GOOD' THEN 'Yes'
                    Else 'No'
            END AS Active
    FROM table1 t1
    JOIN table2 t2
        ON t1.id=t2.Table1ID
        AND t1.ID IN
    (
        SELECT TableID1
        FROM table2
        GROUP BY TableID1
        HAVING (COUNT(DISTINCT ID) =1)
    )