My problem is that this application is deployed with a lot of different payment options in mind, and those payment options vary from one deployment to the next.
My question is, how do I make a set of results become my select statement?
SELECT DISTINCT(CONCAT('SUM(IF(pay_type = "',pay_type,'", pay_amt,0)) AS `',pay_type,'`')) as queryFields
FROM transaction_payments;
Which lends me this result:
SUM(IF(pay_type = "Cash", pay_amt,0)) AS `Cash`, SUM(IF(pay_type = "Credit Card", pay_amt,0)) AS `Credit Card`
SUM(IF(pay_type = "Discount %", pay_amt,0)) AS `Discount %`, SUM(IF(pay_type = "Gift Card", pay_amt,0)) AS `Gift Card`
SUM(IF(pay_type = "Coupon", pay_amt,0)) AS `Coupon`
SUM(IF(pay_type = "Gift Certificate", pay_amt,0)) AS `Gift Certificate`
SUM(IF(pay_type = "Discount Amt.", pay_amt,0)) AS `Discount Amt.
That becomes my select statement in the following query, but the code to do this is quite cumbersome. I want to know if this is possible to do in a single query without any help from the application code.
using SQL to build SQL? ew. *shudder*
i would propose that your approach is wrong. instead of getting everything in one row, you should instead get it in multiple rows:
if you want to put that in a horizontal table, then do it in your host language.
if you’re trying to use this in yet another query, then you need to supply more context.