SQL查询组合表

时间:2017-07-31 13:44:41

标签: sql

如何使用下面的SQL将3个表组合在一起?

-----------   -----------   -----------
AdminAccLog   StaffAccLog   PublicAccLog
-----------   -----------   -----------
id            id            id
name          name          name
ipaddress     ipaddress     ipaddress
datetime      datetime      datetime
task          task          task
---------------------------------------

数据

AdminAccLog 1 ABC 127.0.0.1 30/7/2017 0:00:00AM Logon
AdminAccLog 2 ABC 127.0.0.1 30/7/2017 1:00:00AM Logon
AdminAccLog 3 ABC 127.0.0.1 31/7/2017 0:00:00AM Logon

StaffAccLog 1 ABC 127.0.0.1 31/7/2017 0:00:00AM Logon
PublicAccLog 1 ABC 127.0.0.1 31/7/2017 0:00:00AM Logon

SQL查询

SELECT COUNT(*) AS PublicCount, CONVERT(DATE, datetime) AS PublicDate 
FROM PublicAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime)

SELECT COUNT(*) AS StaffCount, CONVERT(DATE, datetime) AS StaffDate 
FROM StaffAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime)

SELECT COUNT(*) AS AdminCount, CONVERT(DATE, datetime) AS AdminDate 
FROM AdminAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime)

我希望查询结果在同一个表中(不是插入表)

新查询结果为:

----------- ---------- ---------- --------- ---------- ---------
PublicCount PublicDate StaffCount StaffDate AdminCount AdminDate
----------- ---------- ---------- --------- ---------- ---------
 1          31/7/2017  1          31/7/2017 2          30/7/2017 0:00:00AM
                                            1          31/7/2017 0:00:00AM

另一个例子:

Current result

I want the result to be like this

2 个答案:

答案 0 :(得分:1)

据推测,您希望每行的日期列相同,然后才能获得计数。

一种方法使用union all和聚合:

SELECT dte, SUM(PublicCount) as PublicCount, SUM(StaffCount) as StaffCount,
       SUM(AdminCount) as AdminCount
FROM ((SELECT CONVERT(DATE, datetime) AS dte , COUNT(*) AS PublicCount,
              0 as StaffCount, 0 as AdminCount
       FROM PublicAccLog
       WHERE task = 'Logon' 
       GROUP BY CONVERT(DATE, datetime)
      ) UNION ALL
      (SELECT CONVERT(DATE, datetime), 0, COUNT(*) AS StaffCount, 0 AS StaffDate 
       FROM StaffAccLog
       WHERE task = 'Logon' 
       GROUP BY CONVERT(DATE, datetime)
      ) UNION ALL
      (SELECT CONVERT(DATE, datetime), 0, 0, COUNT(*) AS AdminCount
       FROM AdminAccLog
       WHERE task = 'Logon' 
       GROUP BY CONVERT(DATE, datetime)
      )
     ) t
GROUP BY dte
ORDER BY dte;

答案 1 :(得分:0)

Select 
MAX(PublicCount)PublicCount,
MAX(PublicDate),
MAX(StaffCount)StaffCount,
MAX(StaffDate)StaffDate,
MAX(AdminCount)AdminCount,
MAX(AdminDate)AdminDate 
    from (
SELECT COUNT(*) AS PublicCount, CONVERT(DATE, datetime) AS PublicDate 
FROM PublicAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime) )T
,
(

SELECT COUNT(*) AS StaffCount, CONVERT(DATE, datetime) AS StaffDate 
FROM StaffAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime))TT
,

(
SELECT COUNT(*) AS AdminCount, CONVERT(DATE, datetime) AS AdminDate 
FROM AdminAccLog WHERE task = 'Logon' 
GROUP BY CONVERT(DATE, datetime) )TTT