0

我有与 table1id 上的 Table2 相关的 Table1。

表格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

更新:固定结果

4

2 回答 2

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
于 2013-10-31T20:31:21.310 回答
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)
    )
于 2013-10-31T20:33:41.387 回答