I want to know what is the top fruit on 2021-08-15 (completed with highest total price), table below:
product
------------------
id | name
------------------
1 | banana
2 | orange
3 | apple
4 | watermelon
5 | pineapple
sales
--------------------------------------------------------------------------------
s_id | sn.id | sn.product_id | sn.status | sn.total_price | created_at
--------------------------------------------------------------------------------
1 | 1 | 2 | BOOKED | 300 | 2021-08-15 12:20:32
| 2 | 5 | COMPLETED | 800 |
| 3 | 5 | COMPLETED | 200 |
2 | 4 | 2 | COMPLETED | 500 | 2021-08-16 09:00:59
| 5 | 1 | CANCELLED | 1000 |
How to write a query on a table with nested records?
Does MySQL even have nested record data type?
select *
from
(select p.id,p.name,sum(s.total_price) as sumOfSales
from product p join sales s on p.id = s.product_id
where s.status = "COMPLETED"
group by p.id,p.name) T
order by sumOfSales desc
I'm developing a hotel room booking system.
This system will contain some quantity of hotels, rooms & room_categories.
I have tables for these things already.
At the current moment I need to build a query to get the quantity of available rooms for each of room category on given dates.
My rooms table is like this:
--------------------------------------------
| id | name | hotel_id |room_category_id|
--------------------------------------------
| 1 | Room #1 | 1 | 1 |
| 2 | Room #2 | 1 | 1 |
| 3 | Room #3 | 1 | 2 |
| 4 | Room #4 | 1 | 2 |
| 5 | Room #5 | 1 | 3 |
| 6 | Room #6 | 1 | 3 |
| 7 | Room #7 | 1 | 4 |
| 8 | Room #8 | 1 | 4 |
--------------------------------------------
Room categories table is like this:
----------------------------------
| id | name | price | volume |
----------------------------------
| 1 | Standart | $100 | 2 |
| 2 | Comfort | $150 | 2 |
| 3 | Half Lux | $200 | 3 |
| 4 | Lux | $250 | 3 |
----------------------------------
Bookings table is like this:
------------------------------------------------------------------------
| id | booking_start | booking_end | room_id |room_category_id|hotel_id|
------------------------------------------------------------------------
| 1 | 2019-06-17 | 2019-07-17 | 1 | 1 | 1 |
| 2 | 2019-06-17 | 2019-07-17 | null | 2 | 1 |
| 3 | 2019-06-17 | 2019-07-17 | null | 3 | 1 |
------------------------------------------------------------------------
I'm trying this query
SELECT room_categories.name, COUNT(room_categories.name) as quantity FROM rooms
INNER JOIN room_categories
ON rooms.room_category_id = room_categories.id
WHERE hotel_id=1
AND room_categories.id NOT IN (
Select bookings.room_category_id FROM bookings
WHERE '2019-07-28' between booking_start and booking_end
OR booking_end between '2019-06-17' and '2019-07-28'
OR '2019-06-17' between booking_start and booking_end
OR booking_start between '2019-06-17' and '2019-07-28'
)
GROUP BY room_categories.name
ORDER BY quantity
Let's imagine I have 2 rooms for each category and 1 booking for each room category. This query return ONLY category I don't have ANY bookings on (in my case room_category=4).
-------------------
| name |quantity|
-------------------
|Standart| 2 |
-------------------
How should I build a query to get correct counts here like this:
|room_category|count|
---------------------
| Standart | 1 |
| Comfort | 1 |
| Half Lux | 1 |
| Lux | 2 |
---------------------
Your question is a little vague on what you mean by "available" and what dates you want. Let me assume that you want the numbers of rooms, by category, that are available for the entire period from 2019-06-17 to 2019-07-28 (that seems like a long time to me and a hotel that has rooms for that entire period does not seem to have a very good business).
SELECT rc.name,
COUNT(b.room_id IS NULL) as quantity
FROM rooms r JOIN
room_categories rc
ON rc.room_category_id = r.id LEFT JOIN
bookings b
ON b.room_id = r.room_id AND
b.booking_start <= '2019-07-28' AND
b.booking_end >= '2019-06-17'
WHERE r.hotel_id = 1
GROUP BY rc.name
ORDER BY quantity DESC;
The LEFT JOIN is matching any booking that has a booking during the date range. The outer query is then counting rows that do not match. Note that the filter is not in the WHERE clause, so you can get counts of 0.
Given a statuses table that holds information about products availability, how do I select the date that corresponds to the 1st day in the latest 20 days that the product has been active?
Yes I know the question is hard to follow. I think another way to put it would be: I want to know how many times each product has been sold in the last 20 days that it was active, meaning the product could have been active for years, but I'd only want the sales count from the latest 20 days that it had a status of "active".
It's something easily doable in the server-side (i.e. getting any collection of products from the DB, iterating them, performing n+1 queries on the statuses table, etc), but I have hundreds of thousands of items so it's imperative to do it in SQL for performance reasons.
table : products
+-------+-----------+
| id | name |
+-------+-----------+
| 1 | Apple |
| 2 | Banana |
| 3 | Grape |
+-------+-----------+
table : statuses
+-------+-------------+---------------+---------------+
| id | name | product_id | created_at |
+-------+-------------+---------------+---------------+
| 1 | active | 1 | 2018-01-01 |
| 2 | inactive | 1 | 2018-02-01 |
| 3 | active | 1 | 2018-03-01 |
| 4 | inactive | 1 | 2018-03-15 |
| 6 | active | 1 | 2018-04-25 |
| 7 | active | 2 | 2018-03-01 |
| 8 | active | 3 | 2018-03-10 |
| 9 | inactive | 3 | 2018-03-15 |
+-------+-------------+---------------+---------------+
table : items (ordered products)
+-------+---------------+-------------+
| id | product_id | order_id |
+-------+---------------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 6 | 2 | 3 |
| 7 | 2 | 4 |
| 8 | 2 | 5 |
| 9 | 3 | 5 |
+-------+---------------+-------------+
table : orders
+-------+---------------+
| id | created_at |
+-------+---------------+
| 1 | 2018-01-02 |
| 2 | 2018-01-15 |
| 3 | 2018-03-02 |
| 4 | 2018-03-10 |
| 5 | 2018-03-13 |
+-------+---------------+
I want my final results to look like this:
+-------+-----------+----------------------+--------------------------------+
| id | name | recent_sales_count | date_to_start_counting_sales |
+-------+-----------+----------------------+--------------------------------+
| 1 | Apple | 3 | 2018-01-30 |
| 2 | Banana | 0 | 2018-04-09 |
| 3 | Grape | 1 | 2018-03-10 |
+-------+-----------+----------------------+--------------------------------+
So this is what I mean by latest 20 active days for e.g. Apple:
It was last activated at '2018-04-25'. That's 4 days ago.
Before that, it was inactive since '2018-03-15', so all these days until '2018-04-25' don't count.
Before that, it was active since '2018-03-01'. That's more 14 days until '2018-03-15'.
Before that, inactive since '2018-02-01'.
Finally, it was active since '2018-01-01', so it should only count the missing 2 days (4 + 14 + 2 = 20) backwards from '2018-02-01', resulting in date_to_start_counting_sales = '2018-01-30'.
With the '2018-01-30' date in hand, I'm then able to count Apple orders in the last 20 active days: 3.
Hope that makes sense.
Here is a fiddle with the data provided above.
I've got a standard SQL solution, that does not use any window function as you are on MySQL 5
My solution requires 3 stacked views.
It would have been better with a CTE but your version doesn't support it. Same goes for the stacked Views... I don't like to stack views and always try to avoid it, but sometimes you have no other choice, because MySQL doesn't accept subqueries in FROM clause for Views.
CREATE VIEW VIEW_product_dates AS
(
SELECT product_id, created_at AS active_date,
(
SELECT created_at
FROM statuses ti
WHERE name = 'inactive' AND ta.created_at < ti.created_at AND ti.product_id=ta.product_id
GROUP BY product_id
) AS inactive_date
FROM statuses ta
WHERE name = 'active'
);
CREATE VIEW VIEW_product_dates_days AS
(
SELECT product_id, active_date, inactive_date, datediff(IFNULL(inactive_date, SYSDATE()),active_date) AS nb_days
FROM VIEW_product_dates
);
CREATE VIEW VIEW_product_dates_days_cumul AS
(
SELECT product_id, active_date, ifnull(inactive_date,sysdate()) AS inactive_date, nb_days,
IFNULL((SELECT SUM(V2.nb_days) + V1.nb_days
FROM VIEW_product_dates_days V2
WHERE V2.active_date >= IFNULL(V1.inactive_date, SYSDATE()) AND V1.product_id=V2.product_id
),V1.nb_days) AS cumul_days
FROM VIEW_product_dates_days V1
);
The final view produce this :
| product_id | active_date | inactive_date | nb_days | cumul_days |
|------------|----------------------|----------------------|---------|------------|
| 1 | 2018-01-01T00:00:00Z | 2018-02-01T00:00:00Z | 31 | 49 |
| 1 | 2018-03-01T00:00:00Z | 2018-03-15T00:00:00Z | 14 | 18 |
| 1 | 2018-04-25T00:00:00Z | 2018-04-29T11:28:39Z | 4 | 4 |
| 2 | 2018-03-01T00:00:00Z | 2018-04-29T11:28:39Z | 59 | 59 |
| 3 | 2018-03-10T00:00:00Z | 2018-03-15T00:00:00Z | 5 | 5 |
So it aggregates all active periods of all products, it counts the number of days for each period, and the cumulative days of all past active periods since current date.
Then we can query this final view to get the desired date for each product. I set a variable for your 20 days, so you can change that number easily if you want.
SET #cap_days = 20 ;
SELECT PD.id, Pd.name,
SUM(CASE WHEN o.created_at > PD.date_to_start_counting_sales THEN 1 ELSE 0 END) AS recent_sales_count ,
PD.date_to_start_counting_sales
FROM
(
SELECT p.*,
(CASE WHEN LowerCap.max_cumul_days IS NULL
THEN ADDDATE(ifnull(HigherCap.min_inactive_date,sysdate()),(-#cap_days))
ELSE
CASE WHEN LowerCap.max_cumul_days < #cap_days AND HigherCap.min_inactive_date IS NULL
THEN ADDDATE(ifnull(LowerCap.max_inactive_date,sysdate()),(-LowerCap.max_cumul_days))
ELSE ADDDATE(ifnull(HigherCap.min_inactive_date,sysdate()),(LowerCap.max_cumul_days-#cap_days))
END
END) as date_to_start_counting_sales
FROM products P
LEFT JOIN
(
SELECT product_id, MAX(cumul_days) AS max_cumul_days, MAX(inactive_date) AS max_inactive_date
FROM VIEW_product_dates_days_cumul
WHERE cumul_days <= #cap_days
GROUP BY product_id
) LowerCap ON P.id=LowerCap.product_id
LEFT JOIN
(
SELECT product_id, MIN(cumul_days) AS min_cumul_days, MIN(inactive_date) AS min_inactive_date
FROM VIEW_product_dates_days_cumul
WHERE cumul_days > #cap_days
GROUP BY product_id
) HigherCap ON P.id=HigherCap.product_id
) PD
LEFT JOIN items i ON PD.id = i.product_id
LEFT JOIN orders o ON o.id = i.order_id
GROUP BY PD.id, Pd.name, PD.date_to_start_counting_sales
Returns
| id | name | recent_sales_count | date_to_start_counting_sales |
|----|--------|--------------------|------------------------------|
| 1 | Apple | 3 | 2018-01-30T00:00:00Z |
| 2 | Banana | 0 | 2018-04-09T20:43:23Z |
| 3 | Grape | 1 | 2018-03-10T00:00:00Z |
FIDDLE : http://sqlfiddle.com/#!9/804f52/24
Not sure which version of MySql you're working with, but if you can use 8.0, that version came out with a lot of functionality that makes things slightly more doable (CTE's, row_number(), partition, etc.).
My recommendation would be to create a view like in this DB-Fiddle Example, call the view on server side and iterate programatically. There are ways of doing it in SQL, but it'd be a bear to write, test and likely would be less efficient.
Assumptions:
Products cannot be sold during inactive date ranges
Statuses table will always alternate status active/inactive/active for each product. I.e. no date ranges where a certain product is both active and inactive.
View Results:
+------------+-------------+------------+-------------+
| product_id | active_date | end_date | days_active |
+------------+-------------+------------+-------------+
| 1 | 2018-01-01 | 2018-02-01 | 31 |
+------------+-------------+------------+-------------+
| 1 | 2018-03-01 | 2018-03-15 | 14 |
+------------+-------------+------------+-------------+
| 1 | 2018-04-25 | 2018-04-29 | 4 |
+------------+-------------+------------+-------------+
| 2 | 2018-03-01 | 2018-04-29 | 59 |
+------------+-------------+------------+-------------+
| 3 | 2018-03-10 | 2018-03-15 | 5 |
+------------+-------------+------------+-------------+
View:
CREATE OR REPLACE VIEW days_active AS (
WITH active_rn
AS (SELECT *, Row_number()
OVER ( partition BY NAME, product_id
ORDER BY created_at) AS rownum
FROM statuses
WHERE name = 'active'),
inactive_rn
AS (SELECT *, Row_number()
OVER ( partition BY NAME, product_id
ORDER BY created_at) AS rownum
FROM statuses
WHERE name = 'inactive')
SELECT x1.product_id,
x1.created_at AS active_date,
CASE WHEN x2.created_at IS NULL
THEN Curdate()
ELSE x2.created_at
END AS end_date,
CASE WHEN x2.created_at IS NULL
THEN Datediff(Curdate(), x1.created_at)
ELSE Datediff(x2.created_at,x1.created_at)
END AS days_active
FROM active_rn x1
LEFT OUTER JOIN inactive_rn x2
ON x1.rownum = x2.rownum
AND x1.product_id = x2.product_id ORDER BY
x1.product_id);
I am using mysql and I have two tables:
Product Table:
| id | name | prices | revision_id |
|----|-----------|--------|-------------|
| 1 | Produkt 1 | 10 | 1 |
| 2 | Produkt 1 | 4 | 2 |
| 3 | Produkt 1 | 2 | 3 |
| 4 | Product 2 | 42 | 4 |
| 5 | Produkt 2 | 43 | 5 |
| 6 | Produkt 3 | 78 | 6 |
Each product has had price changes. That is why the name is still the same, but the products have a different price.
Revisions Table:
| id | revision_status |
|----|-----------------|
| 1 | 1 |
| 2 | 0 |
| 3 | 0 |
| 4 | 1 |
| 5 | 0 |
| 6 | 1 |
Inside the revision table, 0 indicates an open change, not approved change. 1 indicates - closed - an approved change.
Expected Result:
| id | name | prices | revision_id | revision_status |
|----|-----------|--------|-------------|-----------------|
| 1 | Produkt 1 | 10 | 1 | 1 |
| 2 | Produkt 1 | 4 | 2 | 0 |
| 3 | Produkt 1 | 2 | 3 | 0 |
| 4 | Product 2 | 42 | 4 | 1 |
| 5 | Produkt 2 | 43 | 5 | 0 |
Basically I want all products that have revisions - a revision_status of 0 on it, to see which products actually have revisions.
For example.: Product 3 does not have any price changes, so it should not appear in the final result.
I tried the following:
select *
from product
JOIN revisions
on product.revisions_id = revisions.id
ORDER
BY product.name
However, I still get Product 3 in my table and I am not sure how to get all products that have a revision_status of 0 on it.
I highly appreciate your replies!
In my interpretation you are looking for the products which have more than one revision. Filtering only on revision_status = 0 would not produce your expected result. The following query may answer your question (looking for those products which have more than 1 revision):
SELECT *
FROM product AS p
INNER JOIN revisions AS r ON p.revision_id = r.id
WHERE p.name IN (
SELECT p.name
FROM product AS p
INNER JOIN revisions AS r ON p.revision_id = r.id
GROUP BY p.name
HAVING COUNT(r.revision_status) > 1)
ORDER BY p.name
This would produce your expected result. See example at sqlfiddle.
i am watching a tutorial. There is a code which i don't understand what is supposed to do.
$sql = 'SELECT p.*,
a.screen_name AS author_name,
c.name AS category_name
FROM
posts p
LEFT JOIN
admin_users a ON p.author_id = a.id
LEFT JOIN
categories c ON p.category_id = c.id
WHERE
p.id = ?';
I read about the left joins but i didn't understand them. Can somebody please explain me the code i shared.
Thanks in advance!
Imagine you have two tables. One that stores the information about the programmers on your website, and the other table that keeps track of their online purchases.
PROGRAMMERS Table
+--------------------------------------------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Desire | 32 | 123 fake s| 3000.00 |
| 2 | Jamin | 25 | 234 fake s| 2500.00 |
| 3 | Jon | 23 | 567 fake s| 2000.00 |
| 4 | Bob | 30 | 789 fake s| 1500.00 |
| 5 | OtherGuy | 31 | 890 fake s| 1000.00 |
| 6 | DudeMan | 32 | 901 fake s| 500.00 |
+--------------------------------------------+
PURCHASES Table
+---------------------------------------------+
| ORDER_ID | PROG_ID | DATE | PRICE |
+-------------+---------+---------------------|
| 1 | 1 | 1-1-2017 | 100 |
| 2 | 2 | 1-2-2017 | 200 |
| 3 | 6 | 1-3-2017 | 300 |
+---------------------------------------------|
You decide you need to make a new table to consolidate this information to a table that contains
certain columns you want.
For example, you figure it would be nice for shipping purposes to have a table
that has the ID, the NAME, the PRICE, and the DATE columns.
Currently, the tables we have don't display all of that in a single table.
If we were to LEFT JOIN these tables, we would end up filling the desired columns
with NULL values where there is no information to join.
SELECT ID, NAME, PRICE, DATE
FROM PROGRAMMERS
LEFT JOIN PURCHASES
ON PROGRAMMERS.ID = PURCHASES.PROG_ID;
Notice that I'm selecting the columns I want from the starting table, then joining the right table
even though there might be missing information.
RESULTING TABLE
+-------------------------------------+
| ID | NAME | PRICE | DATE |
+----+----------+-----------------+---+
| 1 | Desire | 100 | 1-1-2017 |
| 2 | Jamin | 200 | 1-2-2017 |
| 3 | Jon | NULL | NULL |
| 4 | Bob | NULL | NULL |
| 5 | OtherGuy | NULL | NULL |
| 6 | DudeMan | 300 | 1-3-2017 |
+-------------------------------------+
For a visual representation of the difference between SQL JOINs check out
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins .