查询以下两个表:
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:
[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
结果产生重复,因为该表有重复项,其中StockA与StockB相关性列在一行中,而相同的相关性列在另一行中,StockB在StockA列中,反之亦然。
由于每个相关性都列出了两次,我想添加一个where子句来将结果限制为stockA在stockB之前按字母顺序排列的结果。我试过了一个<在stockA和stockB之间它并没有起作用。 SQL是否有字符串的比较运算符?
答案 0 :(得分:0)
为什么不这样做,它更有效率,不会产生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