2012-11-15 192 views
-5

我有3個需要合併爲一個的查詢。這裏他們是將3個SQL查詢合併爲1

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的格式

+6

可以提高通過問一個問題...並顯示你所做的事(你的1個查詢)以及你得到的錯誤類型。 – MikeSmithDev

+0

如果我已經有一個查詢,我可能不會首先問一個問題。 – ElenaDBA

+0

顯示你的嘗試,並詢問你如何改進或使其工作,比告訴我們你需要什麼並期待答案好得多。 – MikeSmithDev

回答

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 
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 <> ''