Having one part of a SUM() equation be above a certain number - mysql

So, I currently have a SQL query that brings up a total amount for all orders for a specific customers. This equation is the following.
SUM((OrdIt.ItemPrice- OrdIt.DiscountAmount) * OrdIt.Quantity) As TotalAmount
However, I only want to display results where the initial ItemPrice is OVER 500.
Where would I put OrdIt.ItemPrice > 500 ?

You could sum a CASE expression which checks the price:
SUM((CASE WHEN OrdIt.ItemPrice > 500
THEN OrdIt.ItemPrice - OrdIt.DiscountAmount
ELSE 0 END) * OrdIt.Quantity)

Can you not issue this SQL query?
SELECT SUM((OrdIt.ItemPrice - OrdIt.DiscountAmount) * OrdIt.Quantity) As
TotalAmount
FROM OrdIt
WHERE OrdIt.ItemPrice > 500;

Related

count and sum in case statement

What is the difference below if I use case instead of sum? I believe I would get the same output?
SELECT SUM(CASE WHEN salary > 100000 THEN 1 ELSE 0 END) AS Total
SELECT COUNT(CASE WHEN salary > 100000 THEN 1 END) AS Total
SELECT COUNT(CASE WHEN salary > 100000 THEN 1 ELSE NULL END) AS Total
Thanks!
Per the other answer, all forms are equivalent. There also a couple of other form that are more compact and achieve the same result:
count_if(salary > 100000)
count(if(salary > 100000, 1))
However, the idiomatic and more general way to do this in Trino (formerly known as Presto SQL) is:
SELECT count(*) FILTER (WHERE salary > 100000) AS Total
FROM ...
See the documentation for more details about filtered aggregations.
All other forms except for the one based on SUM should, per the SQL specification, raise a warning to indicate that null values have been eliminated. This behavior is not yet implemented in Trino, but will be added at some point in the future.
The three are equivalent. All of them count the number of rows that meet the particular condition (salary > 100000). All return 0/1 and would not return NULL values for the column.
From a performance perspective, all should be equivalent as well. I have a personal preference for the first version. I consider the third to be unnecessarily verbose because else NULL is the default for a case expression.

Query - To display the Failure rate %

I have written this query to get my data, and all the data is fine.
I have one column which has either Pass Or Fail. I want to calculate the % of number of bookings that failed, and output it in a single value.
I will have to write another query to show that one number.
For example : The below data, I have 4 bookings , out which 2 failed. So 50% is the failure rate. I am omitting some columns , in the display, but can be seen in the query.
That's an aggregation over all records and simple math:
select count(case when decision = 'Fail' then 1 end) / count(*) * 100
from (<your query here>) results;
Explanation: COUNT(something) counts non null values. case when decision = 'Fail' then 1 end is 1 (i.e. not null) for failures and null otherwise (as null is the default for no match in CASE/WHEN &dash; you could as well write else null end explicitly).
Modify your original condition to the following. Notice that there is no need to wrap your query in a subquery.
CONCAT(FORMAT((100 * SUM(CASE WHEN trip_rating.rating <= 3 AND
(TIMESTAMPDIFF(MINUTE,booking.pick_up_time,booking_activity.activity_time) -
ROUND(booking_tracking_detail.google_adjusted_duration_driver_coming/60)) /
TIMESTAMPDIFF(MINUTE,booking.pick_up_time,booking_activity.activity_time)*100 >= 15
THEN 1
ELSE 0
END) / COUNT(*)), 2), '%') AS failureRate
This will also format your failure rate in the format 50.0%, with a percentage sign.

Sum of multiple rows using different cases

In my table for payment details of a shop.Here Payment is done by using credit,debit and by cash.This will represent in the table like a field "mode"
If mode=1 cash,mode=2 credit and mode=3 debit.
Now i take the daily fee details using this query
SELECT * FROM (`fee_data`) WHERE `paid_date` = '2015-20-11'
I want to get the sum of Paid amount in different modes
How can i do this..
You can try this:
SET #paid_date = '2015-01-19 00:00:00';
SELECT
SUM (CASE WHEN MODE = 1 THEN VALUE_PAYMENT ELSE 0 END) TOTAL_1,
SUM (CASE WHEN MODE = 2 THEN VALUE_PAYMENT ELSE 0 END) TOTAL_2,
SUM (CASE WHEN MODE = 3 THEN VALUE_PAYMENT ELSE 0 END) TOTAL_3
FROM (`fee_data`) WHERE `paid_date` = #paid_date;
Where value_payment is the column you store the amount paid.
You can use sum(if( in combination with grouping by date, something like this:
SELECT `paid_date`, sum(if(mode=1, `fee_data`, 0)) sumMode1,
sum(if(mode=2, `fee_data`, 0)) sumMode2,
sum(if(mode=2, `fee_data`, 0)) sumMode3
FROM (`fee_data`) group by `paid_date`
With that you will get per date one line, where you have 3 aggregated columns. For each mode you have one aggregated field. Is that what you are looking for?
Try this :
SELECT * FROM (`fee_data`) WHERE `paid_date` = '2015-20-11' AND ModeID=1
make changes in DB tables accordingly
SELECT *, SUM(paid_amount) as sum_amount FROM (fee_data) WHERE paid_date = '2015-20-11' GROUP BY mode
I think this should work

MySQL Sum positive and negative - calculate the exact total from money transactions

I have a database table full of transactions. The transactions contain negative numbers from people returning items. I would like to add up all the amount field while also subtracting the negative values of returns from the total. How can I do this and output it out?
Currently the best I can do is get:
SELECT SUM(amount)
FROM outputaddition
GROUP by SIGN(amount);
But this only puts positive and negative in the same column.
SELECT personId,SUM(CASE WHEN amount<0 THEN amount ELSE 0 END) as NegativeTotal,
SUM(CASE WHEN amount>=0 THEN amount ELSE 0 END) as PostiveTotal
FROM outputaddition
GROUP BY personID
If you want single column
SELECT personId,SUM(amount) as Total
FROM outputaddition
GROUP BY personID
try this,
SELECT SUM(amount) as ActualTotal
,Sum(Case When amount > 0 then amount else 0 end) totalOfPositiveOnly
FROM outputaddition
I'm afraid your answer is ambiguous; we're not sure exactly what you're asking.
Most simply, if "subtracting the negative values" means you just want to ignore the negative returns:
select sum(amount)
where amount > 0;

Mysql - Multiple Sum Functions in query

I have a query that has several sum functions that are the same. Would it be more efficient to run a separate sum query then bind it to my original query as a value to speed it up?
My current query
$dbquery = $dbh->prepare("
SELECT amount - (Select SUM(amountused) from tblamountused) as amountleft
FROM tblamount
WHERE amount - (Select SUM(amountused) from tblamountused) > 0
");
Maybe something like that:
SELECT amount - (Select SUM(amountused) from tblamountused) as amountleft
FROM tblamount
HAVING amountleft > 0