我需要将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格式的查询
答案 0 :(得分: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 <> ''
答案 1 :(得分: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