LINQ& SQL查询帮助:在两列上做一个截然不同的?

时间:2010-11-08 16:03:00

标签: sql linq

如何根据SELECT AND DISTINCT得到FromLinkID结果ToLinkID

如果我的List有以下数据,我怎样才能在LINQ中获得我的目标?

alt text

6 个答案:

答案 0 :(得分:2)

SELECT  DISTINCT FromLinkId, ToLinkId
FROM    mytable

要为(FromLinkId, ToLinkId)选择一条记录(最少id),假设为SQL Server

SELECT  *
FROM    (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY FromLinkId, ToLinkId ORDER BY id) AS rn
        FROM    mytable
        ) q
WHERE   rn = 1

答案 1 :(得分:0)

试试这个:

Select Distinct FromLinkId LinkId From MyTable 
Union 
Select Distinct ToLinkId LinkId From MyTable 

答案 2 :(得分:0)

SELECT Name, FromLinkId, ToLinkId FROM MyTable GROUP BY FromLinkId, ToLinkId -- if there are more than one record with the same (FromLinkId, ToLinkId) pair, only one of them is displayed.

答案 3 :(得分:0)

您可以执行以下操作:

SELECT MAX(ID), MAX(Name), FromLinkID, ToLinkID FROM MyTable 
GROUP BY FromLinkID, ToLinkID

甚至:

SELECT t.* FROM
(SELECT MAX(ID) as MaxID, FromLinkID, ToLinkID FROM MyTable  
GROUP BY FromLinkID, ToLinkID) d 
LEFT JOIN MyTable t ON d.MaxID=t.ID

答案 4 :(得分:0)

LINQ解决方案:

List<MyObj> distinctResults = allResults
  .GroupBy(p => new {p.FromLinkID, p.ToLinkID} )
  .Select(g => g.First())
  .ToList();

希望它对某人有所帮助。

Helpful related SO question.

答案 5 :(得分:0)

列出distinctResults = allResults   。选择(p =&gt; new {p.FromLinkID,p.ToLinkID})   。不同()   .ToList();