这里它使用嵌入在程序中的 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 (或任何你的名字)[或只需右键单击该过程并选择执行存储过程],你会得到结果。