1

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

这是我的代码:

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

目前我有以下输出:

在职员工人数
X
员工变动
X

我该怎么做

员工人数 | 员工变动 | (员工人数 - 人数变化)
x | x | X
4

3 回答 3

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
于 2012-07-12T19:45:23.930 回答
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
于 2012-07-12T19:48:14.560 回答
0

如果 date<= '2012-05-31' 与 A.date < '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
于 2012-07-12T19:53:04.680 回答