2010-08-22 4 views
7

Voglio contare le città in base al sesso, come questo;SQL AdventureWorks conta i dipendenti in base al sesso per città

City GenderFCount GenderMCount 
Redmond 10    20 

Ecco la mia domanda diventa città e di genere nel database 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 

Se è possibile si potrebbe mostrare la soluzione in molti modi, come "pivot", dalla funzione SQL (UDF) , Stored procedure o altri modi.

grazie

+0

dispiace voglio contare il genere dalle città – qods

+0

Un suggerimento: se si utilizzano gli alias che sono le abbreviazioni delle tabelle, potrebbe rendere più facile da leggere, per esempio, per HRE HumanResources.Employee. Sono sicuro che ci sono molte persone che lo fanno in modi diversi. Ma per me, aiuta a mantenere basso il livello di confusione. Inoltre, l'utilizzo di quegli alias nell'istruzione select, anche quando tecnicamente non sono necessari, può ricordarti da quale tabella lo hai estratto. – DaveX

risposta

6

Ecco la query PIVOT, è possibile scaricare che in una stored procedure 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 

Esempio di 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 

ora si può chiamare in questo modo

SELECT * FROM dbo.fnPivot() 
0

Qui sta usando un CTE, incorporato in una procedura. Ora sto usando AdventureWorks 2012, perché è tutto ciò che ho. Ma il concetto è lo stesso.

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 

Se si desidera creare, piuttosto che alterare, una procedura, basta cambiare "ALTER" per "creare". Quindi aggiorna l'elenco delle stored procedure e puoi modificarlo da lì. Dopodiché, "CREATE" mostrerà automaticamente "ALTER" e tutte le modifiche verranno salvate quando si preme F5, se ha successo. Quindi puoi digitare EXEC dbo.GenderCountbyCity (o qualunque sia il tuo nome) [o semplicemente fare clic con il pulsante destro del mouse sulla procedura e scegliere Esegui stored procedure] e otterrai i risultati.

Problemi correlati