希望我能正确解释。这是一些示例代码。我想要一些行数,其中几列中的值匹配。
DECLARE @myTemp TABLE
(
Author varchar(20),
Title varchar(25),
MediaType varchar(5),
ItemCount int NULL
)
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Heinlein','The Roads Must Roll', 'CD')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Heinlein','The Roads Must Roll', 'Book')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Heinlein','Time Enough for Love', 'Book')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Asimov','The Foundation Trilogy', 'CD')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Asimov','The Foundation Trilogy', 'Book')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Asimov','I Robot', 'CD')
INSERT INTO @myTemp (Author, Title, MediaType) VALUES ('Asimov','Nightfall', 'Book')
我希望能够获得看起来像这样的数据。
Author Title MediaType ItemCount
-------------------- ------------------------- --------- -----------
Heinlein The Roads Must Roll CD 2
Heinlein The Roads Must Roll Book 2
Heinlein Time Enough for Love Book 1
Asimov The Foundation Trilogy CD 2
Asimov The Foundation Trilogy Book 2
Asimov I Robot CD 1
Asimov Nightfall Book 1
像
这样的东西UPDATE @myTemp
SET ItemCount = (SELECT COUNT(1) FROM @myTemp GROUP BY Author, Title)
但是那个子查询返回多行显然不对。
答案 0 :(得分:1)
使用sql server,您可以在update语句中使用FROM并将此表链接到自身以获取每个Author,Title实例的计数。
UPDATE @myTemp
SET ItemCount = bookcount
from @myTemp as m
inner join
(SELECT Author, Title, COUNT(*) as bookcount
FROM @myTemp
group by author, title) as mt
on m.Author = mt.author and m.Title = mt.Title
不确定我理解你的结果。它更像是一个物品总数。例如,The Roads Must Roll没有2张CD。