用户在同一行上使用自定义列的SQL组表

时间:2017-08-09 21:31:01

标签: sql sql-server

我有3张桌子

PATIENT

patientid name   comment  result
--------------------------------
1         davis  test     p
2         brown  test     p
3         mike   test     p

电话类型

phone_id patient_id phone_type 
-------------------------------
3324       1          1 
3325       1          4
5467       2          1

电话详情

phone_id  number
-----------------------
3324      8253322
3325      180040204
5467      5674543

目标是根据电话类型的值(1 =电话,4 =传真)在select语句上添加一列,并对列进行分组,以便电话和 传真在同一条线上,而不是交替。

期望的结果:

name   phone      fax         comment result
---------------------------------------------
davis  8253322    180040204   test       p
brown  5674543    null        test       p
mike   null       null        test       p

到目前为止我有这个

select 
    a.name, a.comment, a.result,
    (CASE WHEN (b.phone_type = 1) THEN c.number ELSE NULL END) AS Phone
    (CASE WHEN (b.phone_type = 4) THEN c.number ELSE NULL END) AS Fax

问题在于它不会由用户对值进行分组。

    name   phone      fax         comment result
    -----------------------------------------------
    davis  8253322    null        test       p
    davis  null       180040204   test       p
    mike   null       null        test       p

3 个答案:

答案 0 :(得分:1)

如果我们可以假设每个名字有1个电话/传真。

mymodule.mymodule_native.A

如果不是......那么根据类型将电话和传真分成两个数据集,并为每个集合生成行号。然后在patentId和行号上使用完全外连接。

select a.name
     , a.comment
     , a.result
     , max(CASE WHEN (b.phone_type = 1) THEN c.number ELSE NULL END) AS Phone
     , max((CASE WHEN (b.phone_type = 4) THEN c.number ELSE NULL END) AS Fax
FROM...
GROUP BY a.name
     , a.comment
     , a.result

答案 1 :(得分:1)

如果您确定最多只有一个值用于电话或传真,则可以使用聚合功能。

select a.name, a.comment, a.result,
       Min((CASE WHEN (b.phone_type = 1) THEN c.number ELSE NULL END) AS Phone,
Min((CASE WHEN (b.phone_type = 4) THEN c.number ELSE NULL END)) AS Fax
FROM (...)
GROUP BY a.name, a.comment, a.result

答案 2 :(得分:1)

您可以使用以下SQL语句

WITH patient_phone AS (
SELECT a.name,
       a.comment,
       a.result,
       (CASE WHEN (b.phone_type = 1) THEN c.number ELSE NULL END) AS Phone,
       (CASE WHEN (b.phone_type = 4) THEN c.number ELSE NULL END) AS Fax
  FROM patient a
  LEFT OUTER JOIN phone_type b
    ON a.patient_id = b.patient_id
  LEFT OUTER JOIN phone_details c
    ON b.phone_id = c.phone_id
 GROUP BY a.name,
          a.comment,
          a.result,
          b.phone_type,
          c.number
) 

SELECT name,       
       MAX(phone) phone,
       MAX(fax) fax,
       comment,
       result
  FROM patient_phone
 GROUP BY name,
          comment,
          result

结果

name    phone   fax         comment result
brown   5674543 NULL        test    p
davis   8253322 180040204   test    p
mike    NULL    NULL        test    p