這裏使用的是一個嵌入在程序中的CTE。現在,我正在使用AdventureWorks 2012,因爲這就是我的全部。但是這個概念是一樣的。
USE [AdventureWorks]
GO
/****** Object: StoredProcedure [dbo].[GenderCountbyCity] Script Date: 4/20/2016 9:07:04 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GenderCountbyCity]
AS
BEGIN
;WITH EmpF
AS (
SELECT pa.City, hre.Gender, COUNT(hre.Gender) AS CountF
FROM Person.BusinessEntityAddress pbea
JOIN Person.Address pa
ON pbea.AddressID = pa.AddressID
JOIN HumanResources.Employee hre
ON pbea.BusinessEntityID = hre.BusinessEntityID
WHERE hre.Gender = 'F'
GROUP BY pa.City, hre.Gender
),
EmpM
AS (
SELECT pa.City, hre.Gender, COUNT(hre.Gender) AS CountM
FROM Person.BusinessEntityAddress pbea
JOIN Person.Address pa
ON pbea.AddressID = pa.AddressID
JOIN HumanResources.Employee hre
ON pbea.BusinessEntityID = hre.BusinessEntityID
WHERE hre.Gender = 'M'
GROUP BY pa.City, hre.Gender
)
SELECT COALESCE(EmpF.City,EmpM.City) AS City, COALESCE(EmpF.CountF,0) AS GenderFCount, COALESCE(EmpM.CountM,0) AS GenderMCount
FROM EmpF
FULL JOIN EmpM
ON EmpF.City = EmpM.City
ORDER BY COALESCE(EmpF.City,EmpM.City)
END
如果你想創建一個過程而不是改變一個過程,只需將「ALTER」改爲「CREATE」即可。然後刷新你的存儲過程列表,你可以從那裏修改它。之後,「CREATE」將自動顯示「ALTER」,如果成功,則按F5時將保存所有更改。然後你可以輸入EXEC dbo.GenderCountbyCity(或者你的名字是什麼)[或者右鍵點擊程序並選擇執行存儲過程],你將得到結果。
對不起,我想根據城市來計算性別 – qods 2010-08-22 10:05:44
建議:如果您使用的是表格縮寫的別名,可能會使讀取更容易,例如HumanResources.Employee的hre。我相信有很多人以不同的方式做它。但對我而言,它有助於保持混亂程度。此外,在select語句中使用這些別名 - 即使在技術上不需要時 - 可以提醒您從哪個表中提取它。 – DaveX 2016-04-20 15:28:42