简体   繁体   English

如何有效地在SQL代码中使用联接和数据透视

[英]How can I efficiently use join and pivot in my SQL code

I have 3 tables. 我有3张桌子。 The query returned the desired result just the sorting of records. 该查询仅返回记录的排序即可返回所需的结果。 I added Order By but it did not work. 我添加了“排序依据”,但是没有用。

在此处输入图片说明

Result should be: 结果应为:

在此处输入图片说明

I got the result it is just the sorting of records. 我得到的结果只是记录的排序。 I want to order by the ID but it is not working. 我想按ID排序,但是不起作用。

QUERY: 查询:

WITH NAMES AS (

   SELECT

      P.NAMES,
      P.CODE,
      Q.NUM_TYP,
      Q.PHONE_NUM
   FROM
      dbo.NAMES P

      INNER JOIN dbo.PHONE Q 
         ON P.ID = Q.ID
      LEFT JOIN DBO.ADDRESS S
         ON P.PRSN_IK = S.PRSN_IK
      WHERE S.ADDR Is Null  

)

SELECT *    
FROM
NAMES    
PIVOT (Max(PHONE_NUM) FOR NUM_TYP IN (WORK, HOME)) R;

Appreciate any input. 感谢任何输入。 Thanks. 谢谢。

try trhis : 试试trhis:

select f1.Name, nullif(f1.code, '') Code ,
isnull(f2.phone_num, 'N/A') work_phone_num, isnull(f3.phone_num, 'N/A') home_phone_num
from Names f1
left outer join Phone f2 on f1.id=f2.id and f2.Num_type='WORK'
left outer join Adress f2b on f2.id=f2b.id and f2.num_type=f2b.add_type
left outer join Phone f3 on f1.id=f3.id and f3.Num_type='HOME'
left outer join Adress f3b on f3.id=f3b.id and f3.num_type=f3b.add_type
where f2b.id is null or f3b.id is null

given that your query is working, this should work : 鉴于您的查询正在工作,这应该工作:

;WITH NAMES AS (
SELECT
  P.NAMES,
  P.CODE,
  Q.NUM_TYP,
  Q.PHONE_NUM
FROM dbo.NAMES P
  INNER JOIN dbo.PHONE Q 
     ON P.ID = Q.ID
  LEFT JOIN DBO.ADDRESS S
     ON P.PRSN_IK = S.PRSN_IK
  WHERE S.ADDR Is Null  
), PIVOTED 
AS
(
 SELECT *
 FROM NAMES
 PIVOT (Max(PHONE_NUM) FOR NUM_TYP IN (WORK, HOME)) R
)
SELECT * FROM PIVOTED piv
inner join [dbo].[NAMES] nam
on piv.names = nam.names
ORDER BY nam.ID

I have included P.ID and wrapped everything under subquery. 我已包含P.ID,并将所有内容包装在子查询下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM