Case或If,在SQL中选择什么

时间:2012-02-29 13:40:53

标签: sql if-statement db2 case

如何管理此查询。我想在查询中只有一个人。如果empId列中有id,那么他的名字。否则就是老板的名字。

Product empId   teamId  
----------------------
A       1       3
B       2       4
C               3
D       2       3
E               4

User Table
Id  Name
-----------
1   Jim
2   Carrey
3   Bill
4   Clinton

Team Table
Team_Id BossId
-----------
3   3
4   4    

结果如下:

Product user.name
-----------------
A       Jim
B       Carrey
C       Bill
D       Carrey
E       Clinton

4 个答案:

答案 0 :(得分:3)

使用CASECOALESCE()功能:

SELECT 
    x.Product
  , COALESCE(emp.Name, boss.Name) AS Name
FROM
    TableX AS x
  LEFT JOIN
    User AS emp
      ON emp.Id = x.empId
  LEFT JOIN
    User AS boss
      ON boss.Id = x.bossId

更新:

SELECT 
    x.Product
  , COALESCE(emp.Name, boss.Name) AS Name
FROM
    TableX AS x
  LEFT JOIN
    User AS emp
      ON emp.Id = x.empId
  LEFT JOIN
      Team As t
    JOIN
      User AS boss
        ON boss.Id = t.bossId
      ON t.team_Id = x.teamId

答案 1 :(得分:2)

这样的事情:

SELECT
    Table1.Product,
    CASE 
        WHEN Table1.empId IS NULL
        THEN Boss.name
        ELSE Emp.name
    END
FROM
    Table1
    LEFT JOIN [User] AS Emp
        ON Emp.Id =Table1.empId
    LEFT JOIN Team
        ON Team.Team_Id =Table1.teamId
    LEFT JOIN [User] AS Boss
        ON Boss.Id=Team.BossId

答案 2 :(得分:1)

SELECT Y.Product, U.Name
  FROM YourTable AS Y 
       JOIN Users AS U ON Y.empId = U.Id
UNION
SELECT Y.Product, U.Name
  FROM YourTable AS Y 
       JOIN Team AS T ON Y.teamId = T.Team_Id
       JOIN Users AS U ON T.BossId = U.Id
 WHERE Y.empId IS NULL;

答案 3 :(得分:1)

-- SET search_path='tmp';
DROP TABLE tmp.products;
CREATE TABLE products
        ( product CHAR(1)
        , emp_id INTEGER
        , team_id INTEGER
        );
INSERT INTO products(product,emp_id,team_id)
     VALUES ('A',1,3),  ('B',2,4),  ('C',NULL,3),  ('D',2,3),  ('E',NULL,4);
DROP TABLE tmp.names;
CREATE TABLE names
        (id INTEGER
        , zname varchar
        );
INSERT INTO names(id,zname)
     VALUES ( 1, 'Jim') ,( 2, 'Carrey') ,( 3, 'Bill') ,( 4, 'Clinton') ;

DROP TABLE tmp.teams;
CREATE TABLE teams
        ( team_id INTEGER NOT NULL
        , boss_id INTEGER NOT NULL
        );
INSERT INTO teams(team_id,boss_id) VALUES ( 3,4) , (4,4);


WITH lutser(prod,id,team) AS
        (
        SELECT k1.product AS prod
                , k1.emp_id AS id
                , k1.team_id AS team
        FROM tmp.products k1
        UNION
        SELECT k2.product AS prod
                , t.boss_id AS id
                , k2.team_id AS team
        FROM tmp.products k2
        JOIN tmp.teams t ON t.team_id = k2.team_id
        WHERE k2.emp_id IS NULL
        )
SELECT l.prod
        , l.id
        , l.team
        , n.zname
FROM lutser l
JOIN names n ON n.id = l.id
        ;

这个CTE递归版的额外奖励点......