Group-By
如果同一表中不存在記錄,如何使用 group by 獲取計數 0?
我需要一些專家的建議。
我在 SQL Server 中有一張包含員工和電子程式碼的表。我想獲取每個員工的電子程式碼計數,但在某些情況下,員工沒有特定的電子程式碼。
我想返回零的員工缺少電子程式碼的地方。
SELECT Employee, eCode, Count(*) cnt FROM Test Group By Employee, eCode Order by Employee, eCode
上面的 SQL 給了我以下輸出
David 缺少 Gary 和 Tony 擁有的 eCode X 和 Y。我怎樣才能為其計數返回零。同樣,Gary 和 Tony 缺少 F 和 G,我希望這兩個值為零。
我可以在這裡使用一些幫助。
這應該完成您正在尋找的內容,但這假設您
eCodes
至少存在Test
表中的一條記錄。否則,您可以將下面Test
右側的表實例CROSS JOIN
替換為CTE
您的源表eCodes
:WITH CTE_EmployeeECodes AS -- Gets a distinct list of all Employee and eCode combinations ( SELECT DISTINCT E.Employee, EC.eCode FROM Test AS E CROSS JOIN Test AS EC ) SELECT EEC.Employee, EEC.eCode, COUNT(T.eCode) AS cnt FROM CTE_EmployeeECodes AS EEC LEFT JOIN Test AS T -- Left join allows us to keep all records from our source Employee & eCode combinations CTE, but T.eCode will be NULL for the eCodes an employee has 0 instances of ON EEC.Employee = T.Employee AND EEC.eCode = T.eCode GROUP BY EEC.Employee, EEC.eCode ORDER BY EEC.Employee, EEC.eCode