Pregunta

Quiero contar las ciudades de género, como esto;

City    GenderFCount  GenderMCount
Redmond 10             20   

Aquí está mi consulta obtiene ciudad y de género en la base de datos 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

Si es posible se puede mostrar la solución de muchas maneras, como "eje", por la función de SQL (UDF), procedimiento almacenado o de otras maneras.

gracias

¿Fue útil?

Solución

Ésta es la consulta de pivote, se puede volcar de que en un procedimiento almacenado o 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

Ejemplo de la 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

Ahora se le puede llamar como esto

 SELECT * FROM dbo.fnPivot()

Otros consejos

Aquí está utilizando un CTE, incrustado en un procedimiento. Ahora, estoy usando AdventureWorks 2012, porque eso es todo lo que tengo. Pero el concepto es el mismo.

    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

Si desea crear, en lugar de alter, un procedimiento, sólo cambia "ALTER" para "crear". Entonces refrescar la lista de procedimientos almacenados y se puede modificar desde allí. Después de eso, el "crear" se mostrará automáticamente "ALTER" y cualquier cambio será salvo cuando se pulse F5, si tiene éxito. A continuación, puede escribir EXEC dbo.GenderCountbyCity (o como se llame) [o simplemente haga clic con el procedimiento y seleccione Ejecutar procedimiento almacenado] y obtendrá los resultados.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top