带自定义字段的SQL查询过滤器

时间:2016-01-12 14:37:42

标签: sql sql-server

下面的代码用于检测是否存在userid = 1 followerid = 2 AND userid = 2 followerid = 1,然后自定义列'bool'将返回TRUE。 但是,不知怎的,我无法摆脱额外的行。 任何更好的建议或建议表示赞赏。谢谢。

SELECT DISTINCT a.id, a.userid, a.followerid, 
CASE WHEN b.userid=a.followerid AND b.followerid=a.userid 
     THEN 'TRUE' ELSE 'FALSE' END AS bool 
FROM tableUserfollow AS a, tableUserfollow AS b
where a.userid=1

tableUserFollow:

id  userid  followerid
1       1       2
2       3       4   
3       1       4
4       5       1
5       2       1

输出结果应为:

1   1   2   TRUE
3   1   4   FALSE

而不是:

1   1   2   FALSE
1   1   2   TRUE
3   1   4   FALSE

2 个答案:

答案 0 :(得分:0)

如果您想知道相互关系是否存在,那么我认为最简单的方法是使用相关子查询,left joinouter apply

select uf.*, coalesce(flag, 'FALSE') as 
from tableUserfollow uf outer apply
     (select 'TRUE' as flag
      from tableUserfollow uf2
      where uf2.userId = uf.followerId and uf2.follwerId = uf.userId
     ) f;

join看起来像:

select uf.*,
       (case when uf2.userId is null then 'FALSE' else 'TRUE' end)
from tableUserfollow uf left join
     tableUserfollow uf2
     on uf2.userId = uf.followerId and uf2.follwerId = uf.userId

答案 1 :(得分:0)

DECLARE @sql AS nvarchar(MAX);
DECLARE @Search AS nvarchar(MAX);
DECLARE @AllFiels Varchar(max);
DECLARE @FixedField Varchar(max);

 SET @FixedField=( SELECT 
    ISNULL(( STUFF( 
    ( 
    SELECT  ', '+(a.value) FROM vwCustomColumns a
    WHERE a.Name  IN (SELECT items FROM dbo.Split(CustomReports.ReportFixedFields,',') )
    FOR    XML path('')
    )
    , 1,1,''))  ,'cR.ContractID [Contract ID]') FixedField

    FROM CustomReports WHERE CustomReportId=@CustomReportId )

  SET @AllFiels=@FixedField;


    SET @sql ='SELECT count(*) OVER()  AS Maxcount ,'+@AllFiels+'
    FROM  vwRequestLatest cR 
    INNER JOIN MasterUsers ON MasterUsers.UsersId = cR.Addedby
    LEFT OUTER JOIN RequestTemplate cte ON cte.ContractTemplateId=cR.RequestTemplateId
    LEFT OUTER JOIN CountryMaster co ON co.CountryId=cR.CountryId
    ORDER BY
';  

IF (@SortColumn = '') 
BEGIN
    IF (@Direction = 0)
    SET @sql =@sql  + ' cR.RequestId ASC '
    ELSE
    SET @sql =@sql  + ' cR.RequestId DESC '
END
ELSE IF (@SortColumn = 'Request ID') 
BEGIN
    IF (@Direction = 0)
    SET @sql =@sql  + ' cR.RequestId ASC '
    ELSE
    SET @sql =@sql  + ' cR.RequestId DESC '
END

SET @sql =@sql  +'OFFSET ( '+CONVERT(VARCHAR(100),@PageNo)+' - 1 ) * '+CONVERT(VARCHAR(100),@RecordsPerPage)+' ROWS FETCH NEXT '+CONVERT(VARCHAR(100),@RecordsPerPage)+' ROWS ONLY'

EXEC(@sql);