我有一个名为" Majors"我希望从该列获取所有内容,但过滤掉任何具有重复的第一个字符的内容。 例如,如果我有AMST和ADIB,只有其中一个会出现,它可能是不确定的。
所以,如果我有AMST,ADIB,BIOL,CSCI,CENG,EENG,那么最终结果可能是AMST,BIOL,CENG,EENG。
我目前拥有的是:
DECLARE @VTest table(majName varchar(100))
INSERT INTO @VTest (majName)
SELECT DISTINCT TOP 5 Major FROM MajorTbl ORDER BY Major desc
--For some reason returns all the rows despite it only giving distincts (Would return AMST and ADIB, even though it should only give one of those and not both)
SELECT * FROM @VTest
WHERE SUBSTRING(majName, 1, 1) =
(SELECT DISTINCT SUBSTRING(CONVERT(varchar(100), [@VTest].majName), 1, 1) as c)
关于如何获得我想要的输出的任何想法?
答案 0 :(得分:2)
如果你只需要每行一次"那么row_number()
似乎是解决问题的明显候选人:
select t.*
from (select t.*,
row_number() over (partition by left(majName, 1) order by newid()) as seqnum
from @VTest t
) t
where seqnum = 1;
请注意,这会将SQL Server约定用于随机化行等内容。您的代码看起来像SQL Server代码。