2015-07-03 28 views
1

我使用SQL Server 2012中,我有以下的樣本數據SQL查詢時,對不符合

Date  Type Symbol  Price 
6/30/1995 gaus 313586U72 109.25 
6/30/1995 gbus 313586U72 108.94 
6/30/1995 csus NES   34.5 
6/30/1995 lcus NES   34.5 
6/30/1995 lcus NYN   40.25 
6/30/1995 uaus NYN   40.25 
6/30/1995 agus SRR   10.25 
6/30/1995 lcus SRR   0.45 
7/1/1995 gaus 313586U72 109.25 
7/1/1995 gbus 313586U72 108.94 

我想篩選出來的時候象徵和價格匹配。如果類型不匹配就可以。因此,對於上述數據,我期望只看到

Date  Type Symbol  Price 
6/30/1995 gaus 313586U72 109.25 
6/30/1995 gbus 313586U72 108.94 
6/30/1995 agus SRR   10.25 
6/30/1995 lcus SRR   0.45 
7/1/1995 gaus 313586U72 109.25 
7/1/1995 gbus 313586U72 108.94 

NES和NYN已被過濾掉,因爲它們的符號和價格匹配。

我正在考慮使用分區和行號,但我不知道如何配對和過濾使用該或其他功能的行。

* ** UPDATE我會測試答覆。我應該提到我只想看到在同一天發生的符號和價格重複。另外,表被稱爲duppri

+0

我剛剛注意到你的編輯;要在同一日期查找重複項,您可以將其他條件添加到我的答案中,請參閱:http://www.sqlfiddle.com/#!6/29d67/1 – jpw

+0

@jpw我通過將您的原始查詢添加到日期行,如您所示。一個問題查詢的select 1部分有什麼作用? –

+1

當您使用'exists'時,唯一感興趣的是查詢是否返回某些內容,而不是返回的內容。使用'select 1'只是表示列不重要的一種方式,而且它使查詢更短。 – jpw

回答

6

一種方法是使用exists謂詞與相關子查詢,檢查,具體的符號有不止一個價格:

select * from table1 t 
where exists (
    select 1 
    from table1 
    where symbol = t.symbol 
    and price <> t.price); 

Sample SQL Fiddle

這將返回:

|     Date | Type | Symbol | Price | 
|------------------------|------|-----------|--------| 
| June, 30 1995 02:00:00 | gaus | 313586U72 | 109.25 | 
| June, 30 1995 02:00:00 | gbus | 313586U72 | 108.94 | 
| June, 30 1995 02:00:00 | agus |  SRR | 10.25 | 
| June, 30 1995 02:00:00 | lcus |  SRR | 0.45 | 
| July, 01 1995 02:00:00 | gaus | 313586U72 | 109.25 | 
| July, 01 1995 02:00:00 | gbus | 313586U72 | 108.94 | 

編輯:戈登Linoffs巧妙回答inspiried另一種選擇是使用avg()作爲窗口函數:

select Date, Type, Symbol, Price 
from (
    select Date, Type, Symbol, Price, avg = avg(price) over (partition by symbol) 
    from table1) a 
where avg <> price; 

編輯:有檢查,以確保在同一日期只有重複返回:http://www.sqlfiddle.com/#!6/29d67/1

+0

Upvote爲窗口函數部分。但如何使用'count distinct'作爲窗口函數? –

+0

這會更直接。 –

+0

...我只是試了一下,現在也讀了'distinct'不支持'partition by'。 (只有'count',沒有'distinct')。但也許它將成爲SQL Server的未來功能。有用戶對此已投票。 –

0

使用子選擇與GROUP BYHAVING COUNT DISTINCT相結合,找到「壞」的符號:

select * from your_table 
where symbol not in 
(
    select symbol 
    from your_table 
    group by symbol 
    having count(distinct price) > 1 
) 
2

我會接近這個利用窗口函數:

select s.* 
from (select s.*, 
      min(price) over (partition by symbol) as minprice, 
      max(price) over (partition by symbol) as maxprice 
     from sample s 
    ) s 
where minprice <> maxprice; 
+0

是不是可以使用「count distinct」作爲窗口函數,而不是使用min和max? * [注意:Upvote。應該有更多的使用窗口功能] * –

+0

Reg。 'count distinct':我剛剛發現'distinct'不支持'partition by'。 (只有'count')。也許這將是SQL Server的未來功能。有用戶投票已經。 –