How count many fields (MySql) - mysql

I have a table that looks like the below and would like to a count of all bookings with a a count of all guests per week. There are 30 guest fields:
locations
| Field | Type |
| ------------ | ---------- |
| location | text |
| day_number | int(11) |
| month_number | int(11) |
| year | text |
| week_number | tinyint(4) |
| start | datetime |
| end | datetime |
| guest_1 | text |
| guest_2 | text |
| … | |
| guest_30 | text |
I am using:
select locaton, count(*) AS `Number of bookings per week`, week_number,
month_number, `month`
FROM locations
GROUP BY location, week_number;
That gets me:
| location | ...Bookings | week_number | month_number | January |
| ------------ | ----------- | ----------- | ------------ | -------- |
| Location One | 3 | 2 | 1 | January |
| Location One | 5 | 3 | 1 | January |
| Location One | 2 | 4 | 1 | January |
| Location One | 2 | 5 | 2 | February |
| Location One | 5 | 6 | 2 | February |
| Location One | 1 | 7 | 2 | February |
| Location One | 3 | 8 | 2 | February |
There are many locations.
How can I combine a count of guests over the 30 guest fields for each week and location in my query?
Thanks for any help in advance.

Simply count the guests for each combination and then sum up those counts
SELECT location,week_number,month_number,SUM(
(guest_1 <> "") +
(guest_2 <> "") +
(guest_3 <> "") +
....
(guest_30 <> "")
) AS num_guests
FROM locations
GROUP BY location,week_number,month_number

It's difficult because this table is not normalized.
In my opinion is this possible please re-create this solution and create new table GUEST with foreign key from LOCATION.
Next step is create subquery for example:
(you query) t1
having 30 = (select count(*) from GUEST where idlocation=t1.idlocation and year=t1.year, week_number=t1.week_number)
It will be more better resolve because in this situation you can add more guest without change logical table.
In your situation you always check every column separately.

Related

How to make a pivot table by multiple unique ID numbers?

I'm trying to break up a SQL table that needs to take a users name and find the unique user ID's from up to 4 systems.
The data is currently like this:
| Name | User_ID |
-----------------
| A | 10 |
| A | 110 |
| A | 1500 |
| A | 4 |
| B | 20 |
| B | 100 |
| B | 2 |
| C | 10 |
I need to pivot it around the user's name to look like this (the id's don't need to be in numerical order as the SYS#_ID for each doesn't matter):
| Name | SYS1_ID | SYS2_ID | SYS3_ID | SYS4_ID |
------------------------------------------------
| A | 4 | 10 | 110 | 1500 |
| B | 2 | 20 | 100 | NULL |
| C | 10 | NULL | NULL | NULL |
This is the code I have tried on MySQL:
PIVOT(
COUNT(User_ID)
FOR Name
IN (SYS1_ID, SYS2_ID, SYS3_ID, SYS4_ID)
)
AS PivotedUsers
ORDER BY PivotedUsers.User_Name;
I'm unsure if PIVOT works on MySQL as I keep getting an error "PIVOT unknown". Is there a way to find the values that each user has and if they do not appear in the table already add them to the next column with a max of 4 values?

Complicated loop of queries into a single one

I need a little bit of help with making a complicated query, i will try to explain what i am trying to accomplish down below.
Here is my data
table_one
+---------+---------+----------+----------+
| user_id | poly_id | in | out |
+---------+---------+----------+----------+
| 900 | 1 | 20-12-17 | 20-12-17 |
| 900 | 2 | 21-12-17 | 22-12-17 |
| 900 | 3 | 22-12-17 | 24-12-17 |
| 900 | 1 | 23-12-17 | 26-12-17 |
| 444 | 4 | 24-12-17 | 28-12-17 |
| 444 | 4 | 25-12-17 | 30-12-17 |
| 444 | 5 | 26-12-17 | 01-01-18 |
| 444 | 3 | 27-12-17 | 03-01-18 |
| 900 | 2 | 28-12-17 | 05-01-18 |
| 900 | 1 | 29-12-17 | 07-01-18 |
| 444 | 2 | 30-12-17 | 09-01-18 |
+---------+---------+----------+----------+
table_two
+----+---------+-------------+---------+
| id | name | type | product |
+----+---------+-------------+---------+
| 1 | city 1 | gas station | general |
| 2 | city 2 | workshop | general |
| 3 | city 3 | paint | bikes |
| 4 | city 4 | paint | general |
| 5 | city 5 | gas station | cars |
| 6 | city 6 | gas station | bikes |
| 7 | city 7 | paint | cars |
| 8 | city 8 | workshop | cars |
| 9 | city 9 | gas station | general |
| 10 | city 10 | gas station | cars |
| 11 | city 11 | gas station | general |
+----+---------+-------------+---------+
i have a working solution that looks like this
//results comes from somewhere else, it looks something like this for example:
array (
"user_id" => "poly_id of the last gas station"
"900" => 1,
"444" => 10
)
foreach ($result AS $res ) {
$query = "
SELECT
table_one.name AS name
FROM
`table_one`
LEFT JOIN
`table_two` ON table_one.poly_id = table_two.id
WHERE
`table_two`.type = 'gas station '
AND
table_one.user_id = $res['user_id']
AND
table_one.poly_id != $res['poly_id']
AND
table_one.in >= "some date from'
AND
table_one.out <= 'some date to'
AND
(FIND_IN_SET('general', table_two.product) > 0 OR FIND_IN_SET('cars', table_two.product) > 0 )
ORDER BY out DESC LIMIT 1
";
//if the results is not empty use the result['name']
}
The idea is: I have the user last gas station, but i need to find the previous one between a date range.
As i said, the above example is working just fine, however i need to be able to process multiple results at once, and sometimes the results are ~2000.
Which means 2000+ queries per request.
Is it even possible to somehow optimize this loop of queries into a single one, so I don't do 2000 queries per request ?
If possible, how :D
Thanks.
This query will return result contains user_id with it's last
enter in the given periode.
one thing here because you are
using date not date time if the user exit in the same
day two time you will have two record of that user you can skip the second
record in you code
select
user_id,
in,
out
from table_one t1
INNER JOIN (
select
user_id
max(out) as 'max_out',
from
table_one
where
in >= ? AND
out <= ? AND
ploy_id not in [list_of_unwanted_ploy_id]
-- you can specify any condition here
group by user_id
) l_out on t1.user_id = l_out.user_id and t1.out = l_out.max_out
where
t1.user_id in [list_of_user_id]

MySQL combining outer joins

For this question I have created a simple example that illustrates what I am asking.
Say I had a table called 'books'
+----+----------------------------+-----------+
| pk | title | author_id |
+----+----------------------------+-----------+
| 1 | The Lost Symbol | 1 |
| 2 | Follow Us Home | 2 |
| 3 | The Man in the High Castle | 3 |
+----+----------------------------+-----------+
(table a)
And another table called 'shops', that had a list of shops that sold each book:
+----+---------+-------------+-------+
| pk | book_id | shop_name | price |
+----+---------+-------------+-------+
| 1 | 1 | WHSmith | 5.00 |
| 2 | 1 | Waterstones | 7.00 |
| 3 | 1 | Amazon | 2.50 |
| 4 | 2 | WHSmith | 4.00 |
| 5 | 2 | Borders | 4.50 |
+----+---------+-------------+-------+
(table b)
If I do a simple select that grabs a book and all of the places it is sold using a join such as:
SELECT
books.*,
shops.shop_name,
shops.price
FROM
books
JOIN shops ON books.pk = shops.book_id
WHERE
book.book_name = "The Lost Symbol"
I would get results such as below:
+----+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+----+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | WHSmith | 5.00 |
| 1 | The Lost Symbol | 1 | Waterstones | 7.00 |
| 1 | The Lost Symbol | 1 | Amazon | 2.50 |
+----+-----------------+-----------+-------------+-------+
(table c)
However, I would LIKE to receive results like this:
+----+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+----+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | NULL | NULL |
| 1 | The Lost Symbol | 1 | WHSmith | 5.00 |
| 1 | The Lost Symbol | 1 | Waterstones | 7.00 |
| 1 | The Lost Symbol | 1 | Amazon | 2.50 |
+----+-----------------+-----------+-------------+-------+
(table d)
I.e. the first row is just the result of left outer join and the rest of the results are the the inner join.
An even more desired outcome is:
+------+-----------------+-----------+-------------+-------+
| pk | title | author_id | shop_name | price |
+------+-----------------+-----------+-------------+-------+
| 1 | The Lost Symbol | 1 | NULL | NULL |
| NULL | NULL | NULL | WHSmith | 5.00 |
| NULL | NULL | NULL | Waterstones | 7.00 |
| NULL | NULL | NULL | Amazon | 2.50 |
+------+-----------------+-----------+-------------+-------+
(table e)
Having shop_name and price concatenated and grouped in a single row seems not to work as it only does the first result from shops instead of all of them, also in my real world scenario, I have punctuation in the data so have to be careful with the separator.
So how would I get the result of table e?
You can use UNION ALL to build the required result set:
SELECT pk, title, author_id, NULL AS shop_name, NULL AS price
FROM books
WHERE books.title = "The Lost Symbol"
UNION ALL
SELECT NULL AS pk, NULL AS title, NULL AS author_id, shops.shop_name, shops.price
FROM books
JOIN shops ON books.pk = shops.book_id
WHERE books.title = "The Lost Symbol"
The first part of the union operation returns the first row of the result, i.e. the book title. The second part returns the rest of the rows, i.e.the shop names.
Demo here

mysql same price mismatch column value

Good afternoon everyone,
I wonder if I can get help with this example in a database.
I have listings delivered as:
------------------------------------
| Id | name | price |
-------------------------------
| 1 | Hawaii | 20.58 |
| 2 | Hawaii VIP | 45.58 |
| 3 | Aruba | 13.58 |
| 4 | Aruba VIP | 34.58 |
| 5 | Japon | 14.58 |
| 6 | Japon VIP | 34.58 |
| 7 | Alemania | 14.58 |
| 8 | Alemania VIP | 14.58 |
But I need them to be shown as follows:
-----------------------------------------------------
| Id | name | price basic | price vip
-----------------------------------------------------
| 1 | Hawaii | 20.58 | 45.34 |
| 5 | Japon | 14.58 | 34.58 |
etc etc etc
What I need are the two prices of the same country in a different column in the same query.
As I can catch the "VIP" based on this field and put it in a column with its value
It would be better to store IS_VIP as a separate column in the first table instead of adding it to the name, but since it's not a perfect world, you could solve it like this until then. :)
SELECT
t.Id,
t.name,
t.price as "price basic",
v.price as "price VIP"
FROM YourTable t
JOIN YourTable v ON v.name = CONCAT(t.name, ' VIP')
Sql Fiddle Example

MySQL - Join tables and convert rows to columns

I have two tables similar to these (t_stamp would normally be a DATETIME, abbreviated here for clarity):
datapoints
+------+---------+----+---------+
| ndx | value | ID | t_stamp |
+------+---------+----+---------+
| 1 | 503.42 | 1 | 3/1/15 |
| 2 | 17.81 | 2 | 3/1/15 |
| 4 | 498.21 | 1 | 3/2/15 |
| 4 | 19.51 | 2 | 3/2/15 |
+------+---------+----+---------+
parameters
+------+----+---------------+-------+
| ndx | ID | description | unit |
+------+----+---------------+-------+
| 1 | 1 | wetwell level | ft |
| 2 | 2 | effluent flow | MGD |
+------+----+---------------+-------+
I'm looking to combine them so that the descriptions become column headers and list the values in order of time stamp, end result looking something like this:
new table
+---------+---------------+---------------+
| t_stamp | wetwell level | effluent flow |
+---------+---------------+---------------+
| 3/1/15 | 503.42 | 17.81 |
| 3/2/15 | 498.21 | 19.51 |
+---------+---------------+---------------+
Bearing in mind, I have considerably more rows in each table so I'm looking for something dynamic. It could be query or stored procedure based. Thank you for any help!