无法过滤和或多行

时间:2018-02-06 09:27:59

标签: sql-server-2008-r2

目前,我有一个表(2列ColumnName,Value),其数据如下:

ColumnName     Value
CustomerName   Facebook
CompanyName    Google

如何使用And / Or条件编写查询以满足请求:

  • 和: CustomerName ='YAHOO'且CompanyName ='Google'将返回0条记录
  • 使用或: CustomerName ='Facebook'或CompanyName ='Google'将返回2条记录

我不知道要开始。

请告知。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以研究 EAV数据模型,了解此模型可能无法很好地扩展的原因。

您可以这样查询:

declare @YourTable table (ColumnName varchar(100), Value varchar(100) primary key (ColumnName, Value));
insert into @YourTable
    select 'CustomerName', 'Facebook' union all
    select 'CompanyName', 'Google';



--with And...
select *
from    @YourTable 
where   (ColumnName = 'CustomerName' and Value = 'Yahoo') and
        (ColumnName = 'CompanyName' and Value = 'Google')

--with Or...
select *
from    @YourTable 
where   (ColumnName = 'CustomerName' and Value = 'Facebook') or
        (ColumnName = 'CompanyName' and Value = 'Google')