How to create MySQL nested query with DISTINCT and COUNT - mysql

I have one mySQL table here with some data.
Before asking for help I tried MySQL Nested Select Query? before, but it's not working for me.
So, what I want to do is to list the total of the dir_id with more doc_id. The table should have only two columns as a result. dir_id and total. In this case, the table results shall have for the 1st-row dir_id = 3 and total = 3. In other words, dir_id 3, has 3 doc_id.
I tried to make use of DISTINCT and COUNT to construct a nested query as follow:
SELECT COUNT(*), AS total `dir_id`
FROM
(SELECT DISTINCT dir_id, doc_id
FROM `dir_subdir`
ORDER BY `dir_subdir`.`dir_id` DESC)
Here is the message error I got after running the query. Unfortunately, it is not clear for me, so I cannot fix it.
Any help will be grateful. Thank you!

You're missing GROUP BY dir_id. You also have the comma misplaced.
You can do this without the subquery using COUNT(DISTINCT column)
SELECT dir_id, COUNT(DISTINCT doc_id) AS total
FROM dir_subdir
GROUP BY dir_id
ORDER BY dir_id DESC

Related

Select Count into Multiple Column SQL

I wondering if I can do a unique Select to diferent count of distinct items into many columns. By now this works fine, but doing only one count by column like:
SELECT provincia,count(provincia) as total_provincia
FROM museos
group by provincia ORDER BY provincia
Result of Select for uno count
Then if a try with other field, still looks good as I needed too:
SELECT localidad,count(localidad) as total_localidad
FROM museos
group by localidad ORDER BY localidad
Result of another Select Query
But, when I trying to get both column with its count at one Select query, it's suppose to be something like this:
SELECT provincia,localidad,count(localidad) as total_localidad,
count(provincia) as total_provincia
FROM museos
group by provincia,localidad ORDER BY provincia,localidad
Then I got:
Select for both count
i've been looking everywhere around Stack and websites with examples, unfortunately I couldn't find something similar of what I tryied to do, and I realy got no answer for why only seems to work one of the count, and always for the small granular data, in this case, "localidad". At the same time the other count of "provincia" is ignored, and its column named as total is just a copie of the values of the first one, as we can see. So, is it possible to make a Select query that return two or more count made on diferent columns, in order to get this kind of response:
Hopefull Select query expected
I mean, finaly the organization of the required table result in a tree scheme, where data like "provincia" are the body or the root, and its capillary data would be the leaves. It's kind of weird built a Query this way, but I think is not impossible at all. So any help or coment I'll be greatful.
You can use over(partition by):
select distinct
provincia, count(provincia) over(partition by provincia) 'count_provincia'
,localidad, count(localidad) over(partition by localidad) 'count_localidad'
from museos
order by provincia;

Mysql DISTINCT with more than one column (remove duplicates)

My database is called: (training_session)
I try to print out some information from my data, but I do not want to have any duplicates. I do get it somehow, may someone tell me what I do wrong?
SELECT DISTINCT athlete_id AND duration FROM training_session
SELECT DISTINCT athlete_id, duration FROM training_session
It works perfectly if i use only one column, but when I add another. it does not work.
I think you misunderstood the use of DISTINCT.
There is big difference between using DISTINCT and GROUP BY.
Both have some sort of goal, but they have different purpose.
You use DISTINCT if you want to show a series of columns and never repeat. That means you dont care about calculations or group function aggregates. DISTINCT will show different RESULTS if you keep adding more columns in your SELECT (if the table has many columns)
You use GROUP BY if you want to show "distinctively" on a certain selected columns and you use group function to calculate the data related to it. Therefore you use GROUP BY if you want to use group functions.
Please check group functions you can use in this link.
https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html
EDIT 1:
It seems like you are trying to get the "latest" of a certain athlete, I'll assume the current scenario if there is no ID.
Here is my alternate solution:
SELECT a.athlete_id ,
( SELECT b.duration
FROM training_session as b
WHERE b.athlete_id = a.athlete_id -- connect
ORDER BY [latest column to sort] DESC
LIMIT 1
) last_duration
FROM training_session as a
GROUP BY a.athlete_id
ORDER BY a.athlete_id
This syntax is called IN-SELECT subquery. With the help of LIMIT 1, it shows the topmost record. In-select subquery must have 1 record to return or else it shows error.
MySQL's DISTINCT clause is used to filter out duplicate recordsets.
If your query was SELECT DISTINCT athlete_id FROM training_session then your output would be:
athlete_id
----------
1
2
3
4
5
6
As soon as you add another column to your query (in your example, the column called duration) then each record resulting from your query are unique, hence the results you're getting. In other words the query is working correctly.

SQL: Group By is mismatching records

I'm trying to get the highest version within a group. My query:
SELECT
rubric_id,
max(version) as version,
group_id
FROM
rubrics
WHERE
client_id = 1
GROUP BY
group_id
The Data:
The Results:
The rubric of ID 2 does not have a version of 2, why is this being mismatched? What do I need to do to correct this?
Edit, not a duplicate:
This is not a duplicate of SQL Select only rows with Max Value on a Column , which is a post I have read and referenced before writing this. My question is not how to find the max, my question is why is the version not matched to the correct ID
MySQL is confusing you by letting you get away with having a column in your select that isn't in your group by. To resolve the issue, make sure you don't select any field that isn't in the group by.
Instead of trying to get everything in one statement, you will need to use a subquery to find the max_version_id and then join to it.
SELECT T.*
FROM rubrics T
JOIN
(
SELECT
group_id,
max(version) as max_version
FROM
rubrics
GROUP BY
group_id
) dedupe
on T.group_id = dedupe.group_id
and T.version_id = dedupe.max_version_id
WHERE
T.client_id = 1
Edit: So MySQL allows it, but I don't think it's a good practise to use it.
You are trying to query non-aggregated data from an aggregated query. You should not do that.
A GROUP BY takes the field it should make group of rows with (in your case, what you say with your GROUP BY is: give me a result per different group_id) and gives a result (the aggregated data) based on the grouping.
Here, you try to access non aggregated data (rubric_id in your case). For some reason, the query does not crash and picks a "random" id in your aggregated data.

MySQL get totals from grouped value

I have a table that's setup like this:
**user_items**
user_item_id
user_id
item_id
User's can have the same item_id associated. If I want to see as a whole, how many items there are assigned to users, this is simply a count.
However, I'd like to the total count factoring in distinct item_id's. So grouping by the item_id, but as a total.
Any idea how I can do this?
Thank you
Select count(*) from ...
is what you are looking for
EDIT: I'm sorry.. This is indeed wrong.
There must be an easier solution, but this will do what you want:
select count() from (select count() from YOURTABLE group by YOURCOL) as WHATEVER;
This counts the rows in the resulting table of the inner query.

How to get count of rows returned from nested and WHERE IN used query in MySQL?

SELECT kullaniciNick,
kullaniciAdi,
kullaniciSoyadi
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
ORDER BY kullaniciSoyadi
at the query i need the count of rows to check if it is over 6 or less.
When i used the COUNT(*) i got an error message. That said it must used with GROUP BY.
Thank you.
Try this:
SELECT kullaniciNick,
kullaniciAdi,
kullaniciSoyadi,
count(*) -- Added this line
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
GROUP BY 1,2,3 -- Added this line
ORDER BY kullaniciSoyadi
You can't have a result, and it's size in one query.
Use 2 queries. First one will give you the size of result and second one will be the result. The First query, should be like this:
SELECT count(*)
FROM panelkullanicilari
WHERE id IN
(SELECT user_id
FROM proje_ekip
WHERE proje_id=11)
the second one , is just like the query you wrote above.