求:top20 order by和unionall和 top20 order by排序

guishensxy 2011-06-27 03:36:45
select top 20 a.c_gcode,b.c_name,sum(a.c_amount),sum(a.c_qtty),substring(a.c_adno,1,3)
from tb_o_sg as a,tb_gds as b
where a.c_gcode=b.c_gcode and a.c_adno like '101___' and a.c_datetime>='2011-06-01' and a.c_datetime<'2011-06-03'
group by a.c_gcode,b.c_name,a.c_adno
order by sum(a.c_amount) desc

union all

select top 20 a.c_gcode,b.c_name,sum(a.c_amount),sum(a.c_qtty),substring(a.c_adno,1,3)
from tb_o_sg as a,tb_gds as b
where a.c_gcode=b.c_gcode and a.c_adno like '102___' and a.c_datetime>='2011-06-01' and a.c_datetime<'2011-06-03'
group by a.c_gcode,b.c_name,a.c_adno
order by sum(a.c_amount) desc

其中 where a.c_adno likfe '101___' 改成 where a.c_adno likfe '102___' 我还改更多的如 103.104.105

要求:
第一个查询公式就是101中的前20 能不能和第二个查询公式102中的前20 放在一起

但union all总写不到一起 有什么方法可以写一起么。。
...全文
104 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
guishensxy 2011-06-28
  • 打赏
  • 举报
回复
怎么给老大加分呢?
guishensxy 2011-06-27
  • 打赏
  • 举报
回复
多谢老大。解决了。。
--小F-- 2011-06-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 guishensxy 的回复:]
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 3 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 4 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 5 指定任何列。
Msg 8155, Level 1……
[/Quote]
提示很明显啊 在cte里面的聚合函数所在的列加别名
guishensxy 2011-06-27
  • 打赏
  • 举报
回复
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 3 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 4 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte1' 的列 5 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte2' 的列 3 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte2' 的列 4 指定任何列。
Msg 8155, Level 16, State 2, Line 1
没有为 'cte2' 的列 5 指定任何列。
guishensxy 2011-06-27
  • 打赏
  • 举报
回复
老大还是不行。提示错误 。。难道是我的库有问题?
xuexiaodong2009 2011-06-27
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 zy112429 的回复:]

SQL code
with cte1 as
(
select top 20 a.c_gcode,b.c_name,sum(a.c_amount),sum(a.c_qtty),substring(a.c_adno,1,3)
from tb_o_sg as a,tb_gds as b
where a.c_gcode=b.c_gcode and a.c_adno like '101___' and ……
[/Quote]牛人啊
GoAwayZ 2011-06-27
  • 打赏
  • 举报
回复
with cte1 as
(
select top 20 a.c_gcode,b.c_name,sum(a.c_amount),sum(a.c_qtty),substring(a.c_adno,1,3)
from tb_o_sg as a,tb_gds as b
where a.c_gcode=b.c_gcode and a.c_adno like '101___' and a.c_datetime>='2011-06-01' and a.c_datetime<'2011-06-03'
group by a.c_gcode,b.c_name,a.c_adno
order by sum(a.c_amount) desc)
,cte2 as
(
select top 20 a.c_gcode,b.c_name,sum(a.c_amount),sum(a.c_qtty),substring(a.c_adno,1,3)
from tb_o_sg as a,tb_gds as b
where a.c_gcode=b.c_gcode and a.c_adno like '102___' and a.c_datetime>='2011-06-01' and a.c_datetime<'2011-06-03'
group by a.c_gcode,b.c_name,a.c_adno
order by sum(a.c_amount) desc
)

select * from cte1
union all
select * from cte2

34,591

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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