--创建测试表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Score]') AND type in (N'U'))
DROP TABLE [dbo].[Score]
GO
CREATE TABLE [dbo].[Score](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[Subject] [nvarchar](50) NULL,
[Source] [numeric](18, 0) NULL
) ON [PRIMARY]
GO
--插入测试数据
INSERT INTO [Score] ([UserName],[Subject],[Source])
SELECT N'张三',N'语文',60 UNION ALL
SELECT N'李四',N'数学',70 UNION ALL
SELECT N'王五',N'英语',80 UNION ALL
SELECT N'王五',N'数学',75 UNION ALL
SELECT N'王五',N'语文',57 UNION ALL
SELECT N'李四',N'语文',80 UNION ALL
SELECT N'张三',N'英语',100
GO
--入参:
DECLARE @UserName VARCHAR(100)
DECLARE @Subject VARCHAR(100)
DECLARE @Source VARCHAR(100)
SET @UserName='张'
SET @Subject='语文'
SET @Source='70'
SELECT id, sum((CASE WHEN charIndex(@UserName,[UserName])>0 THEN 1 ELSE 0 END)
+(CASE WHEN charIndex(@Subject, [Subject])>0 THEN 1 ELSE 0 END)
+(CASE WHEN [Source]>@Source THEN 1 ELSE 0 END)
) AS cnt
INTO #temp
FROM Score GROUP BY id
SELECT * FROM Score a JOIN #temp b ON a.id=b.id ORDER BY b.cnt DESC,UserName
DROP TABLE #temp
标签:UserName,Source,UNION,关键字,Score,SQL,排序,SELECT,Subject
From: https://www.cnblogs.com/viazure/p/18068396