Scenario
I have a users table that has a column for the users iso_code_2 for their country of residence and nationality, and in another table I have all the countries in different languages, so what I want to do is get the country text for the users residence and nationality. I know the problem is the GROUP BY but I do not know how to solve it.
Tables
/* Users table */
╔══════╦═════════════╦════════════╦═════════════╦═══════════════╗
║ id ║ firstname ║ lastname ║ residence ║ nationality ║
╚══════╩═════════════╩════════════╩═════════════╩═══════════════╝
│ 1 │ Joe │ Doe │ JP │ PH │
├──────┼─────────────┼────────────┼─────────────┼───────────────┤
│ 2 │ Lisa │ Simpson │ US │ AR │
├──────┼─────────────┼────────────┼─────────────┼───────────────┤
│ 3 │ Homer │ Simpson │ JP │ JP │
└──────┴─────────────┴────────────┴─────────────┴───────────────┘
/* Countries table */
╔══════╦═══════════════╦══════════════╦═════════════════════╗
║ id ║ language_id ║ iso_code_2 ║ country ║
╚══════╩═══════════════╩══════════════╩═════════════════════╝
│ 1 │ 1 │ JP │ Japan │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 2 │ 2 │ JP │ 日本 │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 3 │ 1 │ PH │ Philippines │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 4 │ 2 │ PH │ フィリピン │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 5 │ 1 │ US │ United States │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 6 │ 2 │ US │ 米国 │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 7 │ 1 │ AR │ Argentina │
├──────┼───────────────┼──────────────┼─────────────────────┤
│ 8 │ 2 │ AR │ アルゼンチン │
└──────┴───────────────┴──────────────┴─────────────────────┘
/* Expected results */
╔══════╦═════════════╦════════════╦════════════════════════╦═══════════════════════╗
║ id ║ firstname ║ lastname ║ residence_country ║ nationality_country ║
╚══════╩═════════════╩════════════╩════════════════════════╩═══════════════════════╝
│ 1 │ Joe │ Doe │ Japan │ Philippines │
├──────┼─────────────┼────────────┼────────────────────────┼───────────────────────┤
│ 1 │ Lisa │ Simpson │ United States │ Argentina │
├──────┼─────────────┼────────────┼────────────────────────┼───────────────────────┤
│ 1 │ Homer │ Simpson │ Japan │ Japan │
└──────┴─────────────┴────────────┴────────────────────────┴───────────────────────┘
Current Query
SELECT
u.id,
u.firstname,
u.lastname,
CASE c.iso_code_2
WHEN u.nationality THEN c.country
END AS nationality_country,
CASE c.iso_code_2
WHEN u.residence THEN c.country
END AS residence_country
FROM
users AS u
LEFT JOIN
countries AS c ON c.language_id = 1 WHERE c.iso_code_2 IN (u.nationality, u.residence)
GROUP BY u.id
ORDER BY u.created_at DESC
LIMIT 15
Wrong results
╔══════╦═════════════╦════════════╦════════════════════════╦═══════════════════════╗
║ id ║ firstname ║ lastname ║ residence_country ║ nationality_country ║
╚══════╩═════════════╩════════════╩════════════════════════╩═══════════════════════╝
│ 1 │ Joe │ Doe │ NULL │ Philippines │
├──────┼─────────────┼────────────┼────────────────────────┼───────────────────────┤
│ 1 │ Lisa │ Simpson │ NULL │ Argentina │
├──────┼─────────────┼────────────┼────────────────────────┼───────────────────────┤
│ 1 │ Homer │ Simpson │ NULL │ Japan │
└──────┴─────────────┴────────────┴────────────────────────┴───────────────────────┘
You group by is retaining only one row per user in the result. Depending on MySQL's preferences, it will either contain the residence_country or the nationality_country.
You need to select twice from the country table to get your desired results (and it will make the query easier)
SELECT
u.id,
u.firstname,
u.lastname,
cn.country
cr.country
FROM
users AS u
LEFT JOIN countries AS cn ON cn.language_id = 1 WHERE cn.iso_code_2 = u.nationality
LEFT JOIN countries AS cr ON cr.language_id = 1 WHERE cr.iso_code_2 = u.residence
Related
I have the following payments table
┌─name───────────────────────────┬─type────────────────────────────┐
│ payment_id │ UInt64 │
│ factory │ String │
│ user_id │ UInt64 │
│ amount_cents │ Int64 │
│ action │ String │
│ success │ UInt8 │
│ country │ FixedString(2) │
│ created_at │ DateTime │
│ finished_at │ Nullable(DateTime) │
└────────────────────────────────┴─────────────────────────────────┘
With sample data
┌─factory───┬─────────finished_at─┬─payment_id─┬─country─┬─action──┬─amount_cents─┬─user_id───┬
│ 0_factory │ 2021-01-18 00:00:01 │ 1 │ BY │ payment │ 1 │ 1 │
│ 0_factory │ 2021-01-18 00:00:02 │ 2 │ BY │ payment │ 1 │ 1 │
│ 1_factory │ 2021-01-18 00:00:02 │ 2 │ PL │ win │ 4 │ 1 │
│ 1_factory │ 2021-01-18 00:00:03 │ 3 │ PL │ win │ 7 │ 1 │
│ 2_factory │ 2021-01-18 00:00:01 │ 4 │ PL │ win │ 7 │ 1 │
│ 2_factory │ 2021-01-18 00:00:02 │ 1 │ PL │ payment │ 7 │ 1 │
│ 2_factory │ 2021-01-18 00:00:03 │ 2 │ PL │ win │ 7 │ 1 │
│ 2_factory │ 2021-01-18 00:00:04 │ 3 │ GR │ win │ 2 │ 1 │
└───────────┴─────────────────────┴────────────┴─────────┴─────────┴─────────┴────────────────┘
This is an example of what I have right now with
SELECT
factory,
user_id,
payment_id,
action,
created_at
FROM payments_all
WHERE (payments_all.action = 'payment') AND (payments_all.factory IN ('0_factory', '1_factory', '2_factory')) AND isNotNull(payments_all.created_at)
GROUP BY
factory,
user_id,
payment_id,
action
HAVING (min(created_at) >= toDate('2019-01-01 00:00:00')) AND (min(created_at) < toDate('2021-10-01 00:00:00'))
ORDER BY user_id
┌─factory───┬─user_id─┬─payment_id─┬─action──┬──────────created_at─┐
│ 1_factory │ 1 │ 1 │ payment │ 2021-02-04 09:00:00 │
│ 0_factory │ 1 │ 1 │ payment │ 2021-01-17 00:00:01 │
│ 0_factory │ 1 │ 2 │ payment │ 2021-01-17 00:00:06 │
└───────────┴─────────┴────────────┴─────────┴─────────────────────┘
I need to add new column first_payment
first_payment takes value 1 if action is payment && it is first payment for a user. Otherwise it takes value 0.
the first_payment should be checked for all period
So expected result is:
┌─factory───┬─────────finished_at─┬─payment_id─┬─country─┬─action──┬─amount_cents─┬─user_id───┬first_payment─┐
│ 0_factory │ 2021-01-18 00:00:01 │ 1 │ BY │ deposit │ 1 │ 1 │ 1 │
│ 0_factory │ 2021-01-18 00:00:02 │ 2 │ BY │ deposit │ 1 │ 1 │ 0 │
│ 1_factory │ 2021-01-18 00:00:02 │ 2 │ PL │ win │ 4 │ 1 │ 0 │
│ 1_factory │ 2021-01-18 00:00:03 │ 3 │ PL │ win │ 7 │ 1 │ 0 │
│ 2_factory │ 2021-01-18 00:00:01 │ 4 │ PL │ win │ 7 │ 1 │ 0 │
│ 2_factory │ 2021-01-18 00:00:02 │ 1 │ PL │ deposit │ 7 │ 1 │ 1 │
│ 2_factory │ 2021-01-18 00:00:03 │ 2 │ PL │ win │ 7 │ 1 │ 0 │
│ 2_factory │ 2021-01-18 00:00:04 │ 3 │ GR │ win │ 2 │ 1 │ 0 │
└───────────┴─────────────────────┴────────────┴─────────┴─────────┴─────────┴────────────────┘
I couldn't find much about ClickHouse, but it doesn't appear to support Windowed Functions.
Your example output also seems to be exactly the same as your sample table, plus one additional column, so I'm not sure what you GROUP BY was meant to achieve.
So, I'd use a LEFT JOIN on to a sub-query.
SELECT
payments_all.*,
CASE WHEN user_summary.user_id IS NOT NULL THEN 1 ELSE 0 END AS first_payment
FROM
payments_all
LEFT JOIN
(
SELECT
user_id,
factory,
MIN(created_at) AS first_created_at
FROM
payments_all
WHERE
action = 'payment'
GROUP BY
user_id,
factory
)
AS user_summary
ON payments_all.user_id = user_summary.user_id
ON payments_all.factory = user_summary.factory
AND payments_all.created_at = user_summary.first_created_at
WHERE
(payments_all.factory IN ('0_factory', '1_factory', '2_factory'))
AND (payments_all.created_at >= toDate('2019-01-01 00:00:00'))
AND (payments_all.created_at < toDate('2021-10-01 00:00:00'))
As I can see for first payment the payment_id is always 1. So, I think you can use CASE WHEN payment_id=1 Then 1 ELSE 0 END AS first_payment. Please check query below =>
WITH CTE AS
(SELECT
factory,
user_id,
payment_id,
action,
created_at
FROM payments_all
WHERE (payments_all.action = 'payment') AND (payments_all.factory IN ('0_factory', '1_factory', '2_factory')) AND isNotNull(payments_all.created_at)
GROUP BY
factory,
user_id,
payment_id,
action
HAVING (min(created_at) >= toDate('2019-01-01 00:00:00')) AND (min(created_at) < toDate('2021-10-01 00:00:00'))
) T1
SELECT *,CASE WHEN payment_id=1 Then 1
ELSE 0 END AS first_payment
FROM CTE
ORDER BY T1.user_id
NOTE: Query is written in SQL Server. Please check and let me know.
Is there a way in ClickHouse to do a GROUP BY DAY/MONTH/YEAR() with a timestamp value? Having hard time figuring it out while rewriting MySQL queries to ClickHouse. My MySQL queries looks like so...
SELECT COUNT(this), COUNT(that) FROM table WHERE something = x AND stamp BETWEEN startdate AND enddate
SELECT COUNT(this), COUNT(that) FROM table WHERE something = x AND stamp BETWEEN startdate AND enddate GROUP BY DAY(stamp)
SELECT COUNT(this), COUNT(that) FROM table WHERE something = x AND stamp BETWEEN startdate AND enddate GROUP BY MONTH(stamp)
SELECT COUNT(this), COUNT(that) FROM table WHERE something = x AND stamp BETWEEN startdate AND enddate GROUP BY YEAR(stamp)
Quite simple AND SLOW in MySQL, but I do not know how to do the aggregates in ClickHouse.
Thanks!
To get part of date use function toYear, toMonth, toDayOfMonth by the next way:
SELECT
toMonth(time) AS month,
count()
FROM
(
SELECT
number,
addDays(now(), number) AS time
FROM numbers(8)
)
GROUP BY month
/*
┌─month─┬─count()─┐
│ 1 │ 7 │
│ 2 │ 1 │
└───────┴─────────┘
*/
To get multiple grouping set use WITH ROLLUP-modifier:
SELECT
toYear(time) AS year,
toMonth(time) AS month,
toDayOfMonth(time) AS day,
count()
FROM
(
SELECT
number,
addDays(now(), number) AS time
FROM numbers(8)
)
GROUP BY
year,
month,
day
WITH ROLLUP
/*
┌─year─┬─month─┬─day─┬─count()─┐
│ 2021 │ 2 │ 1 │ 1 │ // day
│ 2021 │ 1 │ 29 │ 1 │ // day
│ 2021 │ 1 │ 31 │ 1 │ // day
│ 2021 │ 1 │ 26 │ 1 │ // day
│ 2021 │ 1 │ 25 │ 1 │ // day
│ 2021 │ 1 │ 28 │ 1 │ // day
│ 2021 │ 1 │ 30 │ 1 │ // day
│ 2021 │ 1 │ 27 │ 1 │ // day
│ 2021 │ 1 │ 0 │ 7 │ // month
│ 2021 │ 2 │ 0 │ 1 │ // month
│ 2021 │ 0 │ 0 │ 8 │ // year
│ 0 │ 0 │ 0 │ 8 │
└──────┴───────┴─────┴─────────┘
*/
I have a table called student_grades
╔════╤═══════╤═══════╤═════════════════════╗
║ id │ name │ grade │ date_added ║
╠════╪═══════╪═══════╪═════════════════════╣
║ 1 │ bob │ 23 │ 2019-10-01 14:25:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 2 │ james │ 45 │ 2019-10-02 17:31:27 ║
╟────┼───────┼───────┼─────────────────────╢
║ 3 │ mike │ 42 │ 2019-10-03 18:08:13 ║
╟────┼───────┼───────┼─────────────────────╢
║ 4 │ bob │ 68 │ 2019-10-04 02:00:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 5 │ mike │ 83 │ 2019-10-04 09:28:43 ║
╟────┼───────┼───────┼─────────────────────╢
║ 6 │ bob │ 23 │ 2019-10-04 11:42:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 7 │ james │ 86 │ 2019-10-05 12:11:20 ║
╚════╧═══════╧═══════╧═════════════════════╝
First I want to select all the names from the table BUT I only want their most recent record. For example. James has 2 records. One with id 2 AND ONE WITH id 7. So I want the one with id 7 because the id is larger.
So to do that I get:
╔════╤═══════╤═══════╤═════════════════════╗
║ id │ name │ grade │ date_added ║
╠════╪═══════╪═══════╪═════════════════════╣
║ 5 │ mike │ 83 │ 2019-10-04 09:28:43 ║
╟────┼───────┼───────┼─────────────────────╢
║ 6 │ bob │ 23 │ 2019-10-04 11:42:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 7 │ james │ 86 │ 2019-10-05 12:11:20 ║
╚════╧═══════╧═══════╧═════════════════════╝
.
SELECT *
FROM student_grade
GROUP BY id
ORDER BY id DESC
Now I want to randomize those rows and get the first 2 rows of those randomized rows
╔════╤═══════╤═══════╤═════════════════════╗
║ id │ name │ grade │ date_added ║
╠════╪═══════╪═══════╪═════════════════════╣
║ 7 │ james │ 86 │ 2019-10-05 12:11:20 ║
╟────┼───────┼───────┼─────────────────────╢
║ 5 │ mike │ 83 │ 2019-10-04 09:28:43 ║
╚════╧═══════╧═══════╧═════════════════════╝
How do I randomize those 3 rows. My end goal is to get the latest records of each student. I don't care about their past records. I just want their most recent ones, and then I want to randomize them. What is the most efficient way of me doing this?
This query will give you the results you want. It finds the row for each student which has the maximum id value, and then sorts all those rows randomly and selects 2:
SELECT *
FROM student_grade s
WHERE id = (SELECT MAX(id)
FROM student_grade
WHERE name = s.name)
ORDER BY RAND()
LIMIT 2
Dependent on the size of your table, it may be more efficient to implement this as a JOIN:
SELECT s1.*
FROM student_grade s1
JOIN (SELECT name, MAX(id) AS id
FROM student_grade
GROUP BY name) s2 ON s2.name = s1.name AND s2.id = s1.id
ORDER BY RAND()
LIMIT 2;
Demo on dbfiddle
This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 3 years ago.
I am trying to select the latest record of all the students (I don't want a student's past grade, only their most recent). Currently, its just returning me one result.
student_grade table
╔════╤═══════╤═══════╤═════════════════════╗
║ id │ name │ grade │ date_added ║
╠════╪═══════╪═══════╪═════════════════════╣
║ 1 │ bob │ 23 │ 2019-10-01 14:25:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 2 │ james │ 45 │ 2019-10-02 17:31:27 ║
╟────┼───────┼───────┼─────────────────────╢
║ 3 │ mike │ 42 │ 2019-10-03 18:08:13 ║
╟────┼───────┼───────┼─────────────────────╢
║ 4 │ bob │ 68 │ 2019-10-04 02:00:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 5 │ mike │ 83 │ 2019-10-04 09:28:43 ║
╟────┼───────┼───────┼─────────────────────╢
║ 6 │ bob │ 23 │ 2019-10-04 11:42:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 7 │ james │ 86 │ 2019-10-05 12:11:20 ║
╚════╧═══════╧═══════╧═════════════════════╝
What I want it to return
╔════╤═══════╤═══════╤═════════════════════╗
║ id │ name │ grade │ date_added ║
╠════╪═══════╪═══════╪═════════════════════╣
║ 5 │ mike │ 83 │ 2019-10-04 09:28:43 ║
╟────┼───────┼───────┼─────────────────────╢
║ 6 │ bob │ 23 │ 2019-10-04 11:42:00 ║
╟────┼───────┼───────┼─────────────────────╢
║ 7 │ james │ 86 │ 2019-10-05 12:11:20 ║
╚════╧═══════╧═══════╧═════════════════════╝
My sql statement
SELECT id, DISTINCT name, grade, max(date_added)
FROM student_grade
ORDER BY date_added DESC
Or an efficient way of returning me this detail. I'm a little stuck as to how I can get this.
Use a subquery to first select the max id for each name and then the record related to this id :
SELECT sg.*
FROM student_grade sg
INNER JOIN (
SELECT name, max(id) as id
FROM student_grade
GROUP BY name
) x ON x.name = sg.name AND x.id = sg.id
I assumed that the id is the right field to find the last added record. Maybe date_added would be more rightful but if they have the same functional meaning, using id is more efficient
I'm having some problems in counting some entries in my database.
I have following query:
SELECT ref_training_date, training_date FROM fynslund.users_training
INNER JOIN training
ON training.id = users_training.ref_training_date
WHERE attendance = 1
Which gives me following results:
┌──────┬───────────────┐
│ ID │ DATE │
├──────┼───────────────┤
│ '55' │ '2018-01-09' │
│ '55' │ '2018-01-09' │
│ '54' │ '2018-02-03' │
│ '54' │ '2018-02-03' │
│ '54' │ '2018-02-03' │
│ '54' │ '2018-02-03' │
└──────┴───────────────┘
How do I count how many times the date with ID '55' appears?
You need to GOUP BY ref_training_date and then COUNT(training_date):
SELECT ref_training_date, COUNT(training_date) AS date_count
FROM fynslund.users_training
INNER JOIN training ON training.id = users_training.ref_training_date
WHERE attendance = 1
GROUP BY ref_training_date