Select of 2 related tables in MySQL - mysql

I have these 2 tables:
Table Users:
id | name
---------
1 | Joe
2 | Sara
3 | Michael
Table Sales:
id | product | user_id
------------------------
1 | Car | 2
2 | Truck | 3
3 | motorcycle| 1
4 | Car | 2
5 | Truck | 1
6 | Car | 3
7 | Car | 2
8 | Truck | 3
9 | Car | 2
10 | Car | 3
I want the following:
User Name | Car | Truck | Motorcycle
Joe | 0 | 1 | 1
Sara | 4 | 0 | 0
Michael | 2 | 2 | 0
Any help would be appreciated

--For a small number of products this works,
Select username
, Sum(case when product = 'Car' then 1 else 0 End) Cars
, Sum(case when product = 'Truck' then 1 else 0 End) Truck
, Sum(case when product = 'motorcycle' then 1 else 0 End) motorcycle
From Sales s join users u on s.userid = u.userid
group by username

SELECT Users.name,
SUM(Case
WHEN product='Car' then 1
ELSE 0
) AS Car,
SUM(Case
WHEN product='Truck' then 1
ELSE 0
) AS Truck ,
SUM(Case
WHEN product='Motorcycle' then 1
ELSE 0
) AS Motorcycle,
FROM Users
LEFT JOIN Sales ON Users.id = Sales.user_id
GROUP BY Users.name

SELECT
name as UserName ,
SUM(product= 'Car')AS Car,
SUM(product= 'Truck')AS Truck,
SUM(product= 'motorcycle') AS motorcycle
FROM Users join Sales
on Users.id = Sales.user_id
GROUP BY name
hope it helps but still this is a standard solution you should check pivot Tables.

Related

Select records in one table and specific matching records from the other

I have three tables, two of which are relevant for this question. Users, Things, User_to_thing
Users
ID | Name | Active
-------------------
1 | Joe | 1
2 | Jack | 1
3 | Tom | 1
4 | Harry | 0
5 | Stan | 1
6 | Bob | 1
User_to_thing
Thing ID | User ID | Status
---------------------------
3 | 1 | 1
3 | 2 | 2
3 | 5 | 1
4 | 1 | 3
4 | 2 | 2
I'm trying to create a query where I can select all the active users in the users table and have a column where I can see the status for "thing 3" from the User_to_thing table while also sorting results so that the nulls come at the end. So the result would be something like:
User ID | Status
----------------
1 | 1
2 | 2
5 | 1
3 | NULL
6 | NULL
What I have so far for a query is the following:
SELECT u1.id, u1.name, user_to_thing.status
FROM users u1
LEFT JOIN user_to_thing ON u1.id = user_to_thing.user_id
WHERE u1.active = 1
OR user_to_thing.event_id = 62
ORDER BY (CASE WHEN user_to_thing.status = 1 THEN 1
WHEN user_to_thing.status = 2 THEN 2
ELSE 3 END)
What I'm getting as a result is the following:
User ID | Status | Thing ID
---------------------------
1 | 1 | 3
1 | 3 | 4
2 | 2 | 3
2 | 2 | 4
5 | 1 | 3
3 | NULL | NULL
6 | NULL | NULL
I'm not sure how to limit it to just thing #3 while also getting a list of all active users. Any guidance would be appreciated.
It looks like the following should work for you, grouping to remove duplicates and ordering based on null
select u.Id as UserId, t.status
from users u
left join User_to_thing t on t.UserID = u.id
where u.active = 1
group by u.Id, t.Status
order by case when status is null then 1 else 0 end, u.Id
Based on your revised data, you can amend slightly
select u.Id UserId, Min(t.status) Status
from users u
left join User_to_thing t on t.UserID=u.id
where u.active=1
group by u.Id
order by case when Min(t.status) is null then 1 else 0 end, u.Id

SQL- Count number of 'similar' rows and place results in another table

I have a table called of 'orders' that records an order id for a meal, a person id for the person who ordered the meal and the meal (which can be 1, 2, or 3)
orders
oid | pid | meal
________________
1 | 1 | 2
2 | 1 | 3
3 | 3 | 1
4 | 5 | 2
5 | 5 | 2
6 | 5 | 1
I want to generate a result that will allow me to view the number of orders for each meal for each pid:
pid | meal1 | meal2 | meal3
____________________________
1 | 0 | 1 | 1
3 | 1 | 0 | 0
5 | 0 | 2 | 1
I am not an SQL expert, but I was thinking that I would first group the list by pid, then by meal. But how would I do the counting? I am truly lost.
Basically you need to first create multiple columns for the different meals using case when, then you can group by pid and sum it up
Select pid, sum(case when meal =1 then 1 else 0 end) as meal1,
sum(case when meal =2 then 1 else 0 end) as meal2,
sum(case when meal =3 then 1 else 0 end) as meal3
from Table
group by pid

MySQL Crosstab aggregation with 2 conditions

I have a query which creates a crosstab. The results are a count of the txn_id for branda, and the count of txn_id for brandb.
The txn_id is NOT UNIQUE. This is an example of the transactions table.:
txn_id | nationality_id | sku | sales | units
1 | 1 | 1 | 20 | 2
1 | 1 | 2 | 15 | 1
2 | 4 | 1 | 20 | 2
3 | 2 | 1 | 10 | 1
4 | 3 | 2 | 15 | 1
5 | 4 | 1 | 10 | 1
There are 2 other tables (products) - (sku, brand, product name), and (nationalities) - (nationality_id, nationality).
I would like to add a third column which gets me the count of txn_id where BOTH brands are purchased
The output should be
nationality | branda | brandb | combined
1 | 1 | 1 | 1
2 | 1 | 0 | 0
3 | 0 | 1 | 0
4 | 2 | 0 | 0
Current query.
SELECT
nationalities.nationality,
COUNT((CASE brand WHEN 'branda' THEN txn_id ELSE NULL END)) AS branda,
COUNT((CASE brand WHEN 'brandb' THEN txn_id ELSE NULL END)) AS brandb
<I want my 3rd column here>
FROM
transaction_data
INNER JOIN
products USING (sku)
INNER JOIN
nationalities USING (nationality_id)
GROUP BY nationality
ORDER BY branda DESC
LIMIT 20;
I have tried using:
COUNT((CASE brand WHEN 'brandb' OR 'brandb' THEN txn_id ELSE NULL END)) AS combined - however this obviously returns too many (returns branda or brandb regardless of whether they were purchased together). I know I can't use AND, because obviously no single cell is going to be both branda AND brandb.
I have also tried using:
COUNT((CASE brand WHEN IN('branda', 'brandb') THEN txn_id ELSE NULL END)) AS combined - However this isn't valid syntax.
I feel that I should be using a HAVING clause, but I'm not sure how this would work in the column list.
I think you are going to need two levels of aggregation:
SELECT n.nationality,
sum(branda), sum(brandb), sum(branda * brandb)
FROM (SELECT t.txn_id, n.nationality,
MAX(CASE brand WHEN 'branda' THEN 1 ELSE 0 END) AS branda,
MAX(CASE brand WHEN 'brandb' THEN 1 ELSE 0 END) AS brandb
FROM transaction_data t INNER JOIN
products p
USING (sku) INNER JOIN
nationalities n
USING (nationality_id)
GROUP BY t.txn_id, n.nationality
) tn
GROUP BY n.nationality
ORDER BY max(txn_id) DESC
LIMIT 20;

how can I print multiple rows data in one column?

I having two table with mysql as below?
TimeSchedule
subID | date | venue | timeslot
1 | 8-12 | ABC | 10 - 12
2 | 8-12 | ABC | 2 - 4
subject
subID | name
1 | Games
2 | Music
I want to display these two table data as following?
Date | 10 - 12 | 2 - 4 |Venue
8-12 | Game | Music | ABC
Try this:
SELECT t.date,
MAX(CASE WHEN t.timeslot = '10 - 12' THEN s.name ELSE '' END) AS `10 - 12`,
MAX(CASE WHEN t.timeslot = '2 - 4' THEN s.name ELSE '' END) AS `2 - 4`,
t.venue
FROM TimeSchedule t
INNER JOIN `subject` s ON t.subID = s.subID
GROUP BY t.date;

Don't return the lowest value if

The goal
Don't return the lowest price whose its markets are suspended.
The problem
I don't know the syntax.
The scenario
There is the following stored procedure to get the lowest and the biggest price of a specific product:
BEGIN
Select Min(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As minProductPrice,
Max(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As maxProductPrice
From products As product
Where product.Name = 'Playstation 3';
END
The context is: there are markets and products. Products belong to markets. If some market is suspended, then doesn't display its products and nor add them to max/min price comparison.
Can you all understand? I want to exclude the products whose its markets are suspended from the Min or Max statement of above's query.
The tables
Here is the markets table:
+----+------+-------------+
| Id | Name | SituationId |
+----+------+-------------+
| 1 | A | 1 |
+----+------+-------------+
| 2 | B | 2 |
+----+------+-------------+
| 3 | C | 3 |
+----+------+-------------+
Here is the markets_situations table:
+----+-----------+
| Id | Name |
+----+-----------+
| 1 | Neutral |
+----+-----------+
| 2 | Premium |
+----+-----------+
| 3 | Suspended |
+----+-----------+
And finally, here is the products table:
+----+---------------+--------+------------------+---------------+
| Id | Name | Market | PromotionalPrice | OriginalPrice |
+----+---------------+--------+------------------+---------------+
| 1 | Xbox 360 | 1 | 0 | 225,00 |
+----+---------------+--------+------------------+---------------+
| 2 | Xbox 360 | 2 | 99,00 | 175,00 |
+----+---------------+--------+------------------+---------------+
| 3 | Xbox 360 | 3 | 0 | 135,00 |
+----+---------------+--------+------------------+---------------+
| 4 | Playstation 3 | 1 | 0 | 189,00 |
+----+---------------+--------+------------------+---------------+
| 5 | Playstation 3 | 2 | 125,00 | 165,00 |
+----+---------------+--------+------------------+---------------+
| 6 | Playstation 3 | 3 | 110,00 | 185,00 |
+----+---------------+--------+------------------+---------------+
To enhance the comprehension
I don't want to display 110,00 as the Min price of the stored procedure's result because its market (C) is Suspended.
What I already did
I already tried the following, but without success:
BEGIN
[...]
Where product.Name = 'Playstation 3'
And marketSituation.Id <> 3;
END
What happens? The And condition does nothing. The query keeps returning me the price of the suspended market.
Select Min(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As minProductPrice,
Max(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As maxProductPrice
From products As product
Inner join markets on product.market = markets.id AND markets.SituationId <> 3
Where product.Name = 'Playstation 3';
How about something like
Select Min(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As minProductPrice,
Max(Case When product.PromotionalPrice = 0
Then product.OriginalPrice Else
Least(product.PromotionalPrice, product.OriginalPrice)
End) As maxProductPrice
From products As product INNER JOIN
Markets ON Product.Market = Markets.Id
Where product.Name = 'Playstation 3'
AND Markets.SituationID <> 3