sql >> Databasteknik >  >> RDS >> Sqlserver

Få räkning för flera fält med hjälp av group by i SQL

select data.category, cl.combovalue as esilocation, cd.combovalue as esidispensary,
    year(date) as year, month(date) as month,
    sum(data.joins) as [Joining Count], sum(data.terms) as [Termination Count]
from (
    select category, esilocation, esidispensary, dateofjoining as date,
           1 as joins, 0 as terms
    from dbo.employeedetail
    where dateofjoining is not null
    union all
    select category, esilocation, esidispensary, terminationdate as date,
           0 as joins, 1 as terms
    from dbo.employeedetail
    where terminationdate is not null
) data
left join dbo.combovalues cl on cl.id = data.esilocation
left join dbo.combovalues cd on cd.id = data.esidispensary
where category in ( 1, 2 ) 
and date >= '2014-01-01' 
and date <= '2014-12-31'
group by data.category, cl.combovalue, cd.combovalue, year(date), month(date)


  1. SQL:trigger för att förhindra att ogiltiga data infogas i en tabell

  2. Servern skickade teckenuppsättning (255) okänd för klienten, men teckenuppsättningarna matchar

  3. SQL Server 2017:Tillgängliga funktioner på Linux

  4. Hur visar man kategorier, underkategorier, underkategorier i vald lista - php/mysql?