SQL排除先前在另一个类别中选择的行

时间:2013-02-22 21:19:02

标签: sql-server sql-server-2008

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 个答案:

答案 0 :(得分:4)

这会给你想要的结果

SELECT MIN(Site) AS Site,
       Data
FROM   dbo.Sample
GROUP  BY Data
ORDER  BY Site 

答案 1 :(得分: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

答案 2 :(得分:2)

SELECT * 
FROM dbo.sample a 
WHERE site = 
(SELECT min(site) 
 FROM dbo.sample b 
 WHERE a.data=b.data)
order by site

不如第一个解决方案那么优雅,但是如果您最终得到具有不同值的其他列(例如颜色)并且每个动物只想要一行,这也会有效。

答案 3 :(得分:0)

试试这个

SELECT min(site)
FROM dbo.sample
GROUP BY data
ORDER BY 1