符合多少条件?

时间:2018-08-10 09:35:10

标签: sql sql-server tsql

如果我使用OR将条件条件串在一起,它将返回适合任何条件的结果,对吗?

例如,如果我键入

select * from TestTable
where Color='White' or Material='Cotton' or Gender='Female'
      or Length='Short'

它将给我从1个匹配到所有4个匹配条件的结果,对吧?

有什么办法知道每个返回结果匹配多少条件?

2 个答案:

答案 0 :(得分:4)

您需要在CASE中使用SELECT表达式。也许像这样:

CASE Color WHEN 'White' THEN 1 ELSE 0 END + 
CASE Material WHEN 'Cotton' THEN 1 ELSE 0 END + 
CASE Gender WHEN 'Female' THEN 1 ELSE 0 END + 
CASE Length WHEN 'Short' THEN 1 ELSE 0 END AS WhereMatched

答案 1 :(得分:2)

一种方法是使用CASE表达式以及SUM窗口函数:

CREATE TABLE dbo.testtable(
      Color varchar(10)
    , Material varchar(10)
    , Gender varchar(10)
    , Length varchar(10)
);

INSERT INTO dbo.testtable VALUES
      ('White', 'Cotton', 'Female', 'Short')
    , ('White', 'Cotton', 'Female', 'Long')
    , ('White', 'Cotton', 'Male', 'Long')
    , ('White', 'Nylon', 'Male', 'Long')

SELECT *
    ,SUM(CASE WHEN Color='White' THEN 1 END) OVER(ORDER BY (SELECT 0)) AS ColorMatches 
    ,SUM(CASE WHEN Material='Cotton' THEN 1 END) OVER(ORDER BY (SELECT 0)) AS MaterialMatches 
    ,SUM(CASE WHEN Gender='Female' THEN 1 END) OVER(ORDER BY (SELECT 0)) AS GenderMatches
    ,SUM(CASE WHEN Length='Short' THEN 1 END) OVER(ORDER BY (SELECT 0)) AS LengthMatches
FROM TestTable
WHERE 
       Color='White'
    OR Material='Cotton' 
    OR Gender='Female'
    OR Length='Short';