将查询与不同的where子句条件组合在一起

时间:2019-01-22 20:34:49

标签: sql

如何合并这些查询,以便可以在第一个查询的第二个查询中使用dayCall

第一个查询

select clientid, 
DATEDIFF(
        DAY,
        CONVERT(datetime, convert(varchar(10), min(calendar))),
        MIN(dayCall)     
        )
from
Stats 
group by clientid

第二个查询

SELECT  
    clientid, 
    MIN(calendar)    
    as dayCall
FROM (
    SELECT 
        clientid, 
        CONVERT(datetime, convert(varchar(10), calendar)) calendar,
        lead(calls) over (partition by clientid order by calendar) as total_1,
        lead(calls, 2) over (partition by clientid order by calendar) as total_2
    FROM STATS

) a
where calls = 0 and total_1 = 0 and total_2 = 0
GROUP BY clientid

2 个答案:

答案 0 :(得分:3)

您可以将表连接在一起。我看到clientID在这两者中都是通用的,但是即使两个表之间没有通用的clientID,也应该进行完全外部联接以确保获得所有结果:

SELECT * FROM 
(
select clientid, 
DATEDIFF(
        DAY,
        CONVERT(datetime, convert(varchar(10), min(calendar))),
        MIN(dayCall)     
        )
from
Stats 
group by clientid
) tableA
FULL OUTER JOIN 
(
SELECT  
    clientid, 
    MIN(calendar)    
    as dayCall
FROM (
    SELECT 
        clientid, 
        CONVERT(datetime, convert(varchar(10), calendar)) calendar,
        lead(calls) over (partition by clientid order by calendar) as total_1,
        lead(calls, 2) over (partition by clientid order by calendar) as total_2
    FROM STATS

) a
where calls = 0 and total_1 = 0 and total_2 = 0
GROUP BY clientid
) tableB
ON tableA.clientid = tableB.clientid

答案 1 :(得分:0)

使用条件聚合:

select clientid, 
       min(case when calls = 0 and total_1 = 0 and total_2 = 0 then calendar end) as dayCall,
       datediff(day
                convert(datetime, convert(varchar(10), min(calendar))),
                min(dayCall)     
               )
from (select s.*, 
             convert(datetime, convert(varchar(10), calendar)) calendar,
                     lead(calls) over (partition by clientid order by calendar) as total_1,
                     lead(calls, 2) over (partition by clientid order by calendar) as total_2
      from STATS s
     ) s
group by clientid