-5

我有 3 个查询需要合并为一个。他们来了

SELECT COUNT(e.EmployeeID) AS TotalEmpCount
FROM Employees as e
WHERE HomePhone <> ''

SELECT COUNT(e.EmployeeID) AS USEmpCount
FROM Employees as e
INNER JOIN Orders as o ON e.EmployeeID=o.EmployeeID
WHERE e.HomePhone <> '' AND e.Country='US' AND o.OrderDate BETWEEN '11/01/2011' AND GETDATE()


SELECT COUNT(e.EmployeeID) AS UKEmpCount
FROM Employees as e
INNER JOIN Orders as o ON e.EmployeeID=o.EmployeeID
WHERE HomePhone <> '' AND Country ='UK' AND o.OrderDate BETWEEN '01/01/2011' AND '12/31/2012'

我需要一个返回 3 列的查询:TotalEmpCount、USEmpCount、UKEmpCount。

我需要 T-SQL 和 Linq 格式的这个查询

4

2 回答 2

1

这应该会给您相同的结果:

SELECT COUNT(e.EmployeeID) AS TotalEmpCount,
    USEmpCount = SUM(CASE WHEN e.Country='US' AND o.OrderDate BETWEEN '11/01/2011' AND GETDATE() THEN 1 ELSE 0 END),
    UKEmpCount = SUM(CASE WHEN e.Country ='UK' AND o.OrderDate BETWEEN '01/01/2011' AND '12/31/2012' THEN 1 ELSE 0 END)
FROM Employees as e
LEFT JOIN Orders o
    ON e.EmployeeID = o.EmployeeID
WHERE HomePhone <> ''
于 2012-11-15T20:22:58.380 回答
0

我自己想通了:

SELECT  (
        SELECT COUNT(*) 
FROM Employees as e
WHERE HomePhone <> ''
        ) AS TotalEmpCount,
        (
        SELECT COUNT(*)
FROM Employees as e
INNER JOIN Orders as o ON e.EmployeeID=o.EmployeeID
WHERE e.HomePhone <> '' AND e.Country='US' AND o.OrderDate BETWEEN '11/01/2011' AND GETDATE()
        )  AS USEmpCount,
        (
        SELECT COUNT(*)
FROM Employees as e
INNER JOIN Orders as o ON e.EmployeeID=o.EmployeeID
WHERE HomePhone <> '' AND Country ='UK' AND o.OrderDate BETWEEN '01/01/2011' AND '12/31/2012'
        )  AS UKEmpCount
于 2012-11-15T20:15:45.527 回答