昨天遇到的一道大数据sql题目,求解答!

deepmist 2013-09-12 12:05:18
有一张表UserInfo,
字段(UserNo 用户编号,UserName 用户名,UserAge 用户年龄,UserSalary 用户薪水)
这张表存储了100万左右的数据,
请用一条你认为最高效的sql实现以下条件数据条数的统计。
1. UserSalary >9999 and UserAge >35
2. UserSalary >9999 and UserAge <35
3. UserSalary <9999 and UserAge >35
4. UserSalary <9999 and UserAge <35

遇到的这个面试题,也不知道标准答案,大家有什么好的办法呢?
...全文
290 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2013-09-13
  • 打赏
  • 举报
回复
如果要最高效的sql实现,可以用视图索引.
  • 打赏
  • 举报
回复
select sum(case when UserSalary >9999 and UserAge >35 then 1 else 0 end ) as count1,
  sum(case when UserSalary >9999 and UserAge <35 then 1 else 0 end ) as count2,
  sum(case when UserSalary <9999 and UserAge >35 then 1 else 0 end ) as count3,
  sum(case when UserSalary <9999 and UserAge <35 then 1 else 0 end ) as count4
   from UserInfo 
无名熊猫 2013-09-12
  • 打赏
  • 举报
回复
在UserAge属性上建立索引,然后查询条件结构为UserAge在最外层,UserSalary嵌套在最里面一层。
發糞塗牆 2013-09-12
  • 打赏
  • 举报
回复
貌似很简单,又貌似有陷阱。建索引的问题要看数据量、查询的数据集大小、数据分布等等。而且你问的是“sql写法”,貌似答案只有一种...select count(主键) from tb where
yiyishuitian 2013-09-12
  • 打赏
  • 举报
回复
坐等老黄的回答。 我只能想到 建索引,分页的话,数据是不是太少了不值的。
引用 1 楼 DBA_Huangzj 的回复:
你这个题目说的太不清楚了,什么统计啊?求和?求平均?
deepmist 2013-09-12
  • 打赏
  • 举报
回复
引用 1 楼 DBA_Huangzj 的回复:
你这个题目说的太不清楚了,什么统计啊?求和?求平均?
哦对了,忘记说了 就是统计满足对应条件的记录数
deepmist 2013-09-12
  • 打赏
  • 举报
回复
哦对了,忘记说了 就是统计满足对应条件的记录数
發糞塗牆 2013-09-12
  • 打赏
  • 举报
回复
你这个题目说的太不清楚了,什么统计啊?求和?求平均?
Q315054403 2013-09-12
  • 打赏
  • 举报
回复
Case When是正道 这个条件涵盖所有,所以索引只要有这两个字段的就OK了(索引扫描)
hgwyl 2013-09-12
  • 打赏
  • 举报
回复
看起来是有点蛋疼…… 是个坑吧?写过sql应该都能写出来 又没有说需要对这个进行优化——他么有给其他条件嘛……
Andy__Huang 2013-09-12
  • 打赏
  • 举报
回复
我认为他想考你union 和 union all会不会用。我以前民曾经遇到别人这么考我,那时我不会
select COUNT(用户编号) as count1 from UserInfo where UserSalary >9999 and UserAge >35
union all select COUNT(用户编号) as count2 from UserInfo where UserSalary >9999 and UserAge <35
union all select COUNT(用户编号) as count3 from UserInfo where UserSalary <9999 and UserAge >35
union all select COUNT(用户编号) as count4 from UserInfo where UserSalary <9999 and UserAge <35
發糞塗牆 2013-09-12
  • 打赏
  • 举报
回复
单纯SQL单表查询,貌似没啥好优化的
deepmist 2013-09-12
  • 打赏
  • 举报
回复
引用 5 楼 DBA_Huangzj 的回复:
貌似很简单,又貌似有陷阱。建索引的问题要看数据量、查询的数据集大小、数据分布等等。而且你问的是“sql写法”,貌似答案只有一种...select count(主键) from tb where
我也是这样想的,但尼玛这题目是最后一道,估计主要是想知道你对大数据查询的处理

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧