Estudo SQL
Estudo SQL
We have to draw 2 tables, one is a list of countries mentioning id & country and
another is the users of the country in the another column table. The following
SQL lists the number of users in each country.
SELECT b.country, count(a.id) AS user_count FROM countries b LEFT JOIN
users a ON b.id = a.country_id GROUP BY b.country;Country users -------- -----
UK 4 Argentina 2 portugal 2 USA 10 France 8 Russia 5 ...
2. Write an SQL statement to count the number of orders per country (10 marks)
SELECT country, userid, COUNT(o.orderid) as orders_per_country
FROM user_tab as u
INNER JOIN order_tab as o
ON u.userid = o.userid
GROUP BY country
3. Write an SQL statement to find the first order date of each user (10 marks)
SELECT u.userid, MIN (o.order_time) AS first_order_date
FROM user_tab as u
LEFT JOIN order_tab as o
ON u.userid = o.userid
GROUP BY userid
4. Write an SQL statement to find the number of users who made their first order in each
country, each
day (25 marks)
SELECT u.country, o.order_time, COUNT(userid) as number_of_users
FROM user_tab as u
INNER JOIN (
SELECT userid, MIN(order_time) as first_order
FROM order_tab
GROUP BY userid) AS o
ON u.userid = o.userid
GROUP BY u.country, o.order_time
Here, we are trying to find the earliest date for each user_id by using the MIN
function and then INNER JOIN both the tables for each country and order_time.
We use the DISTINCT keyword in case a user buys more than two items in a
day.
5. Write an SQL statement to find the first order GMV of each user. If there is a tie, use the
order with
the lower orderid (30 marks)
SELECT u.userid,
6. Find out what is wrong with the sample data (20 marks)
Answer:
Because the sample data does not reflect the proper amount of goals scored at
each stage of the season, it is erroneous.
Step by step explanation:
Because the sample data does not contain the proper number of goals scored
at any stage of the season, the average number of goals scored is not accurate
for any stage of the season.