SQL - Difficult Query - mysql

I want to do a query where for each diagnostic code - ID (this is a column), select the name of the most common medication - p_name (another column) used to treat that condition i.e., the medication name that more often appears associated to prescriptions (table) for that diagnosis.
This is the structure of my prescription table:
| p_name | lab | doctor_VAT | date_timestamp | ID | dosage | prescription_description |
I started by making a query to count the tuple pairs p_name and ID:
SELECT DISTINCT p.ID,
p.p_name,
COUNT(*) OVER (PARTITION BY p.p_name, p.ID) AS Cnt
FROM prescription AS p
ORDER BY Cnt DESC
And then to this I tried to apply the "greatest_n_per_group" problem to this
(SQL select only rows with max value on a column):
FROM (SELECT DISTINCT p.ID,
p.p_name,
COUNT(*) OVER (PARTITION BY p.p_name, p.ID) AS Cnt
FROM prescription AS p
ORDER BY Cnt DESC) as Tabela
INNER JOIN(
SELECT Tabela2.ID, MAX(Tabela2.Cnt)
FROM (SELECT DISTINCT p.ID,
p.p_name,
COUNT(*) OVER (PARTITION BY p.p_name, p.ID) AS Cnt
FROM prescription AS p
ORDER BY Cnt DESC) as Tabela2
GROUP BY Tabela2.ID
)
But this produces errors, am I going at this the right the way? do you suggest a different method?

Since your MySQL supports Window function, You can simply use -
SELECT ID, p_name
FROM (SELECT ID, p_name, RANK() OVER(PARTITION BY ID ORDER BY CNT DESC) RNK
FROM (SELECT ID,
p_name,
COUNT(*) CNT
FROM prescription
GROUP BY ID,
p_name
) T1
) T2
WHERE RNK = 1

You need FROM ( ) T in this case T is the table name alias for the FROM subquery clause
FROM (SELECT DISTINCT p.ID,
p.p_name,
COUNT(*) OVER (PARTITION BY p.p_name, p.ID) AS Cnt
FROM prescription AS p
ORDER BY Cnt DESC) as Tabela
INNER JOIN(
SELECT Tabela2.ID, MAX(Tabela2.Cnt)
FROM (SELECT DISTINCT p.ID,
p.p_name,
COUNT(*) OVER (PARTITION BY p.p_name, p.ID) AS Cnt
FROM prescription AS p
ORDER BY Cnt DESC) as Tabela2
GROUP BY Tabela2.ID
) T

SELECT
p1.ID,
(SELECT TOP 1 p2.p_name
FROM prescription AS p2
WHERE p2.ID=p1.ID
GROUP BY p2.p_name
ORDER BY count(*) DESC) as MostUsed
FROM prescription AS p1
GROUP BY p1.ID
Above is for MSSQL, below is for MySQL
SELECT
p1.ID,
(SELECT p2.p_name
FROM prescription AS p2
WHERE p2.ID=p1.ID
GROUP BY p2.p_name
ORDER BY count(*) DESC
LIMIT 1) as MostUsed
FROM prescription AS p1
GROUP BY p1.ID
dbfiddle

Related

MySQL-condition on partition size

table1 has 3 columns in my database: id, category, timestamp. I need to query the newest 3 rows from each category:
WITH ranked_rows AS
(SELECT t.*, ROW_NUMBER() OVER (PARTITION BY category ORDER BY t.timestamp DESC) AS rn
FROM table1 AS t)
SELECT ranked_rows.* FROM ranked_rows WHERE rn<=3
now I need to add one more condition: select only from the partitions which have at least 3 rows. how to add this condition?
here is another way:
select * from (
SELECT t.*
, ROW_NUMBER() OVER (PARTITION BY category ORDER BY t.timestamp DESC) AS rn
, count(*) OVER (PARTITION BY category) AS cnt
FROM table1 AS t
) t
WHERE rn<=3 and cnt>= 3
You could make another CTE of only the categories matching your condition, then join to that:
WITH ranked_rows AS
(
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY category ORDER BY t.timestamp DESC) AS rn
FROM table1 AS t
),
categories AS
(
SELECT category
FROM table1
GROUP BY category
HAVING COUNT(*) >= 3
)
SELECT r.* FROM ranked_rows AS r
JOIN categories AS c USING (category)
WHERE r.rn <= 3;

how to display end of line with join mysql

I have 3 tables:
table user
table activity a
table activity b
I want to retrieve all the data in the user table and all the last data in the table of activities a and b, like this :
how do i do sql writing?
In MySQL, I would recommend using row_number() and left join:
select u.*, a.*, b.*
from user u left join
(select a.*,
row_number() over (partition by id_user order by date_a desc) as seqnum
from a
) a
on a.id_user = u.id_user and a.seqnum = 1 left join
(select b.*,
row_number() over (partition by id_user order by date_b desc) as seqnum
from b
) b
on b.id_user = u.id_user and b.seqnum = 1;

mysql query bug

select id, s
from (
select o_user_id as id, sum(total_price) as s
from Orders o
group by o.o_user_id
) as t1
where s = (select max(t1.s) from t1)
it returns a bug said table t1 doesn't exist.
I want to find the id of the user who spends the most money among all of the orders
here is the table of order
That alias is out of scope for the subquery
select id, s
from (
select o_user_id as id, sum(total_price) as s
from Orders o
group by o.o_user_id
) as t1
where s = (select max(t1.s) from t1)
You can do
WITH T1 AS
(
select o_user_id as id, sum(total_price) as s
from Orders o
group by o.o_user_id
)
SELECT id, s
FROM T1
WHERE s = (select max(t1.s) from t1);
If you want only one row, you can use order by and limit:
select o_user_id as id, sum(total_price) as s
from Orders o
group by o.o_user_id
order by s desc
limit 1;
In MySQL 8+, you can use window functions. To get multiple rows in the event of ties, use rank():
select ou.*
from (select o_user_id as id, sum(total_price) as s,
rank() over (order by sum(total_price) desc) as seqnum
from Orders o
group by o.o_user_id
) ou
where seqnum = 1;

MySQL, get sum of two queries

I have three different tables about Product having different columns and structure, assume
Product1, Product2, Product3
So, I'm trying to get sum of count(*) of three tables having same user_id, i.e. foreach user_id field.
Table - Product1
select P.user_id, count(*)
from Product1 P
group by P.user_id
Table - Product2
select P.user_id, count(*)
from Product2 P
group by P.user_id
Table - Product3
select P.user_id, count(*)
from Product3 P
group by P.user_id
They give me user_id field and count(*),
Can I add results of count(*), foreach user_id field? Thanks, in advance
Having three tables with the same structure is usually a sign of poor database design. You should figure out ways to combine the tables into a single table.
In any case, you can aggregate the results. One way is:
select user_id, sum(cnt)
from ((select user_id, count(*) as cnt
from product1
group by user_id
) union all
(select user_id, count(*) as cnt
from product2
group by user_id
) union all
(select user_id, count(*) as cnt
from product3
group by user_id
)
) up
group by user_id;
You want to use union all rather than a join because MySQL does not support full outer join. Union all ensures that users from all three tables are included.
Aggregating twice (in the subqueries and the outer query) allows MySQL to use indexes for the inner aggregations. That can be a performance advantage.
Also, if you are looking for a particular user or set of users, use a where clause in the subqueries. That is more efficient (in MySQL) than bringing all the data together in subqueries and then doing the filtering.
Combine the results using UNION and then do the addition.
Query
select t.`user_id`, sum(`count`) as `total` from(
select `user_id`, count(*) as `count`
from `Product1`
group by `user_id`
union all
select `user_id`, count(*)
from `Product2`
group by `user_id`
union all
select `user_id`, count(*)
from `Product3`
group by `user_id`
) t
group by t.`user_id`;
You could sum the result of union all
select user_id, sum(my_count)
from (
select P.user_id, count(*) my_count
from Product1 P
group by P.user_id
UNION ALL
select P.user_id, count(*)
from Product2 P
group by P.user_id
UNION ALL
select P.user_id, count(*)
from Product3 P
group by P.user_id ) t
group by user_id
Yes you can :)
SELECT SUM(userProducts) userProducts
FROM (
SELECT count(user_id) userProducts FROM Product1 WHERE user_id = your_user_id
UNION ALL
SELECT count(user_id) userProducts FROM Product2 WHERE user_id = your_user_id
UNION ALL
SELECT count(user_id) userProducts FROM Product3 WHERE user_id = your_user_id
) s
Please try below. Not tried in db so could get syntax error.
select p.user_id ,sum(total) from (
select P.user_id, count() total from product1 p group by P.user_id
union all
select P.user_id, count() total from product2 p group by P.user_id
union all
select P.user_id, count(*) total from product3 p group by P.user_id
) a
Yes, we can aggregate results from different tables using join and union based on our requirement. In your case Union All will work perfectly and can write optimised query by using count(1) instead of count(*), as it uses first Index of the table which is more often clustered Index.
select user_id, sum(cnt)
from ((select user_id, count(1) as cnt
from product1
group by user_id
) union all
(select user_id, count(1) as cnt
from product2
group by user_id
) union all
(select user_id, count(1) as cnt
from product3
group by user_id
)
) a
group by user_id;

error in Max count(*) in SQL with same data

I wrote a SQL query to get users with the largest number of purchases.
SELECT name, count(*) as C
FROM sells
GROUP BY user_id
ORDER BY C
LIMIT 1
But, If i have two users with same number of purchase this query can not detect. what's the solution?
Try subquery:
SELECT name, count(*) as C
FROM sells
GROUP BY user_id
HAVING C >= ALL
(SELECT count(*)
FROM sells
GROUP BY user_id)
This will work in any sql version, without using LIMIT in a subquery
Write a subquery that gets the maximum count. Then use HAVING to select all the rows with that count.
SELECT name, COUNT(*) AS c
FROM sells
GROUP BY user_id
HAVING c = (SELECT COUNT(*) c
FROM sells
GROUP BY user_id
ORDER BY c DESC
LIMIT 1)
or this can be done as a join between subqueries:
SELECT t1.*
FROM (SELECT name, COUNT(*) AS c
FROM sells
GROUP BY user_id) AS t1
JOIN (SELECT COUNT(*) AS c
FROM sells
GROUP BY user_id
ORDER BY c DESC
LIMIT 1) AS t2
ON t1.c = t2.c
SELECT name, COUNT(*)
FROM sells
GROUP BY user_id
HAVING COUNT(*) = ( SELECT MAX(C) FROM ( SELECT COUNT(*) AS C FROM sells GROUP BY user_id ) )
You are using LIMIT 1 in the query. It restricts the number of records in the output to one. If you wish to see all the records from the output remove this LIMIT.
If you only need to see one row per every same count, you can modify this query as:
SELECT GROUP_CONCAT(name), count(*) as C
FROM sells
GROUP BY user_id
ORDER BY C
LIMIT 1
This will concatenate both the names having similar counts.