tags:

views:

50

answers:

1

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.

A: 

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:

select pay_type
     , sum(pay_amt) as pay_amt
  from transaction_payments
group
    by pay_type

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.

longneck
I thought it would be easier to generate the select statement from sql than hand coding all the possible payment types, especially considering they vary from one deployment to the next. My superiors thought otherwise as well though. I just like to let the machine work when I can.Thanks for the quick response.
kristofer
Gonna spend the next few days tracking down all the possible types now :(
kristofer
you don't have to hard code them. where did i say that?
longneck