[英]Getting filtered results with subquery
I have a table with something like the following: 我有一张桌子,上面的东西如下:
ID Name Color
------------
1 Bob Blue
2 John Yellow
1 Bob Green
3 Sara Red
3 Sara Green
What I would like to do is return a filtered list of results whereby the following data is returned: 我想做的是返回经过过滤的结果列表,从而返回以下数据:
ID Name Color
------------
1 Bob Blue
2 John Yellow
3 Sara Red
ie I would like to return 1 row per user. 即我想返回每个用户1行。 (I do not mind which row is returned for the particular user - I just need that the [ID] is unique.) I have something already that works but is really slow where I create a temp table adding all the ID's and then using a "OUTER APPLY" selecting the top 1 from the same table, ie
(我不介意为特定用户返回哪一行-我只需要[ID]是唯一的。)我已经可以使用某些东西,但是在创建一个临时表时要添加所有ID,然后使用“外部申请”从同一表格中选择前1个,即
CREATE TABLE #tb
(
[ID] [int]
)
INSERT INTO #tb
select distinct [ID] from MyTable
select
T1.[ID],
T2.[Name],
T2.Color
from
#tb T1
OUTER APPLY
(
SELECT TOP 1 * FROM MyTable T2 WHERE T2.[ID] = T1.[ID]
) AS V2
DROP TABLE #tb
Can somebody suggest how I may improve it? 有人可以建议我如何改善它吗?
Thanks 谢谢
Try: 尝试:
WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS 'RowNo',
ID, Name, Color
FROM table
)
SELECT ID,Name,color
FROM CTE
WHERE RowNo = 1
or 要么
select
*
from
(
Select
ID, Name, Color,
rank() over (partition by Id order by sum(Name) desc) as Rank
from
table
group by
ID
)
HRRanks
where
rank = 1
If you're using SQL Server 2005 or higher, you could use the Ranking functions and just grab the first one in the list. 如果您使用的是SQL Server 2005或更高版本,则可以使用“排名”功能,只需获取列表中的第一个即可。
http://msdn.microsoft.com/en-us/library/ms189798.aspx http://msdn.microsoft.com/en-us/library/ms189798.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.