0

I have 2 tables one stores Retailers info (Store Name, Address, Post Code) I then have a Contact table that stores personal details Name, Telephone, Email Address.

I'm exporting data, but because I could have more than one contact for a Retailer the export is duplicating rows for each contact/retailer.

for example:
Another Retailer, 26 Lime Street,London,Anna Triffo,0207 4932678,anna@another.com
Another Retailer, 26 Lime Street,London,Jane Hall,,

What I would like do is for each contact place in a separate column(s) ie: RetailerName,TradingName, AddressLine1, AddressLine2,AddressLine3,AddressLine4, Town, Country,Contact1, Contact2, Contact3,Contact4,Tel1,Tel2,Tel3,Tel4,Email1 Email2, Email3

so the above example will look like:
Another Retailer, 26 Lime Street,London,Anna Triffo,0207 4932678,anna@another.com,Jane Hall,,

the output will be:
HeadOffice_YN, HeadOfficeId_N_R, ReferenceId, RetailerName, TradingName AddressLine1, AddressLine2, Contact1, Tel1, Email1, Contact2, Tel2, Email2, IBAN, BIC Rebate, RebateCalc, VATRegNo

and my select:

SELECT 
OL_HO_YN as 'HeadOffice_YN', 
SageX3ID as 'HeadOfficeId_N_R', 
tblBusinessPartner.BP_ID as 'ReferenceId', 
BP_NAME,
OL_NAME as 'RetailerName', 
OL_FULL_NAME as 'TradingName',
 @num_street_lines := 1 + LENGTH(OL_ADDRESS) - LENGTH(REPLACE(OL_ADDRESS, '\n', '')) AS num_street_lines,
    SUBSTRING_INDEX(OL_ADDRESS, '\n', 1) AS AddressLine1,
    IF(@num_street_lines > 1, SUBSTRING_INDEX(SUBSTRING_INDEX(OL_ADDRESS, '\n', 2), '\n', -1), '') AS AddressLine2,
    IF(@num_street_lines > 2, SUBSTRING_INDEX(SUBSTRING_INDEX(OL_ADDRESS, '\n', 3), '\n', -1), '') AS AddressLine3,
    RetailerCountry.CO_NAME as 'Country',
    if(OL_TOWN Is Null, '', OL_TOWN) AS 'Town', 
    if(BP_CREATED_DATE is null,'',BP_CREATED_DATE) as 'DateJoined_D',
    if(Contact.LastName is Null, Contact.FirstName, concat(Contact.FirstName, ' ', Contact.LastName)) as Contact1,
    Contact.TelNo as 'Tel1' , Contact.EmailAddress as 'Email1',
    #Add More Contact Details here
    BP_IBAN as 'IBAN', 
    BP_BIC as 'BIC',
    BP_REBATE as 'Rebate',
    tblCheckCodes.CC_Description as 'RebateCalc',
    OL_VAT_REG_NO as 'VATRegNo'

 FROM gbtfco_GBTF003L.tblBusinessPartner
join tblOutlet on BP_ID = OL_HO_BP_ID
join tblTerminal on OL_ID = TE_OL_ID
join tblCountry RetailerCountry on OL_CO_ID = CO_ID
join tblCheckCodes on tblBusinessPartner.BP_REBATE_CALC = tblCheckCodes.CC_CheckCode
left join ContactDetails Contact on tblOutlet.OL_ID = Contact.OL_ID 

Thanks
Darren

Darren
  • 1
  • 1
  • 5
  • that's creating a pivot. I'de recommend you follow this question : https://stackoverflow.com/questions/7674786/mysql-pivot-table – Guy Louzon Sep 28 '18 at 14:40
  • Possible duplicate of [MySQL pivot table](https://stackoverflow.com/questions/7674786/mysql-pivot-table) – Guy Louzon Sep 28 '18 at 14:40

0 Answers0