4
SELECT * FROM dbo.Sample ORDER BY Site

输出:

Site Data
1   Cat
1   Mule
1   Pig
2   Giraffe
2   Dog
2   Horse
2   Mule
4   Cat
8   Dog
8   Pig
8   Mule
8   Bull
9   Bull
9   Giraffe
9   Moose

我想显示按站点排序的数据,但排除以前站点中的行。显示站点 1 中的所有项目 站点 2 中尚未在站点 1 中显示的任何项目,等等。

所以结果显示为:

Site    Data
----     ----
1   Cat
1   Mule
1   Pig
2   Dog
2   Giraffe
2   Horse
9   Moose

初始列表是从具有多个连接的查询构建的。

一个工作示例是:

SELECT * FROM dbo.Sample WHERE Site = 1
UNION
SELECT * FROM dbo.Sample WHERE Site = 2
AND Data NOT IN (SELECT Data FROM dbo.Sample WHERE Site < 2)
UNION
SELECT * FROM dbo.Sample WHERE Site = 8
AND Data NOT IN (SELECT Data FROM dbo.Sample WHERE Site < 8)
UNION
SELECT * FROM dbo.Sample WHERE Site = 9
AND Data NOT IN (SELECT Data FROM dbo.Sample WHERE Site < 9)
ORDER BY Site

我的站点列表也来自查询。

从 SiteList 中选择不同的站点

1
2
4
8
9

当然应该有一种简单有效的方法来做到这一点?

4

4 回答 4

4

这会给你想要的结果

SELECT MIN(Site) AS Site,
       Data
FROM   dbo.Sample
GROUP  BY Data
ORDER  BY Site 
于 2013-02-22T21:21:44.537 回答
4

您可以使用ROW_NUMBER

WITH CTE AS
(
   SELECT s.*,
      RN = ROW_NUMBER () OVER (PARTITION BY Data Order By Site) 
   FROM dbo.Sample s
)
SELECT * FROM CTE WHERE RN = 1
ORDER BY Site
于 2013-02-22T21:22:41.577 回答
2
SELECT * 
FROM dbo.sample a 
WHERE site = 
(SELECT min(site) 
 FROM dbo.sample b 
 WHERE a.data=b.data)
order by site

不像第一个解决方案那样优雅,但是如果您最终得到具有不同值的其他列(例如颜色)并且仍然只希望每只动物有一行,这也将起作用。

于 2013-02-22T21:35:47.877 回答
0

试试这个

SELECT min(site)
FROM dbo.sample
GROUP BY data
ORDER BY 1
于 2013-02-22T21:22:04.463 回答