我有两个表格,我想从SQL的同一列中检索不同的结果

时间:2019-09-13 05:10:55

标签: sql-server

我已经列出了实际表。因此,我希望得到预期的结果。

enter image description here

2 个答案:

答案 0 :(得分:0)

您的问题不是您写的问题。您首先要学习如何规范化SQL或表格数据。当您应用第二范式时,此问题已解决。 给定的链接可以更好地理解规范化。 Normalization in SQL Tables

答案 1 :(得分:0)

尝试

CREATE TABLE demo (
jobPreference varchar(255),
Triggered varchar(255),
Success varchar(255),
opened varchar(255));


INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('email-pwd reset', 'yes', 'success','yes');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('email-pwd reset', 'yes', 'success','yes');

INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('email-pwd reset', 'yes', 'fail','no');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('email-statement', 'yes', 'success','no');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('email-EMI reminder', 'yes', 'fail','no');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('SMS-loan EMI', 'yes', 'fail','no');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('SMS-confirmation', 'yes', 'fail','no');
INSERT INTO demo(jobPreference,Triggered,Success,opened) VALUES ('SMS-confirmation', 'yes', 'success','yes');


select SUBSTRING(jobPreference,0,CHARINDEX('-',jobPreference,0)) as Splitted
        ,jobPreference
        ,count(case Triggered when 'yes' then 1 else null end) as TriggeredCount
        ,count(case Success when 'success' then 1 else null end) as SuccessCount
        ,count(case opened when 'yes' then 1 else null end) as openedCount 
from demo
group by jobPreference

对于演示:https://rextester.com/ANPN26483