How do you compare strings in SQL by aplhabetical order?
Querying the following two tables:
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 DESCThe result produces duplicates because the table has duplicates where StockA vs StockB correlation is listed in one row and the same correlation is listed in another row that has StockB is in the StockA column and vica versa.
Since each correlation is listed twice, I figured to add a where clause to limit the results to those in which stockA is alphabetically before stockB. I tried a < between stockA and stockB and it didn't work. Does SQL have an 开发者_运维知识库comparison operator for strings?
Why not do this, it is more efficient and does not produce permutatation of 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
精彩评论