2016-08-18 60 views
0

我想结合2不同的选择where子句 第一选择是合并2 SELECT语句不同的where子句SQLSERVER

SELECT name, 
    COUNT(telat_1_30min) 
FROM kkpsurabaya 
WHERE telat_1_30min >= 1 
AND telat_1_30min <= 30; 

结果是:

name   | telat1 1-30 min 
FERI WAHYUDI | 2 

和其他选择是

SELECT COUNT(late) AS 'telat 31-60min' 
FROM kkpsurabaya 
WHERE timetable NOT LIKE 'minggu' 
AND timetable NOT LIKE 'sabtu' 
AND late <= 90 
AND late >= 61; 

且结果如下:

name   | telat1 31-60 min 
KARIYONO  | 1 

我想结合,像

name   | telat1 1-30 min|telat1 31-60 min 
FERI WAHYUDI | 2    |0 
KARIYONO  | 0    |1 

我尝试使用查询

SELECT name, 
     'telat < 30menit' = (SELECT 
     COUNT(telat_1_30min) AS 'telat 1-30min' 
     FROM kkpsurabaya 
     WHERE telat_1_30min >= 1 
     AND telat_1_30min <= 30), 
     'telat 31-60 min' = (SELECT 
     COUNT(late) AS telat_60_90 
     FROM kkpsurabaya 
     WHERE timetable NOT LIKE 'minggu' 
     AND timetable NOT LIKE 'sabtu' 
     AND late <= 90 
     AND late >= 61) 
FROM kkpsurabaya 
GROUP BY Name; 

,其结果是:

name   | telat1 1-30 min|telat1 31-60 min 
FERI WAHYUDI | 2    |1 
KARIYONO  | 2    |1 

telat_1_30min的数据类型为int

末的数据类型为int

解决

select name ,sum (case when telat_1_30min >=1 and telat_1_30min <=30 then 1 else 0 end) as 'telat1 1-30 min' ,sum(case when timetable not like 'minggu' and timetable not like 'sabtu' and late <=90 and late >=61 then 1 else 0 end) as 'telat1 31-60 min' from kkpsurabaya group by name

回答

2
select name, count(telat_1_30min) as ' telat1 1-30 min',0 as 'telat1 31-60 min' 
    from kkpsurabaya where telat_1_30min >=1 and telat_1_30min <=30 
    union all 
    SELECT name,0 as ' telat1 1-30 min', count(late) as 'telat 31-60min' 
    FROM kkpsurabaya WHERE timetable not like 'minggu' and timetable not like 'sabtu' and late <=90 and late >=61 

编辑

select 
a.name 
,sum(telat1 31-60 min) as 'telat1 1-30 min' 
,sum(telat1 31-60 min) as 'telat1 31-60 min' 
(
select name 
,case when telat_1_30min >=1 and telat_1_30min <=30 then 1 else o end as 'telat1 1-30 min' 
,case when timetable not like 'minggu' and timetable not like 'sabtu' and late <=90 and late >=61 then 1 else 0 end as 'telat1 31-60 min' 
from timetable 
)a 
group by a.name 
+0

嗯仅显示与名称才有价值,我怎么能显示没有价值的命名?我的意思是他们telat 1-30 = 0和31-60 = 0 –

+0

什么是总和(telat1 31-60分钟)为'telat1 1-30分钟' ,总和(telat1 31-60分钟)为'telat1 31 -60分钟,那里,我没有专栏telat1 31-60分钟 –