根据条件从另一个表中选择

时间:2019-03-11 08:38:12

标签: sql sql-server

我是SQL Server和SQL查询的新手。这是我的三个表:

enter image description here

主键

  • 表1:CaseId
  • 表2:ID
  • 表3:parentId

在表3中-如果父母是父亲,则状态码为 8 ;如果父母是母亲,则状态码为 10

我想编写一个选择查询,从中可以得到如下输出:

enter image description here

请帮助我,谢谢!

3 个答案:

答案 0 :(得分:1)

您应该能够使用Table3中的两个子查询,其中一个用于父亲,另一个用于母亲。然后您可以将它们与case和case-parent映射表连接起来,以获得所需的输出,

ion-radio

答案 1 :(得分:1)

您可以在表达式为大小写的情况下使用条件聚合

select caseid,casename,max(case when gendercode=8 then name end) as fathername
MAX(case when gendercode=8 then email end) as fatheremail,
MAX(case when gendercode=10 then name end) as mothername,
MAX(case when gendercode=10 then email end) as motheremail
from
(
select b.caseid,c.casesname,gendercode,name,email
from table3 a inner join table2 b on a.parentid=b.parentid
inner join table1 c on b.caseid=c.caseid
)A group by caseid,casename

答案 2 :(得分:0)

您可以尝试以下操作。要合并两行(母亲和父亲),可以使用MAX

使用GROUP BY聚合函数
SELECT caseid, 
       casename, 
       Max(fathername)  AS fathername, 
       Max(fatheremail) AS fatheremail, 
       Max(mothername)  AS mothername, 
       Max(motheremail) AS motheremail 
FROM   (SELECT t1.caseid, 
               t1.casename, 
               CASE 
                 WHEN gendercode = 8 THEN t3.NAME 
                 ELSE NULL 
               END AS fathername, 
               CASE 
                 WHEN gendercode = 8 THEN t3.email 
                 ELSE NULL 
               END AS fatheremail, 
               CASE 
                 WHEN gendercode = 10 THEN t3.NAME 
                 ELSE NULL 
               END AS mothername, 
               CASE 
                 WHEN gendercode = 10 THEN t3.email 
                 ELSE NULL 
               END AS motheremail 
        FROM   table1 t1 
               INNER JOIN table2 t2 
                       ON t1.caseid = t2.caseid 
               INNER JOIN table3 t3 
                       ON t2.parentid = t2.parentid 
        WHERE  t3.gendercode IN( 8, 10 ))t 
GROUP  BY caseid, 
          casename