我想按性别统计城市,就像这样;
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
如果有可能,您可以通过多种方式显示解决方案,例如“PIVOT”,sql function(UDF),存储过程或其他方式。
感谢
答案 0 :(得分:6)
这是PIVOT查询,您可以将其转储到存储过程或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()
答案 1 :(得分:0)
这里使用的是嵌入在程序中的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(或者你的名字)[或者只需右键单击该程序并选择执行存储过程],你就会得到结果。