0

你能告诉我如何将下面的 SQL 代码翻译成 Linq To SQL 或 Linq To Entites 吗?

正确的 SQL 代码是:

select CollectId,url,userid,pubtime from Collect group by url,collectid,userid,pubtime 具有 pubtime >= (select max(pubtime) from collect d where d.url = collect.url ) 按 Collect.pubtime desc 排序

数据库表脚本是:

如果存在 (select * from sysobjects where id = OBJECT_ID('[Collect]') and OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE [Collect]

CREATE TABLE [Collect] ( [CollectId] [int] IDENTITY (1, 1) NOT NULL, [Url] [nvarchar] (200) NULL, [UserId] [nvarchar] (50) NULL, [PubTime] [datetime] NULL )

ALTER TABLE [Collect] WITH NOCHECK ADD CONSTRAINT [PK_Collect] PRIMARY KEY NONCLUSTERED ([CollectId] ) SET IDENTITY_INSERT [Collect] ON

插入 [Collect] ([CollectId],[Url],[UserId],[PubTime]) 值 (1,'www.sohu.com','Mike','2008-10-10 0:00:00')插入 [Collect] ([CollectId],[Url],[UserId],[PubTime]) 值 (2,'www.echina365.com','Lily','2008-10-15 0:00:00')插入 [Collect] ([CollectId],[Url],[UserId],[PubTime]) 值 (3,'www.php.com','Tom','2008-10-20 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES (4,'www.echina365.com','姚明','2008-10-23 0:00:00')插入 [Collect] ([CollectId],[Url],[UserId],[PubTime]) 值 (5,'www.echina365.com','Mike','2008-10-25 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES (6,'www.sohu.com','Jack','2008-10-26 0:00:00') 插入 [Collect] ([CollectId],[Url],[UserId],[PubTime]) 值 (7,'www.echina365.com','Tracy',' 2008-11-2 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES (8,'www.php.com','YaoMing',' 2008-11-5 0:00:00')

SET IDENTITY_INSERT [收集] 关闭

4

1 回答 1

2

由于您的“拥有”条件实际上不在聚合列上,所以您不能只使用“where”子句吗?

select distinct CollectId, url, userid, pubtime
from Collect
where pubtime >= (select max(pubtime) from collect d where d.url = collect.url)
order by Collect.pubtime desc

给定您提供的数据集,这将得到相同的结果。然后 LINQ 语句变得相当简单:

var rows = (from c in Collect
where c.PubTime >= (
    from d in Collect
    where d.Url == c.Url
    select d.PubTime).Max()
orderby c.PubTime descending
select c).Distinct();

不过,我可能会误解您的意图。也许我的查询版本并不能完全满足您的要求。如果是这样,请给我留言,我将删除答案,以免混淆问题。

于 2008-11-26T05:21:08.657 回答