right now I'm trying to return the biggest COUNT(DISTINCT column)-number from a mysql table.
It's hard to describe, so I'll give you an example:
My table has the following columns: s_id, k_id, p_id.
Now I want to count the different s with the condition that every entry has the same p_id, too. I need this to prepare a HTML-Table (so i know how many Columns this table will have).
Data Example:
This is what I got, so far:
SELECT COUNT(DISTINCT k_id) AS a FROM `table`
the problem with this is, that there may be 4 different k_ids but 3 of them are related to p_id = 1 and the last one is releated to p_id = 2.
a returns 4 instead of 3.
Thanks for support!
I think you want this:
select p_id, count(distinct s_id) as cnt
from table
group by p_id
order by cnt desc
limit 1;
Please consider this:
select max(count(distinct(k_id))) from table
group by p_id
Related
I'm trying to get the unique records after sorting the data in specific order.
The data table looks like this
SELECT * FROM category_products;
Now, requirement is to Order By the records on category_id and then select unique rows of product_id. I wrote the below query to sort the records
SELECT * FROM category_products ORDER BY category_id=2 desc;
When I try to Group By this sorted results with product_id, then the results aren't in right order. Even tried Group By clause in both child query and same query.
SELECT * FROM
(SELECT
*
FROM
category_products
ORDER BY category_id = 2 DESC) AS cat_products
GROUP BY cat_products.product_id;
Current Output:
Expected Output:
The result isn't the right one for which I'm looking for. Kindly help me guys, this doesn't seems to that tricky thing but I'm kind of stuck with it.
requirement is to Order By the records on category_id and then select
unique rows of product_id. I wrote the below query to sort the records
This should be what you are looking for:
SELECT DISTINCT product_id
,(SELECT category_id
FROM category_products
WHERE product_id = CP.product_id
ORDER BY category_id
LIMIT 1) AS cat_id
FROM category_products CP;
you need a SUBQUERY with an ORDER BY and LIMIT 1
It's a little unclear on how you aim to achieve this but from my understanding you can maybe create a custom sorting column to fulfill your requirement. See example below:
SELECT *,
CASE WHEN category_id=2 THEN 1
WHEN category_id=4 THEN 2
ELSE 99 END AS rownum
FROM category_products
ORDER BY rownum, product_id;
I'm using CASE to define a custom rownum and use it in the ORDER BY clause.
Demo fiddle here: https://www.db-fiddle.com/f/kAcGYtng2RWCf2Yhn5N1C9/0
Similar to this issue: MySQL 5.7 group by latest record
I'm not sure how to do this properly in 5.7. Also with possibility of 2nd sort column. Working query in 5.6 that I'm trying to replicate in 5.7:
SELECT id FROM test
GROUP BY category
ORDER BY sort1 DESC, sort2 DESC
id is not always the highest, so MAX(id) does not work.
Looking into the link above, the solution for single sort should be:
SELECT t1.*
FROM test t1
INNER JOIN (
SELECT category, max(sort) AS sort FROM test GROUP BY category
) t2 ON t2.category = t1.category AND t2.sort = t1.sort
But how will it work with 2 sorting?
You are using GROUP BY the wrong way.
Think of group by as a way to separate data row into different groups. Each group has multiple rows, based on the value of group by column.
Once you get those groups, selecting table columns (as in: select *) is like picking any row from that group randomly. This is not helpful nor useful.
Usually once we group records (or rows), we need to find meta information about those records. For example: get us the count of records in that group (as in: select count(*)), or the sum of values of a specific column in that group (as in: select sum(price)), or get the min, max or avg values.
So in a nutshell, when you use group by you should use on of the aggregation functions with it, otherwise it's not going to do you any good.
Why don't you have the ORDER BY at your outer query, instead?
SELECT *
FROM (
SELECT 100 AS id, 1 AS category, NULL AS sort
UNION
SELECT 200 AS id, 1 AS category, 2 AS sort
) dt
GROUP BY category
ORDER BY sort DESC;
It seems that what happened to the data when it was grouped, it took the first data while neglecting the ORDER BY DESC. On your first query, it ordered descending first then group by took the first record which is 200. And yes, this shouldn't be the way you should use GROUP BY. It is used in conjunction with aggregate functions.
when you select a column in a group by query that is not one of the columns you are grouping by, (ie, your id) you have no control over the value unless you use another aggregate function. If you want to sort, use MIN or MAX:
SELECT MAX(id), category, FROM `test2`
GROUP BY category; -- always returns 200
SELECT MIN(id), category, FROM `test2`
GROUP BY category; -- always returns 100
I have table(T1) with userid(int), user_name(char) and contact(char) as columns.
I need to iterate over the table to find out which user_name is present multiple times in the table and the count. And I will be using the count to delete the user_name if the occurrence is more than three times.
I tried using
select user_name,count(user_name) from T1 group by user_name having count(*)>3
The output is
user_name EXPR_1
chris 4
Fred 5
Now if I need to use the values in EXPR_1. How to iterate over this result set without creating a new/temp table.
Thanks
Use your query as a sub-select:
DELETE FROM T1 WHERE user_name IN (
SELECT user_name
FROM T1
GROUP BY user_name
HAVING COUNT(user_name) > 3
)
Response to comment:
Well, now I'm confused as to what you're asking for. If all you want to do is sort by highest count, then just do this:
SELECT
user_name,
COUNT(user_name) AS numOccurrences
FROM T1
GROUP BY user_name
HAVING COUNT(user_name) > 3
ORDER BY numOccurrences DESC
Now when you iterate through them, it will be ordered by the number of occurrences, highest to lowest.
Are you asking how to iterate over the results? If so, that completely depends on what tool you're using to execute this query and how you're sending it to your other application. Please elaborate on that.
I am using query like
select * from audittable where a_id IN (1,2,3,4,5,6,7,8);
For each ID its returning 5-6 records. I wanted to get the last but one record for each ID.
Can i do this in one sql statement.
Try this query
SELECT
*
FROM
(SELECT
#rn:=if(#prv=a_id, #rn+1, 1) as rId,
#prv:=a_id as a_id,
---Remaining columns
FROM
audittable
JOIN
(SELECT #rn:=0, #prv:=0) t
WHERE
a_id IN (1,2,3,4,5,6,7,8)
ORDER BY
a_id, <column> desc)tmp --Replace column with the column with which you will determine it is the last record
WHERE
rId=1;
If your database is having DateCreated or any column in which you are saving the DateTime as well like when your data is inserted for a particular row then you may use query like
select at1.* from audittable at1 where
datecreated in( select max(datecreated) from audittable at2
where
at1.id = at2.id
order by datecreated desc
);
You may also use LIMIT function as well.
Hope you understand and works for you.
In SQLite, you have the columns a_id and b. For each a_id you get a set of b's. Let you want
to get the latest/highest (maximum in terms of row_id, date or another naturally increasing index) one of b's
SELECT MAX(b), *
FROM audittable
GROUP BY a_id
Here MAX help to get the maximum b from each group.
Bad news that MySQL doesn't associate MAX b with other *-columns of the table. But it still can be used in case of simple table with a_id and b columns!
I am trying to select the latest entry of the duplicate entries against the ticket_id in a mysql table , My current is something like this.
SELECT * ,
COUNT(*) AS cnt ,
ticket_id
FROM temp_tickets
GROUP BY ticket_id
ORDER BY id DESC
It gives the number of times a row is duplicated but i am able to select the latest one of those mulptiple rows
Let say i have 3 ticket_id's which got duplicated for 5 times so now i want to select the latest occurrence from all these 3 id's .
Lemme know if i have to be more specific.
Thanks
Here's one way (assuming "latest" means "greatest id")
SELECT temp_tickets.*
FROM temp_tickets
JOIN ( SELECT MAX(id) AS id
FROM temp_tickets
GROUP BY ticket_id
HAVING COUNT(*) > 1
) latest ON latest.id = temp_tickets.id
I suspect it might be possible to come up with a more efficient solution involving user variables but I'll leave that to someone else...