SQL:两次获取带有不同子句的列表,其中

时间:2018-09-04 14:43:08

标签: sql sql-server tsql where-clause

我尝试使用不同的子句两次获取同一表中的同一列:

我的查询:

SELECT 
    * 
FROM
    (SELECT TOP 10 
         CONVERT(DATE, attemptdate) AS Date, 
         Max(currentcount) AS A 
     FROM   
         logintracking 
     INNER JOIN 
         maxuser ON logintracking.loginid = maxuser.loginid 
     INNER JOIN 
         site ON site.siteid = maxuser.defsite 
     WHERE  
         attemptdate BETWEEN @dateDebut AND @dateFin 
         AND logintracking.clientaddr IN ('10.118.254.21', '10.118.254.156') 
     GROUP BY 
         CONVERT(DATE, attemptdate) 
     ORDER BY 
         CONVERT(DATE, attemptdate) ASC
    ) AS T1, 
    (SELECT TOP 10 
         CONVERT(DATE, attemptdate) AS Date, 
         MAX(currentcount) AS B 
     FROM   
         logintracking 
     INNER JOIN 
         maxuser ON logintracking.loginid = maxuser.loginid 
     INNER JOIN 
         site ON site.siteid = maxuser.defsite 
     WHERE  
         attemptdate BETWEEN @dateDebut AND @dateFin 
         AND logintracking.clientaddr = '10.118.254.35' 
     GROUP BY 
         CONVERT(DATE, attemptdate) 
     ORDER BY 
         CONVERT(DATE, attemptdate) ASC) AS T2 

结果:

enter image description here

所需结果:

enter image description here

我的目标是两次获得同一列'max(currentcount)'并应用不同的where子句,以便获得两个名为(A&B)的列,我还需要在第一列中显示日期,你能帮忙吗?谢谢

1 个答案:

答案 0 :(得分:1)

由于AB之间的唯一区别是logintracking.clientaddr,因此您可以将该条件放在CASE函数的MAX语句中:

SELECT CONVERT(DATE, attemptdate) AS Date, 
    MAX(CASE WHEN logintracking.clientaddr IN ( '10.118.254.21', '10.118.254.156' ) THEN currentcount END) AS A,
    MAX(CASE WHEN logintracking.clientaddr IN ( '10.118.254.35' ) THEN currentcount END) AS B
FROM logintracking 
    INNER JOIN maxuser 
        ON logintracking.loginid = maxuser.loginid 
    INNER JOIN site 
        ON site.siteid = maxuser.defsite 
WHERE attemptdate BETWEEN @dateDebut AND @dateFin
GROUP BY CONVERT(DATE, attemptdate) 
ORDER BY CONVERT(DATE, attemptdate) ASC