查询以选择每年的记录数

时间:2018-02-07 12:31:43

标签: sql sql-server sql-server-2012

抱歉这个新手问题...我试图获取每年的行数......这是我的尝试:

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

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

我有记录的日期,现在我有2017年和2018年的日期,所以我需要每年的计数。但id = 16只有2018年的日期标签而不是2017年,所以我得到结果

eg: 15

怎么样呢

eg: 0 //2017
    15 //2018

3 个答案:

答案 0 :(得分:2)

获取数据所有年份的简单方法 - 即使它们不符合where子句的条件 - 是使用条件聚合:

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;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以通过以下方式将计数和年份分为两列:

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

或作为一个字符串

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