2010-12-31 11 views
0

Abfragen von den beiden folgenden Tabellen:Wie vergleicht man Zeichenketten in SQL nach aphabetischer Reihenfolge?

CREATE TABLE [dbo].[MTCorrelations](

[CorrelationID] [int] IDENTITY(1,1) NOT NULL, 
[StockA] [nvarchar](5) NOT NULL, 
[StockB] [nvarchar](5) NOT NULL, 
[Correlation] [float] NOT NULL, 
[LengthStr] [nvarchar](5) NOT NULL, 
[Date] [datetime] NOT NULL 

)

CREATE TABLE [dbo].[Industries](

[IndustryID] [int] IDENTITY(1,1) NOT NULL, 
[Symbol] [nvarchar](5) NOT NULL, 
[Sector] [nvarchar](50) NULL, 
[Industry] [nvarchar](50) NULL 

)

with this query:

Select StockA, StockB, Correlation, LengthStr From MTCorrelations
WHERE
StockA IN
(Select Symbol From
Industries WHERE Industry = 'Money Center Banks')
AND
StockB IN
(Select Symbol From
Industries WHERE Industry = 'Money Center Banks')
ORDER BY Correlation DESC

Das Ergebnis produziert Dubletten, da die Tabelle Dubletten aufweist, wo stocka vs StockB Korrelation in einer Reihe und die gleiche Korrelation aufgeführt ist, wird in einer anderen Zeile aufgelistet, die StockB in hat, ist die StockA-Spalte und umgekehrt.

Da jede Korrelation zweimal aufgeführt ist, habe ich eine Where-Klausel hinzugefügt, um die Ergebnisse auf diejenigen zu beschränken, in denen stockA alphabetisch vor stockB steht. Ich habe eine < zwischen stockA und stockB versucht und es hat nicht funktioniert. Hat SQL einen Vergleichsoperator für Strings?

+0

Ah, die berühmte Computersoftware Problem: „Es hat nicht funktioniert“. Interessieren Sie sich für weitere Details? –

Antwort

0

Warum dies nicht tun, ist es effizienter und produzieren nicht permutatation von A/B:

SELECT StockA, StockB, Correlation, LengthStr From MTCorrelations 
WHERE StockA < StockB AND -- This is to remove the permutations 
    EXISTS     -- Fast check for StockA being within constraints 
    (SELECT * 
    FROM Industries 
    WHERE Industry = 'Money Center Banks' AND 
     Symbol = StockA) AND 
    EXISTS     -- Fast check for StockB being within constraints 
    (SELECT * 
    FROM Industries 
    WHERE Industry = 'Money Center Banks' AND 
     Symbol = StockB)  
ORDER BY Correlation DESC 
+0

Das ist im Grunde, was er versucht zu tun. 'IN' und' EXISTS' erhalten [genau den gleichen Plan] (http://sqlinthewild.co.za/index.php/2009/08/17/exists-vs-in-/) –