这个语句应该怎么写?

assiwe 2011-01-14 04:09:09
假设表A里有3个字段 ColA,ColB,ColC

我要取 select ColB,ColC from 表A Group By ColA;
其中 ColB,ColC是随便一条记录都可以,但是必须是同一条记录的


比如 ColA ColB ColC
1 2 1
2 3 1

我希望的结果 可以是 1.2.1 或者 2.3.1,但是不能是 1.3.1
并且不能使用游标 存储过程 或临时表,因为没有权限.
应该怎么写?


谢谢各位了.


...全文
68 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2011-01-14
  • 打赏
  • 举报
回复


declare @table table (A int,B int,C int)
insert into @table
select 1,2,1 union all
select 2,3,1 UNION ALL
SELECT 2,3,2 UNION ALL
SELECT 2,1,2

SELECT aa.a,aa.b,MIN(c) AS c FROM (
select * from @table t where b=
(select max(b) from @table where A=t.A)
) aa GROUP BY aa.a,aa.b order by aa.a

只能再嵌套一次,可以解决!!!
叶子 2011-01-14
  • 打赏
  • 举报
回复
这个问题出在需求上:
declare @table table (A int,B int,C int)
insert into @table
select 1,2,1 union all
select 2,3,1 UNION ALL
SELECT 2,3,2 UNION ALL
SELECT 2,1,2

select * from @table t where b=
(select max(b) from @table where A=t.A) order by a

例如上面的数据,
按a分类后,b有两个3,c有两个2,按谁取都取2条
brownhwy 2011-01-14
  • 打赏
  • 举报
回复
我给你留了言。象下面的例子就不正确了。

declare @table table (A int,B int,C int)
insert into @table
select 1,2,1 union all
select 2,3,1 UNION ALL
SELECT 2,3,2

select * from @table t where b=
(select max(b) from @table where A=t.A) order by a
叶子 2011-01-14
  • 打赏
  • 举报
回复

order by是排序
where A=t.A 相对于分组。
brownhwy 2011-01-14
  • 打赏
  • 举报
回复
怎么觉得你写的好象有些问题,最后只有Order by A,并没有按A分组,对楼主这个例子似乎正确,但是如果数据很多的话,A,B,C,有很多重复的就不正确了。
楼主没有说明表的主码。其实建视图这个问题应该简单。
[Quote=引用 4 楼 maco_wang 的回复:]
SQL code

declare @table table (A int,B int,C int)
insert into @table
select 1,2,1 union all
select 2,3,1 UNION ALL
SELECT 2,2,2

select * from @table t where b=
(select max(b) from @table wh……
[/Quote]
assiwe 2011-01-14
  • 打赏
  • 举报
回复
谢谢1楼的
叶子 2011-01-14
  • 打赏
  • 举报
回复

declare @table table (A int,B int,C int)
insert into @table
select 1,2,1 union all
select 2,3,1 UNION ALL
SELECT 2,2,2

select * from @table t where b=
(select max(b) from @table where A=t.A) order by a

/*
A B C
----------- ----------- -----------
1 2 1
2 3 1
*/

你说的是按A分组
ws_hgo 2011-01-14
  • 打赏
  • 举报
回复
没有看懂??
AcHerat 元老 2011-01-14
  • 打赏
  • 举报
回复
select top 1 colb,colc from a where a.cola = '...'
叶子 2011-01-14
  • 打赏
  • 举报
回复

declare @table table (A int,B varchar(7),C int)
insert into @table
select 1,'2009-06',1 union all
select 2,'2009-06',2 union all
select 2,'2009-07',3 union all
select 3,'2009-06',2

select * from @table t where b=
(select max(b) from @table where A=t.A) order by a

/*
A B C
----------- ------- -----------
1 2009-06 1
2 2009-07 3
3 2009-06 2
*/


你改下字段名和表名就可以了

34,593

社区成员

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

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