I have a very difficult (for me) mysql query I'm trying to write -- I'm so very very close besides one little part. Here's the deal-- I have a table of transactions and a table of plants, and I'm trying to get a "leaderboard" together which will tabulate all of the transactions and the costs and calculate total revenues and开发者_如何学Python profit margins. Here's the relevant fields (modified names to make it simpler here):
TABLE transactions:
username | user_city | total_sale | qty_sold
============================================
TABLE plants:
plant_city | plant_base_cost
So I've been able to calculate everything I need to know about the sale with a pretty good-sized query, which results in this (two example rows):
username |price | user_city | plant_city | base_cost | qty | cost | profit
=======================================================================================
AndyHabs | 1140 | 1 | 1 | 65 | 6 | 390 | 750
AndyHabs | 1000 | 1 | 5 | 100 | 5 | 500 | 500
Pretty simple, right? I just need to sum the relevant fields and group them by username--except here's the issue! If the user_city is DIFFERENT than the plant_city, I need to multiply the base cost by 1.6... I have NO IDEA how to incorporate this condition into my query--it was pretty simple to perform a basic calculation on a field, but is there a way to incorporate a condition like this in my statement?
I have no problem inherently just doing this in a PHP script--but if this table gets much bigger it'll take a really long time, and I would love to use some nifty pagination scripts which would make it nice to just get the data I need straight up from MySQL.
Thanks in advance!
Use a CASE expression in the calculation.
精彩评论