Question

I have two tables, arrc_PurchActivity and arrc_Voucher. The purchase activity table contains multiple records per purchase, tied together by the credit card authorization. I need to return a single row per purchase, plus pull in a field from the voucher table. If I just grab a few fields from the purchase activity table, like this:

SELECT group_concat( VoucherID ) , CcAuthCode FROM arrc_PurchaseActivity GROUP BY CcAuthCode

it works fine, returning something like this:

group_concat( VoucherID )  | CcAuthCode
=========================================
610643,611139,610642       | 8LUPDN

What I need to do is pull in another contatenated field (VoucherNbr), this time from the arrc_Voucher table, where the voucher table's VoucherID is equal to the purchase table's VoucherID. In this case, because VoucherID is a concatenation, I need to return a concatenated column of VoucherNbr for each VoucherID in the concatenated column. Clear as mud, right? What I need would look like this:

group_concat( VoucherID )  | group_concat( VoucherNbr)  |  CcAuthCode
===========================|============================|=============
610643,611139,610642       | 123,456,789                |  8LUPDN 

In other words, the VoucherNbr for VoucherID 610643 is 123, VoucherNbr for 611139 is 456, etc.

Can anyone help me out? This is way over my head...

Was it helpful?

Solution

Use:

   SELECT pa.ccauthcode,
          GROUP_CONCAT(DISTINCT pa.voucherid) AS voucherids,
          GROUP_CONCAT(v.vouchernbr) AS vouchernbrs
     FROM ARRC_PURCHASEACTIVITY pa 
LEFT JOIN ARRC_VOUCHER v ON v.voucherid = pa.voucherid
 GROUP BY pa.ccauthcode

I specified the DISTINCT in the GROUP_CONCAT for the voucherid's because it's possible you'd have multiple vouchernbr's to a voucherid. If not, remove the DISTINCT.

The LEFT JOIN ensures you'll get ARRC_PURCHASEACTIVITY records that do not have supporting records in ARRC_VOUCHER. Change "LEFT JOIN" to "JOIN" if you don't want this behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top