SQL如何根据其他列

时间:2016-07-08 21:09:41

标签: mysql sql

我需要根据以下四个表创建报告:

Table A: Columns(record_id, contact_id, role_id)

Table B: Columns(contact_id, fname, lname)

Table C: Columns(role_id,role_description)

Table D: Columns(Record_id, date)

查询:

select d.record_id,d.date,b.fname,b.lname,c.role_description
from a,b,c,d
where a.contact_id = b.contact_id and
      a.role_id = c.role_id and
      a.role_id in('legal','finance') and
      a.record_id = d.record_id

此查询将生成多行,如下所示:

Record ID | Date   | Fname | Lname | Role | 
=============================================
1         |Jan 2   | Bob   | Smith | Legal |
----------------------------------------------
1         |Jan 2   | Jim   | Jones | Finance |  
----------------------------------------------

我需要制作的是:

-----------------------------------------------------------------------------
record ID | Date  | Legal User | Finance User |       
--------------------------------------------------------------------
1         | Jan 2 |Bob Smith   | Jim Jones   |

我理解连接和连接,但无法弄清楚如何根据角色获得一行中的2个用户。

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM
    (
       select d.record_id,d.date
          ,b.fname + b.lname AS name
          ,c.role_description + ' User' as role_description
       from a,b,c,d
       where a.contact_id = b.contact_id and
            a.role_id = c.role_id and
            a.role_id in('legal','finance') and
            a.record_id = d.record_id
    ) q
    PIVOT 
    (
       MAX(name)
       FOR role_description IN ([Legal User], [Finance User])
    )

你应该可以使用PIVOT。我知道它看起来很奇怪,因为你正在使用varchar的MAX(),但它可以这样做。

根据您对特定语法的评论,我不会简化这一点:

SELECT *
FROM
    (
       select
          d.ctx_id
          ,effective_date,
          b.first_name + b.last_name AS name
          ,c.description
       from
          ctx_contract_contacts a
          INNER JOIN ctx_contacts b
          ON a.contact_id = b.contact_id
          INNER JOIN code_lookup c
          ON a.association = c.lookup_code 
          INNER JOIN ctx_basic_info d 
          ON a.ctx_id = d.ctx_id
       where
          and a.association in(117601,117759)
    ) q 

    PIVOT
    (
       MAX(name) 
       FOR description IN ([Legal Reviewer], [NDA reviewer])
    ) p

答案 1 :(得分:0)

select d.record_id,d.date,
[legal user]=case role_id when 'legal' then b.fname +' '+b.lname
[Finance user]=case role_id when 'finance' then b.fname +' '+b.lname
from a,b,c,d
where a.contact_id = b.contact_id and
      a.role_id = c.role_id and
      a.role_id in('legal','finance') and
      a.record_id = d.record_id