SQL基于con将行提取为列

时间:2018-11-16 16:00:49

标签: sql oracle etl

我在下面的结构中有一个表。我想创建一个可以按特定顺序获取记录的sql。

Name	Phone	B.Email           P.Email
Jack	12      ab12@test.com	  a21@test.com
Ram	12345   null              Ram@test.com
Raja    543     Raj@test.om       null
Rik     122     null		  null

我要按以下顺序输出

Name	Phone	        EMAIL			IsPrimary	EmailType
Jack	123		ab12@test.com		Y		B
Jack	123		a21@test.com		N		P
Ram	321	        Ram@test.com		Y		P
Raja	543		Raj@test.om		Y		B

如果有B.Email,则它将是主要的,否则P.Email将是主要的。如果两个电子邮件都为空,那么该记录将不在输出中。

4 个答案:

答案 0 :(得分:0)

这是您想要的吗?

order by phone, name, isprimary desc

答案 1 :(得分:0)

我使用UNION来首先吸引使用b.email的人员,然后让那些使用p.email和CASE的人员分类主要人员并输入

SELECT name, phone, b.email EMAIL, 'Y' IsPrimary,
    CASE WHEN b.email  IS NULL THEN 'P'
    ELSE 'B' 
    END EmailType
FROM mail
WHERE b.email IS NOT NULL 
UNION 
SELECT name, phone,  p.email EMAIL, 
   CASE WHEN b.email IS NULL THEN 'Y'
   ELSE 'N' 
   END IsPrimary,
   CASE WHEN b.email  IS NULL THEN 'P'
   ELSE 'B' 
   END EmailType
FROM mail
WHERE p.email IS NOT NULL 
ORDER BY name

答案 2 :(得分:0)

其他答案很接近,但我认为它们的输出都有错误。

不确定这是什么SQL引擎,这是我对MySQL5.6的回答:

SELECT name,
       phone,
       CASE WHEN BEmail IS NOT NULL THEN BEMail ELSE PEmail END as EMAIL,
       'Y' as IsPrimary,
       CASE WHEN BEmail IS NOT NULL THEN 'B' ELSE 'P' END as EmailType
FROM table_name t
WHERE NOT (BEmail IS NULL AND PEmail IS NULL)
UNION ALL
SELECT name, phone, PEmail, 'N', 'P'
from table_name
WHERE BEmail IS NOT NULL
AND PEmail IS NOT NULL
ORDER BY Name;

请注意,我已将B.Email更改为BEmail,将P.Email更改为PEMail,该表称为“ table_name”。

SQL Fiddle here

答案 3 :(得分:0)

请尝试以下查询:

create table     Table3
(Name  varchar2(20),
phone number,
"B.mail" varchar2(50),
"P.mail" varchar2(50));

insert into Table3 values ('Jack',12,'ab12@test.com','a21@test.com');
insert into Table3 values ('Ram',12345,null,'Ram@test.com');
insert into Table3 values ('Raja',543,'Raj@test.com',null);
insert into Table3 values ('Rik',122,null,null);

SELECT Name, Phone, COALESCE("B.mail","P.mail") Email, CASE WHEN "B.mail" IS NOT NULL THEN 'Y'  ELSE 'N' END as IsPrimary,CASE WHEN "B.mail" IS NOT NULL THEN 'B'  ELSE 'P' END as EmailType
FROM Table3 t
where "B.mail" IS NOT NULL OR "P.mail" IS NOT NULL 
UNION 
SELECT Name, Phone, COALESCE("P.mail","B.mail") Email, CASE WHEN "P.mail" IS NOT NULL THEN 'N'  ELSE 'Y' END as IsPrimary,CASE WHEN "P.mail" IS NOT NULL THEN 'P'  ELSE 'B' END as EmailType
FROM Table3 t
where "B.mail" IS NOT NULL OR "P.mail" IS NOT NULL