query to select count of records for each year

你离开我真会死。 提交于 2019-12-11 17:05:19

问题


sorry for this newbie question ... im trying to get number of rows per year of my table..... this is my try:

select count(*)
from tbl_fact
where stat = 1 and id = 16
group by (year(fact_date))
go

and

select count(*)
from tbl_fact
where stat = 1 and id = 16 and year(fact_date) in (select Distinct(year(fact_date)) from tbl_fact)
group by (year(fact_date))
go

i have records that taged with dates that for now i have dates from 2017 and 2018 so i need counts for each year. but the id=16 has only date tag of 2018 not 2017 so i get result as

eg: 15

how ever it should be like

eg: 0 //2017
    15 //2018

回答1:


A simple method to get all years in the data -- even when they don't meet the conditions of the where clause -- is to use conditional aggregation:

select year(fact_date) as yyyy,
       sum(case when stat = 1 and id = 16 then 1 else 0 end) as cnt_16
from tbl_fact
group by year(fact_date)
order by yyyy;



回答2:


SELECT CAST([CountPerYear] AS VARCHAR(10)) 
        + ' // ' + 
        CAST([Year] AS VARCHAR(10))
FROM 
 (
    select   year(fact_date) [Year]
           , count(*)  [CountPerYear]
    from tbl_fact
    where stat = 1 and id = 16
    group by year(fact_date)
 )x



回答3:


You can get the count and year in two columns by:

select 
     count(*) as [COUNT], 
     year(fact_date) as [Year]
from tbl_fact
where stat = 1 and id = 16
group by (year(fact_date));

or as one string

select 
     count(*) + ' // ' + year(fact_date) as [grouping]
from tbl_fact
where stat = 1 and id = 16
group by (year(fact_date));


来源:https://stackoverflow.com/questions/48663898/query-to-select-count-of-records-for-each-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!