Say, I got these two tables....
Table 1 : Hotels
hotel_id hotel_name
1 abc
2 xyz
3 efg
Table 2 : Payments
payment_id payment_date hotel_id total_amt comission
p1 23-03-2010 1 100 10
p2 23-03-2010 2 50 5
p3 23-03-2010 2 200 25
p4 23-03-2010 1 40 2
Now, I need to get the following details from the two tables
Given a particular date (say, 23-03-2010), the sum of the total_amt for each of the hotel for which a payment has been made on that particular date.
All the rows that has the date 23-03-2010 ordered according to the hotel name
A sample output is as follows...
+------------+------------+------------+---------------+
| hotel_name | date | total_amt | commission |
+------------+------------+------------+---------------+
| * abc | 23-03-2010 | 140 | 12 |
+------------+------------+------------+---------------+
|+-----------+------------+------------+--------------+|
|| paymt_id | date | total_amt | commission ||
|+-----------+------------+------------+--------------+|
|| p1 | 23-03-2010 | 100 | 10 ||
|+-----------+------------+------------+--------------+|
|| p4 | 23-03-2010 | 40 | 2 ||
|+-----------+------------+------------+--------------+|
+------------+------------+------------+---------------+
| * xyz | 23-03-2010 | 250 | 30 |
+------------+------------+------------+---------------+
|+-----------+------------+------------+--------------+|
|| paymt_id | date | total_amt | commission ||
|+-----------+------------+------------+--------------+|
|| p2 | 23-03-2010 | 50 | 5 ||
|+-----------+------------+------------+--------------+|
|| p3 | 23-03-2010 | 200 | 25 ||
|+-----------+------------+------------+--------------+|
+------------------------------------------------------+
Above the sample of the table that has to be printed...
The idea is first to show the consolidated detail of each hotel, and when the '*' next to the hotel name is clicked the breakdown of the payment details will become visible... But that can be done by some jquery..!!! The table itself can be generated with php...
Right now i am using two separate queries : One to get the sum of the amount and commission grouped by the hotel name. The next is to get the individual row for each entry having that date in the table. This is, of course, because grouping the records for calculating sum() returns only one row for each of the hotel with the sum of the amounts...
Is there a way to combine these two queries into a single one and do the operation in a more optimized way...??
Hope i am being clear.. Thanks for your time and replies...
EDIT : Added Queries Too
Query to get the sum()
SELECT DATE_FORMAT($payments.payment_date, '%d-%m-%Y %T') as payment_date,
$payments.payment_id AS payment_id,
$payments.payment_amount AS payment_amount,
$payments.agent_commision AS commision,
$payments.comm_percentage AS percentage,
$hotels.hotel_name AS hotel
SUM($payments.payment_amount) AS tot_amt
SUM($payments.agent_commision) AS tot_ag_comsn
FROM $payments
JOIN $hotels
ON $payments.hotel_id = $hotels.hotel_id
WHERE DATE_FORMAT(payment_date,'%d-%m-%Y') = '$date_report'
GROUP BY $payments.hotel_id
ORDER BY $payments.payment_date ASC
Query to get the individual rows
SELECT DATE_FORMAT($payments.payment_date, '%d-%m-%Y %T') as payment_date,
$payments.payment_id AS payment_id,
$payments.payment_amount AS payment_amount,
$payments.agent_commision AS commision,
$payments.comm_percentage AS percentage,
$hotels.hotel_name AS hotel
FROM $payments
JOIN $hotels
ON $payments.hotel_id = $hotels.hotel_id
WHERE DATE_FORMAT(payment_date,'%d-%m-%Y') = '$date_report'
GROUP BY $payments.payment_date
ORDER BY $payments.payment_date ASC
I add the rows returned by the two queries in two separate temporary tables and then use php to print the table as shown above...
EDIT 2 : And also, appreciate if someone suggests a better title for this post... ;)
This is the domain of report writers, or equivalent logic in a programming language.
Related
Following is my scenario
I have tables named
Products
id | name | count | Price
-------------------------
1 | meat | 1 | 10
Users
id | name | balance
-----------------
1 | Tim | 10
2 | Joe | 10
Work flow
select products if count >= 1,
reduce user's balance and count = count - 1
if no_balance or count < 1 throw error
Let's say if both users placing an order for 1 product at exact same time, products table count updates to -1, means query executes for both users.
Products
id | name | count | Price
-------------------------
1 | meat | -1 | 10
During placeing of an order,I have used the below query to select matching products
Select * from products where count >= 1 and price >= 10
Also, if users place orders with even little time difference, the expecting output gathered.
Is there any solution to this ?
You should consider use lock for each row, for example.
Select * from products where count >= 1 and price >= 10 FOR UPDATE.
But in your scenario, I advice you use Redis to do that.
How to design a second kill system for online shop
A more generic title for this post would be
MySql Sum different columns in same table based on value of another row, group by yet another row
I have a table of employee expenses:
id | employee_id | expense_cat_id | expense_amount |
1 | 11 | 1 | 100 |
2 | 11 | 1 | 200 |
3 | 12 | 1 | 120 |
4 | 12 | 1 | 140 |
5 | 11 | 2 | 5 |
6 | 12 | 2 | 8 |`
and I want to produce a report like this:
Employee Id | Expense Cat 1 Total Amount | Expense Cat 2 Total Amount
11 | 300 | 5
12 | 260 | 8
So initially I thought I could use 2 table aliases for the same table like this:
SELECT
employee_id,
sum(expense_cat_1.expense_amount) as expense_1_total,
sum(expense_cat_2.expense_amount) as expense_2_total
FROM
expenses as expense_cat_1 where expense_cat_1.expense_cat_id=1 ,
expenses as expense_cat_2 where expense_cat_2.expense_cat_id=2
group by employee_id
but this was not correct Sql Syntax, which makes sense to me.
So I thought I could do two joins on between employee table and the expenses table:
SELECT
employees.id as employee_id,
sum(expenses_cat_1.expense_amount) as expense_1_total,
sum(expenses_cat_2.expense_amount) as expense_2_total
FROM employees
join expenses as expenses_cat_1 on employees.id = expenses_cat_1.employee_id and expenses_cat_1.expense_cat_id=1
join expenses as expenses_cat_2 on employees.id = expenses_cat_2.employee_id and expenses_cat_2.expense_cat_id=2
group by employees.id
Which comes close, but is wrong:
employee_id | expense_1_total | expense_2_total
11 | 300 | 10
12 | 260 | 16
as the expense 2 total is doubled! I think this is because the join on shows up two rows for each of the two expenses with category 1, and sums them.
I also tried a sub-query approach:
SELECT (SELECT sum(expense_amount)
FROM expenses
WHERE expense_cat_id = 1) AS sum1 ,
(SELECT sum(expense_amount)
FROM expenses
WHERE expense_cat_id = 2) AS sum2,
employee_id
FROM expenses group by employee_id
but this has the same problem as the join approach - totals for cat 2 are doubled.
How do I make the second join only include the expense_2_total once ???
I have a personal dislike of sql case statements as they seem more of a procedural language construct (and sql is declarative), but am happy to consider their use in this case - but I put the challenge out there for sql experts to solve this elegantly.
You are looking for conditional aggregation:
SELECT employee_id,
sum(case when expense_cat_id = 1 then expense_amount else 0 end) as expense_1_total,
sum(case when expense_cat_id = 2 then expense_amount else 0 end) as expense_2_total
FROM expenses e
GROUP BY employee_id;
I have the following tables:
Let's assume the first table represents a booking made by a customer for a hotel.
+------------+-----------+-----------+--------------+----------------+
| booking_id | client_id | room_type | arrival_date | departure_date |
+------------+-----------+-----------+--------------+----------------+
| 1 | 1 | 1 | 2016-05-30 | 2016-06-03 |
+------------+-----------+-----------+--------------+----------------+
The second table contains the prices for different types of room. The prices vary for different periods of time.
+---------------+-----------+------------+------------+-------+
| room_price_id | room_type | start_date | end_date | price |
+---------------+-----------+------------+------------+-------+
| 1 | 1 | 2016-03-01 | 2016-05-31 | 150 |
| 2 | 1 | 2016-06-01 | 2016-08-31 | 200 |
+---------------+-----------+------------+------------+-------+
My question is: how can I calculate the total cost for a booking if the price is not the same during the whole period of the booking? (in my case the total cost would be 700)
I read the following links: MySQL: Select all dates between date range and get table data matching dates and Select data from date range between two dates, but I don't get it on how to solve my problem since the entries in the table with the prices contain only date ranges and not explicit dates as in the first link.
The trick with your question is in formulating the join condition between the booking and prices tables. Once this is out of the way, a simple aggregation gets you the result you want. The join condition should be true whenever any point in a given price range falls within the range of the arrival or departure date.
Then, to count days we use the greater of the arrival date or the start date, and the lesser of the departure date or the end date.
SELECT
b.booking_id,
SUM((DATEDIFF(LEAST(b.departure_date, p.end_date),
GREATEST(b.arrival_date, p.start_date)) + 1) * p.price) AS total
FROM booking b
INNER JOIN prices p
ON b.room_type = p.room_type AND
(p.start_date BETWEEN b.arrival_date AND b.departure_date OR
p.end_date BETWEEN b.arrival_date AND b.departure_date)
GROUP BY b.booking_id;
The output for your sample data is 900. This is correct because:
2 days x 150 = 300
3 days x 200 = 600
total = 900
Demo here:
SQLFiddle
And here is another demo which highlights the case where a stay overlaps an entire price range.
I have some table in mysql database like this.
id | product | warehouse | price | date_shipping
------------------------------------------------
1 | Salt | 15 | 300 | 2017-03-08
2 | Salt | 15 | 300 | 2017-03-09
I want to SUM that column price with several condition. This is the condition.
From the product salt if the warehouse is have same id I don't want to SUM price value.
This is my second condition.
id | product | warehouse | price | date_shipping
------------------------------------------------
1 | Salt | 15 | 300 | 2017-03-08
2 | Salt | 18 | 300 | 2017-03-09
From the product salt if the warehouse is have different id I want to SUM price value.
This is the result what I want from the query.
From first condition :
salt | 15 | 300
From second condition :
salt | 15,18 | 600
This is query what I have doing.
SELECT product, GROUP_CONCAT(warehouse SEPARATOR ',') as warehouse, SUM(price)
FROM db_product
Somebody can help me with this ? Thank you.
Your problem requires two aggregations. The first one identifies, for each product in a warehouse, the record having the earliest shipping date. Then, a second aggregation is needed to group concatenate the warehouses for each product.
SELECT t.product,
GROUP_CONCAT(t.warehouse) AS warehouses,
SUM(t.price) AS total
FROM
(
SELECT t1.product,
t1.warehouse,
t1.price
FROM db_product t1
INNER JOIN
(
SELECT product, warehouse, MIN(date_shipping) AS min_date_shipping
FROM db_product
GROUP BY product, warehouse
) t2
ON t1.product = t2.product AND
t1.warehouse = t2.warehouse AND
t1.date_shipping = t2.min_date_shipping
) t
GROUP BY t.product
Output:
Demo here:
Rextester
I have two tables (Invoices and taxes) in mysql:
Invoices:
- id
- account_id
- issued_at
- total
- gross_amount
- country
Taxes:
- id
- invoice_id
- tax_name
- tax_rate
- taxable_amount
- tax_amount
I'm trying to retrive a report like this
rep_month | country | total_amount | tax_name | tax_rate(%) | taxable_amount | tax_amount
--------------------------------------------------------------------------------------
2017-01-01 | ES | 1000 | TAX1 | 21 | 700 | 147
2017-01-01 | ES | 1000 | TAX2 | -15 | 700 | 105
2016-12-01 | FR | 100 | TAX4 | 20 | 30 | 6
2016-12-01 | FR | 100 | B2B | 0 | 70 | 0
2017-01-01 | GB | 2500 | TAX3 | 20 | 1000 | 200
The idea behind this is that an invoice has a has_many relation with taxes. So an invoice can have or not taxes. The report should show the total amount collected (total_amount) for a given country (regardess if it includes taxes)
and indicate which part of that total amount is taxable (taxable_amount) for an specific tax.
My current approach is this one:
SELECT
DATE_FORMAT(invoices.issued_at, '%Y-%m-01') AS rep_month,
invoices.country AS country
( SELECT sum(docs.gross_amount)
FROM invoices AS docs
WHERE docs.country = invoices.country
AND DATE_FORMAT(docs.issue_date, '%Y-%m-01') = rep_month
) AS total_amount,
taxes.tax_name AS tax_name,
taxes.tax_rate AS tax_rate,
SUM(taxes.taxable_amount) AS taxable_amount,
SUM(taxes.tax_amount) AS tax_amount
FROM invoices
JOIN taxes ON invoices.id = taxes.document_id
AND documents.issue_date BETWEEN '2016-01-01' AND '2017-12-31'
GROUP BY account_id, rep_month, country, tax_name, tax_rate
ORDER BY country desc
Well, this works but for a real dataset (thousands of records) it's really slow as the select subquery for retrieving the total_amount is being run for each row of the report.
I cannot make a LEFT JOIN taxes with a direct SUM(gross_amount) as the GROUP BY groups by tax name and rate and I need to show the total collected per country regardless if the amount was taxed or not. Is there a faster alternative to this?
I do not know the exact use case of using this query but the issue is the way with which you're trying to structure the DB, you're trying to get the entire data in one go.
Ideally, you should run the query you have and store in a different table (summary table) and then query directly from the summary table whenever you want. And if you have a new entry in the Invoices table then you can use the query to run either on every entry or periodically update the summary table via a cronjob.