TSQL,帮助查询用户年龄

TSQL, help with small query about user#39;s age(TSQL,帮助查询用户年龄)
本文介绍了TSQL,帮助查询用户年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个包含注册用户的表,其中我将年份保存为 varchar 值,因为我只需要一年.我想创建带有年龄的饼图以显示哪些用户更有可能注册.

I have a table with registered users, in which i save year as varchar values simply because i take just an year. I want to create pie chart with ages to show which users are more likely to register.

下面的查询为我提供了在表中出现超过 5 次的用户年龄计数,以避免出现小结果.虽然这些小结果,在拥有 ount(userID)>5"下面我想以其他人的身份出现.我应该向这个查询添加什么或可能重新设计它.我可以创建愚蠢的解决方案,比如获取出现在初始查询中的所有年份,然后选择除那些年份之外的所有年份,但必须有更好、更有创意的方式来编写此查询.

Query below gives me count of user ages which appear more than 5 times in Table to avoid small results. While these small results, below "having ount(userID)>5" i want to appear as others. What should i add to this query or possibly to re-design it. I can create silly solutions like to take all years that appear in initial query and then select all besides those year but there must be better and more creative way of writing this query.

所以结果将是这样的1 10 19902 4 19803 10 其他

So result will be something like that 1 10 1990 2 4 1980 3 10 others

select count(userID) ageCount,userBirthYear from Users
group by userBirthYear
having count(userID)>5
order by count(userID) desc

谢谢

推荐答案

这是一种方法(假设 SQL2005 或更高版本).

Here's one way (assuming SQL2005 or later).

With Ages As
(
select count(userID) ageCount,userBirthYear 
from Users
group by userBirthYear
)

SELECT ageCount,userBirthYear FROM Ages WHERE ageCount>5
UNION ALL
SELECT sum(ageCount) ,'others' As userBirthYear FROM Ages WHERE ageCount<=5

这篇关于TSQL,帮助查询用户年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Error casting varchar containing a number expressed in scientific notation to decimal(将包含以科学记数法表示的数字的 varchar 转换为十进制时出错)
Calculate cumulative product value(计算累积产品价值)
SQL Server loop for changing multiple values of different users(用于更改不同用户的多个值的 SQL Server 循环)
SQL Server 2008: Can a multi-statement UDF return a UDT?(SQL Server 2008:多语句 UDF 能否返回 UDT?)
Merge columns in sql(合并sql中的列)
SQL Column is invalid in ORDER BY, not contained in aggregate or GROUP BY(SQL 列在 ORDER BY 中无效,未包含在聚合或 GROUP BY 中)