我是SQL的新手,我希望你能帮我解决一个问题。我有一张桌子,如果它们在几年之前不存在,我需要计算今年的独特价值(基本上我只想知道2016年的新条目)。
BP Name Year
A 2013
B 2016
A 2014
A 2016
C 2012
C 2016
在这种情况下,它只计为1(BP名称:B)
由于 卡斯特里奥特·
答案 0 :(得分:1)
我会用两级聚合来处理这个问题。以下是所有年份的计算:
select first_year, count(*)
from (select pbname, min(year) as first_year
from t
group by pbname
) t
group by first_year;
2016年:
select count(*)
from (select pbname, min(year) as first_year
from t
group by pbname
) t
where first_year = 2016;
答案 1 :(得分:1)
试试这个
select count(*)
from
(select Distinct bpname,year
from tmpBP a
where a.year=2016
and not exists (select 1 from tmpBP b where a.bpname = b.bpname and a.year > b.year
)
)x
答案 2 :(得分:1)
这应该有效:
"今年的独特价值" =表名 BP名称和年份=列
select t."BP Name", t."Year" from
(select "BP Name", "Year" from "unique values this year" where year("Year")=2016) t
left join (select "BP Name" from "unique values this year" where year("Year")!=2016 ) t1 on t."BP Name"=t1."BP Name"
where t1."BP Name" is null
答案 3 :(得分:0)
检查一下。
select count(*) from table1 a
where a.year=2016
and not exists (select 1 from table1 b where a.bpname = b.bpname and a.year > b.year)
答案 4 :(得分:0)
SELECT COUNT(BPName),BPName,_Year FROM #Temp otr WHERE NOT EXISTS(SELECT 1 FROM #Temp inr WHERE inr.BPName = otr.BPName and inr._Year > otr._Year ) GROUP BY BPName,_Year