SQL AdventureWorks 按城市按性别统计员工数量
我想按性别统计城市,像这样;
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函数(UDF),存储过程或其他方式。
谢谢
I want to count the cities by gender, like this;
City GenderFCount GenderMCount
Redmond 10 20
Here is my query gets city and gender in AdventureWorks database
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
If it is possible could you show the solution in many ways, like "PIVOT", by sql function(UDF), Stored Procedure or other ways.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 PIVOT 查询,您可以将其转储到存储过程或 udf
UDF 示例
中,现在您可以这样调用它
Here is the PIVOT query, you can dump that in a stored procedure or udf
Example of the UDF
now you can call it like this
这里它使用嵌入在过程中的 CTE。现在,我正在使用 AdventureWorks 2012,因为这就是我所拥有的全部。但概念是一样的。
如果您想创建而不是更改过程,只需将“ALTER”更改为“CREATE”即可。然后刷新存储过程列表,您可以从那里修改它。之后,“CREATE”将自动显示“ALTER”,如果成功,则按 F5 时将保存所有更改。然后您可以键入 EXEC dbo.GenderCountbyCity (或任何您的名字)[或者只需右键单击该过程并选择“执行存储过程”],您将获得结果。
Here it is using a CTE, embedded in a procedure. Now, I'm using AdventureWorks 2012, because that's all I have. But the concept is the same.
If you want to create, rather than alter, a procedure, just change "ALTER" to "CREATE". Then refresh your list of stored procedures and you can modify it from there. After that, the "CREATE" will automatically show "ALTER" and any changes will be saved when you hit F5, if it is successful. Then you can type EXEC dbo.GenderCountbyCity (or whatever your name is) [or just right-click the procedure and choose Execute Stored Procedure] and you will get the results.