SQL AdventureWorksは、City By Cityの従業員を数えています
-
30-09-2019 - |
質問
このような性別ごとに都市を数えたいです。
City GenderFCount GenderMCount
Redmond 10 20
これが私のクエリですadventureworksデータベースの都市と性別を取得します
select Gender,City from HumanResources.Employee as t1
inner join HumanResources.EmployeeAddress as t2
on t1.EmployeeID = t2.EmployeeID
inner join Person.Address as t3
on t2.AddressID = t3.AddressID
それが可能であれば、あなたは多くの方法で解決策を示すことができますか 「ピボット」、SQL関数(UDF)、ストアドプロシージャ または他の方法。
ありがとう
解決
これがピボットクエリです。ストアドプロシージャまたはUDFにそれをダンプできます
select City, F as GenderFCount, M as GenderMCount
from(
select Gender,City
from HumanResources.Employee as t1
inner join HumanResources.EmployeeAddress as t2
on t1.EmployeeID = t2.EmployeeID
inner join Person.Address as t3
on t2.AddressID = t3.AddressID
) AS pivTemp
PIVOT
( count(Gender)
FOR Gender IN ([F],[M])
) AS pivTable
UDFの例
CREATE FUNCTION fnPivot()
RETURNS TABLE
AS
RETURN (
select City, F as GenderFCount, M as GenderMCount
from(
select Gender,City
from HumanResources.Employee as t1
inner join HumanResources.EmployeeAddress as t2
on t1.EmployeeID = t2.EmployeeID
inner join Person.Address as t3
on t2.AddressID = t3.AddressID
) AS pivTemp
PIVOT
( count(Gender)
FOR Gender IN ([F],[M])
) AS pivTable
)
GO
今、あなたはそれをこのように呼ぶことができます
SELECT * FROM dbo.fnPivot()
他のヒント
ここでは、手順に埋め込まれた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
手順を変更するのではなく作成したい場合は、「変更」を「作成」に変更するだけです。次に、ストアドプロシージャのリストを更新すると、そこから変更できます。その後、「Create」は「Alter」を自動的に表示し、F5に達したときに変更が保存されます。次に、exec dbo.gendercountbycity(またはあなたの名前が何であれ)[または手順を右クリックしてストアドプロシージャの実行を選択]と入力すると、結果が得られます。
所属していません StackOverflow