简体   繁体   中英

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

I have 3 tables. 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.

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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