如何设置一个if for a select for sql?

时间:2017-01-16 05:26:39

标签: sql sql-server sqlcommand

我有两个名为UserParentUser的表,它们之间存在一对多的关系,而多边是ParentUser表。

我在User表上写了这个选择:

select u.* from [User] u inner join ParentUser p on u.UserId=p.UserId where p.ParentId=2440

现在我想向你添加另一个列。*包含0或1.0的用户是在ParentUser中有一些孩子的用户,而对于那些没有任何孩子的用户。

如何处理?

更新

enter image description here

3 个答案:

答案 0 :(得分:3)

您需要LEFT JOIN

SELECT u.*,
       CASE
         WHEN p.ParentId IS NULL THEN 1
         ELSE 0
       END AS HasChildren
FROM   [User] u
       LEFT JOIN (SELECT DISTINCT ParentId
                  FROM   ParentUser
                  WHERE  ParentId IN (SELECT UserId
                                      FROM   ParentUser
                                      WHERE  parentId = 2440)) p
              ON u.UserId = p.ParentId 

答案 1 :(得分:1)

SELECT DISTINCT
     [UserId]       =   [u].[userid]
    ,[HasChildren]  =   CAST(ISNULL([pu].[userid], 0) AS BIT)
FROM
    [User]  AS  [u]
OUTER APPLY
    (
        SELECT [userid] FROM [ParentUser] WHERE [parentid] = [u].[userid]
    )       AS  [pu];

并且,如果您想按父ID进行过滤:

 DECLARE @ParentId INT = 2;

SELECT DISTINCT
     [UserId]       =   [u].[userid]
    ,[HasChildren]  =   CAST(ISNULL([pu].[userid], 0) AS BIT)
    ,[ChildrenId]   =   [pu].[userid]
FROM
    [user]  AS  [u]
OUTER APPLY
    (
        SELECT [userid], [parentid] FROM [ParentUser] WHERE [parentid] = [u].[userid]
    )       AS  [pu]
WHERE
        [pu].[parentid] = @ParentId;

答案 2 :(得分:0)

确定每个有孩子的用户都相当容易。以下通过确定子项数开始,但在最终输出中(使用用户的其他列)只需将其减少为:"是否有孩子?"

/************************* Set up sample data *************************/
declare @User table (
    UserId int,
    UserName varchar(10)
)
insert @User
select 1, 'A' union all
select 2, 'B' union all
select 3, 'C'

declare @ParentUser table (
    UserId int,
    ParentId int
)
insert @ParentUser
select 3, 1 union all
select 3, 2 union all
select 2, 1


/****************************** Solution ******************************/
;with ChildCounts as (
    select  p.ParentId, COUNT(*) as ChildCount
    from    @ParentUser p
    group by p.ParentId
), UsersWithHasChildren as (
    select  u.*,
            case
                when p.ChildCount > 0 then 1
                else 0
            end as HasChildren
    from    @User u
            left join ChildCounts p on
                p.ParentId = u.UserId
)
select  *
from    UsersWithHasChildren u

根据您的重复问题,确定特定父母的哪些孩子也有孩子的特殊情况是一个简单的WHERE过滤器,如下所示。

where   u.UserId in (
            select  p.UserId
            from    @ParentUser p
            where   p.ParentId = 1 /*Parametrise this value*/
        )