Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Sql help

$
0
0

After getting some help here with some sql, I have populated a table with some data that I now need to present in a particular way. I don't think using a pivot will do the trick. I have four phone number fields of different categories. Some have values, some don't. I have an additional set of phone numbers that I need to slot into empty fields while maintaining the position of the original ones.

The original data looks like this:

     CustNo, Avail1, Avail2, Avail3, Avail4
     123, NULL, 888888, NULL, 888888
     124, 888888, NULL, NULL, 888888
     125, NULL, NULL, 888888, NULL

I have added extra columnS to this table to accommodate the extra phone numbers I have. This data looks like this:

     CustNo, P1, P2, P3, P4
     123, 777777, 777777, NULL, NULL
     124, 777777, NULL, NULL, NULL
     125, 777777, 777777, 777777, 777777

I need my sql to slot the new phone numbers into the available fields (NULLS) while maintaining the position of the original data. Eg

     123, 777777, 888888, 777777, 888888
     124, 888888, 777777, 777777, 888888
     125, 777777, 777777, 888888, 777777 (The final one will be ignored as there are too many)

I am battling with the best way to write the sql and I have written it several different ways. At the moment, it looks like the sql below but I don't think I'm going down the right path. Any help would be greatly appreciated.

SELECT
      PRIVATE_PHONE
      ,PRIVATE_MOBILE
      ,WORK_PHONE
      ,PRIVATE_FAX
      ,B.[1]
      ,B.[2]
      ,B.[3]
      ,B.[4]
FROM
(
                                                                  
SELECT
      CUSTOMER_NO
,CASEWHEN AVAIL1IS NOT NULL THEN 'TAKEN'ELSE'' END PRIVATE_PHONE
,CASEWHEN AVAIL2IS NOT NULL THEN 'TAKEN'ELSE ''END PRIVATE_MOBILE
,CASEWHEN AVAIL3IS NOT NULL THEN 'TAKEN'ELSE ''END WORK_PHONE
,CASEWHEN AVAIL4IS NOT NULLTHEN 'TAKEN'ELSE ''END PRIVATE_FAX
,A.[1]
,A.[2]
,A.[3]
,A.[4]
,CASEWHEN AVAIL1IS NULL THEN A.[1]ELSE''END PHONE1
--PHONE1 SHOULD NO LONGER BE AVAILABLE NOW AS THE 1ST EXTRA NUMBER WILL ALWAYS BE IN COLUMN 1

--This is the area I'm getting lost in----------------                 
      ,
CASE WHEN AVAIL1IS NOT NULL AND AVAIL2IS NULL THEN A.[1]ELSE '' END PHONE2
,CASE WHEN AVAIL1IS NOT NULL AND AVAIL2IS NOT NULLAND AVAIL3 IS NULL THEN A.[1]ELSE '' END PHONE3
,CASE WHEN AVAIL1IS NOT NULLAND AVAIL2 IS NOTNULL AND AVAIL3IS NOT NULLAND AVAIL4 IS NULL THEN A.[1]ELSE '' END PHONE4

FROM DBO.NEW_PHONE_NUMBERS A

) B

ORDERBY CUSTOMER_NO


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>