后面跟个数量(小问题)

iey000 2010-09-17 02:43:52
表a:

---------------------------
id num
A 10
A 11
B 34
A 88
B 23
---------------------------

我现在想对表A进行检索,想要的结果是:

---------------------------
id num order
A 10 3
A 11 3
A 88 3
B 34 2
B 23 2
---------------------------

意思应该很简单吧,我想在后面加个count(id)显示出来,怎么写?
...全文
55 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
envykok 2010-09-19
  • 打赏
  • 举报
回复


if object_id('DurationSGDB.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
id char(2),
num int
)
go
--插入测试数据
insert into tb select 'A',10
union all select 'A',11
union all select 'B',34
union all select 'A',88
union all select 'B',23
go



SELECT tb.id, tb.num, tb_2.[order]
FROM tb
INNER JOIN
(SELECT id,COUNT(*) AS [order] FROM tb GROUP BY id) AS tb_2 ON tb.id=tb_2.id
abuying 2010-09-19
  • 打赏
  • 举报
回复


select a.id,a.name,b.order from tb a inner join (select id,count(id) as order from tb group by id ) as b on
a.id=b.id
喜-喜 2010-09-17
  • 打赏
  • 举报
回复
use test
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
id char(2),
num int
)
go
--插入测试数据
insert into tb select 'A',10
union all select 'A',11
union all select 'B',34
union all select 'A',88
union all select 'B',23
go
--代码实现

select *,[order]=(select count(*) from tb where [id]=t.[id])
from tb t

/*测试结果

id num order
---------------------
A 10 3
A 11 3
B 34 2
A 88 3
B 23 2

(5 行受影响)
*/
王向飞 2010-09-17
  • 打赏
  • 举报
回复

--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:[TB]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]')
AND type in (N'U'))
DROP TABLE [TB]
GO

---->建表
create table [TB]([id] varchar(1),[num] int)
insert [TB]
select 'A',10 union all
select 'A',11 union all
select 'B',34 union all
select 'A',88 union all
select 'B',23
GO



--> 查询结果
SELECT * FROM [TB]

SELECT [TB].id,[TB].num ,T.[order]
FROM [TB],(select id,COUNT(1) as [order] from TB a group by id)T
where TB.id=T.id
--> 删除表格
--DROP TABLE [TB]

22,209

社区成员

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

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