come tradurre il codice SQL & # 8220; avendo & # 8221; condizione in LinqToSQL o LinqToEntites?
-
11-07-2019 - |
Domanda
Potresti dirmi come tradurre il seguente codice SQL in Linq in SQL o Linq in entità?
Il codice SQL corretto è:
seleziona CollectId, url, userid, pubtime da Raccogli gruppo di avere url, collectid, userid, pubtime pubtime > = (seleziona max (pubtime) da raccogliere d dove d.url = collect.url) ordina per Collect.pubtime desc
Lo script della tabella del database è:
se esiste (selezionare * da sysobjects dove id = OBJECT_ID ('[Collect]') e OBJECTPROPERTY (id, 'IsUserTable') = 1) DROP TABLE [Raccogli]
CREA TABELLA [Raccogli] ([CollectId] [int] IDENTITY (1, 1) NOT NULL, [Url] [nvarchar] (200) NULL, [UserId] [nvarchar] (50) NULL, [PubTime] [datetime] NULL)
ALTER TABLE [Raccogli] CON NOCHECK ADD VINCOLO [PK_Collect] TASTO PRIMARIO SET NONCLUSTERED ([CollectId]) IDENTITY_INSERT [Raccogli] ON
INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 1, 'www.sohu.com', 'Mike', '2008-10-10 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 2, 'www.echina365.com', 'Giglio', '2008-10-15 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 3, 'www.php.com', 'Tom', '2008-10-20 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 4, 'www.echina365.com', 'Yaoming', '2008-10-23 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 5, 'www.echina365.com', 'Mike', '2008-10-25 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 6, 'www.sohu.com', 'Jack', '2008-10-26 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 7, 'www.echina365.com', 'Tracy', '2008/11/02 0:00:00 ') INSERISCI [Raccogli] ([CollectId], [url], [userid], [PubTime]) VALORI ( 8, 'www.php.com', 'Yaoming', '2008/11/05 0:00:00' )
SET IDENTITY_INSERT [Raccogli] OFF
Soluzione
Poiché il tuo " avendo " la condizione non è in realtà su una colonna aggregata, non potresti semplicemente usare la " dove " Clausola?
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
Questo ottiene lo stesso risultato dato il set di dati che hai fornito. L'istruzione LINQ diventa quindi ragionevolmente semplice:
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();
Potrei interpretare male il tuo intento però. Forse la mia versione della query non fa esattamente quello che vuoi. In tal caso, lasciami un commento e eliminerò la risposta per non confondere il problema.