在一个答案下加入两个不同的查询

时间:2012-07-12 19:40:21

标签: sql combinations

我有两个不同的查询产生了正确的结果,但我想让他们在一个表中产生答案。我该怎么做?

这是我的代码:

SELECT count(distinct ID) as NoOfEmployees
FROM Table_Name
WHERE date<= '2012-05-31';

select count(subA.ID) as EmployeesChanged from (
SELECT A.ID 
FROM Table_Name A 
WHERE A.date < '2012-06-01' 
GROUP BY 1 
HAVING COUNT(A.Service_type) > 1 ) subA

目前我有以下输出:

Number of Employees
x
Employees Changed
x

如何制作

Number of Employees |  Employees Changed  | (Number of employees - number changed)
x                   |             x       |            x

3 个答案:

答案 0 :(得分:2)

我不知道您使用的数据库。但对于某些数据库,您可以尝试:

select q1.Value, q2.Value, q1.Value - q2.Value from
  (SELECT count(distinct ID) as Value FROM Table_Name 
    WHERE date<= '2012-05-31') q1,
  (select count(subA.ID) as Value from 
      ( SELECT A.ID FROM Table_Name A 
        WHERE A.date < '2012-06-01' GROUP BY 1 
        HAVING COUNT(A.Service_type) > 1 ) subA) q2

答案 1 :(得分:0)

您可以使用CROSS JOIN

SELECT a.*, b.*, a.NoOfEmployees - b.EmployeesChanged
FROM
(
    SELECT count(distinct ID) as NoOfEmployees
    FROM Table_Name
    WHERE date<= '2012-05-31'
) a
CROSS JOIN
(
    SELECT count(subA.ID) as EmployeesChanged 
    FROM 
    (
        SELECT A.ID 
        FROM Table_Name A 
        WHERE A.date < '2012-06-01' 
        GROUP BY 1 
        HAVING COUNT(A.Service_type) > 1 
    ) subA
) b

修改

您可以通过使用条件聚合而不是执行两个单独的查询来大大优化查询:

SELECT a.NoOfEmployees, a.EmployeesChanged, a.NoOfEmployees - a.EmployeesChanged
FROM
(
    SELECT 
        COUNT(DISTINCT CASE WHEN date <= '2012-05-31' THEN ID END) as NoOfEmployees,
        COUNT(DISTINCT CASE WHEN date < '2012-06-01' AND COUNT(Service_type) > 1 THEN ID END) AS EmployeesChanged
    FROM Table_Name
    GROUP BY ID
) a

答案 2 :(得分:0)

如果日期&lt; =''2012-05-31'与A.date&lt;相同'2012-06-01'?

SELECT COUNT(1) AS NoOfEmployees,
SUM(CASE WHEN STCount > 0 then 1 else 0 end) as HasChange,
SUM(CASE WHEN STCount = 0 then 1 else 0 end) as NoChange
FROM 
  (SELECT ID,
  COUNT(A.Service_type) STCount
  FROM Table_Name
  WHERE date<= '2012-05-31'
  GROUP BY ID) AS Data