选择表中的所有行,并以逗号分隔,并附带条件

时间:2019-04-08 20:58:33

标签: sql-server

客户输入票证并从列表中选择一个部门,在某些情况下还选择多个部门。我的应用程序返回每个票证ID的部门,以逗号分隔。效果很好。但是,用户可能已经从选择中选择了“所有”部门(选择ALL的DEPARTMENT_ID为'1')。然后,我需要返回“部门”表中的每个部门,并用逗号分隔。

Ticket Table
    TICKET_ID   |  ISSUE
-------------------------
       100      | Power Outage
       101      | Internet is not working

单位表:

 DEPARTMENT_ID | DEPARTMENT
 --------------------------
         1    | ALL
         2    | Accounting
         3    | Human Resources
         4    | Receiving

部门机票表

DEPARTMENT_TICKETS_ID | TICKET_ID | DEPARTMENT_ID
----------------------------------------------------------
       1              |    100    |     2
       2              |    100    |     3
       3              |    101    |     1

使用我的查询,票证100显示以下结果: 停电:会计,人力资源 如何使票证101显示以下内容: 互联网无法正常工作:全部,会计,人力资源,接收

    Select ISSUE, 
    stuff((
    SELECT ', ' + cast(Departments.DEPARTMENT as varchar(max))
    FROM Departments
    left join DepartmentTickets
    ON DepartmentTicket.TICKET_ID = TICKETS.TICKET_ID
    WHERE DepartmentTickets.TICKET_ID = TICKETS.TICKET_ID and DepartmentTickets.DEPARTMENT_ID = Departments.DEPARTMENT_ID       
    FOR XML PATH('')
    ), 1, 2, '') AS DEPARTMENTS
    FROM TICKETS
    WHERE TICKET_ID = '100'
    ORDER BY ISSUE

1 个答案:

答案 0 :(得分:1)

首先使您的内部联接变相为适当的内部联接。在ON子句中,然后添加OR,以检查部门ID为1

顺便说一句,如果ID是整数而不是字符串(看起来像是字符串),则不应将文字用单引号引起来。

SELECT t.issue, 
       stuff((SELECT ', ' + cast(d.department AS varchar(max))
                     FROM departments d
                          INNER JOIN departmenttickets dt
                                     ON dt.department_id = d.department_id
                                         OR dt.department_id = 1
                     WHERE dt.ticket_id = t.ticket_id
                     FOR XML PATH('')),
             1,
             2,
             '') departments
       FROM tickets t
       WHERE t.ticket_id = 101
       ORDER BY t.issue;

db<>fiddle