如何解决如何在SQL中命名行
我有以下查询:
(SELECT count(ID)/2 FROM people where Date between '2000' and '2001')
union
(SELECT count(ID)/3 FROM people where Date between '2002' and '2004')
union
(SELECT count(ID)/6 FROM people where Date between '2005' and '2010')
数字正确。现在,我想在行中命名,以了解含义。 到目前为止,我只知道如何给列命名。
编辑:加上我该如何命名新名称所在的列?
解决方法
只需在子查询中添加一列:
select dt_2000_2001 as dt_range,count(id) cnt from people where date between 2000 and 2001
union all
select dt_2002_2004,count(id) / 2 from people where date between 2002 and 2004
union all
select dt_2005_2010,count(id) / 5 from people where date between 2005 and 2010
我不认为您这里确实需要union
。如果每年都有行,则可以使用case
表达式来构建组,并使用count(distinct)
来计算分母,如下所示:
select
case when date between 2000 and 2001 then dt_2000_2001
when date between 2002 and 2004 then dt_2002_2004
when date between 2005 and 2010 then dt_2005_2010
end as dt_range,count(*) / count(distinct date) cnt
from people
group by dt_range
,
我建议:
select (case when date between 2000 and 2001 then '2000-2001'
when date between 2002 and 2004 then '2002-2004'
when date between 2005 and 2010 then '2005-2010'
end) as dt_range,(count(*) * 1.0 /
(case when date between 2000 and 2001 then 1
when date between 2002 and 2004 then 2
when date between 2005 and 2010 then 5
end)
) as value
from people
group by dt_range;
您对分母的选择感到惊讶。比比率少一。我希望该值是完整范围。
假设您拥有所有年份的数据,则可以表示为:
select (case when date between 2000 and 2001 then '2000-2001'
when date between 2002 and 2004 then '2002-2004'
when date between 2005 and 2010 then '2005-2010'
end) as dt_range,(count(*) * 1.0 /
(max(date) - min(date) + 1)
) as value
from people
group by dt_range;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。