TSQL, help with small query about user's age

不问归期 提交于 2020-01-24 12:15:54

问题


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.

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.

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

thanks


回答1:


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



回答2:


Here's a regrouping solution (union-less) to avoid repeated IO.

The basic idea is you want every record to contribute to the result, so there should be no WHERE or HAVING clauses.

SELECT
  SUM(sub.ageCount) as ageCount,
  sub.userBirthYear
FROM
(
  SELECT Count(userId) ageCount,
    CASE WHEN COUNT(userID) > 5)
         THEN userBirthYear
         ELSE 'Other'
    END as userBirthYear
  FROM Users
  GROUP BY userBirthYear
) as sub
GROUP BY sub.userBirthYear



回答3:


select  count(userID) ageCount,userBirthYear from Users 
group   by userBirthYear 
having  count(userID)>5 
union
SELECT  SUM(agecount), 'Others' 
FROM    (select count(userID) ageCount,'Others' userBirthYear from Users 
     group  by userBirthYear 
     having count(userID)<5)TMP 
order by    count(userID) desc


来源:https://stackoverflow.com/questions/3101653/tsql-help-with-small-query-about-users-age

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