SELECT statement to count elements - sql

I have an SQL table consisting of:
[title]
ElementA
ElementA
ElementB
ElementC
ElementA
ElementA
I am trying to find a way to count the element which occurs the most; in this example, that would be
4 because ElementA has occurred 4 times. The problem is, this table is dynamic, so I can't just say SELECT COUNT(*) WHERE title = 'ElementA';
Does anyone have any idea how to compose a SELECT statement to do this? Conceptually, it seems pretty simple, but I just can't make it work.
Many thanks,
Brett

SELECT TOP 1 Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC
or
SELECT Title, COUNT(*) FROM table GROUP BY Title ORDER BY 2 DESC LIMIT = 1
depending on the product you're using.
(Edited to correct the ORDER BY clause).

Select TOP 1 Title
FROM
(
Select
Count(title) k, title
FROM
titles
GROUP BY
TITLE
) Count
ORDER BY
k Desc

Try this to get a complete list
SELECT Title, Count (*) as NumOccurences
FROM MyTable
GROUP BY Title
Order BY NumOccurences
To just get the top dog, use the following with some flavor changes to suit your SQL syntax
SELECT TOP 1 Title, NumOccurences
FROM
(
SELECT Title, Count (*) NumOccurences
FROM MyTable
GROUP BY Title
Order BY Count (*) DESC
) AS Titles

Sql Server:
SELECT TOP 1
Title, COUNT(*) AS Count
FROM tbl
GROUP BY Title
ORDER BY Count DESC
Postgresql, MySQL, etc:
SELECT
Title, COUNT(*) AS Count
FROM tbl
GROUP BY Title
ORDER BY Count DESC
LIMIT 1

Use a group by to group the elements followed by a max on der respective count.. Use nested queries to make the solution simpler.. :)

WITH CTE (Title, Counter) as
(SELECT Title, Count(*) Counter FROM #Test GROUP BY Title)
SELECT Top 1 Title, Counter FROM CTE order by Counter Desc

Related

SQL MAX(COUNT(*)) GROUP BY Alternatives?

I've seen many topics about this and none of them is what I'm looking for.
Say we have this simple table:
CREATE TABLE A (
id INT,
date DATETIME
);
I want to retrieve the MAX value after grouping.
So I do it as follow:
DECLARE #tmpTable TABLE(id INT, count INT);
INSERT INTO #tmpTable SELECT id, COUNT(*) FROM A GROUP BY id;
SELECT MAX(count) FROM #tmpTable;
Is there a better way of doing that?
I've seen a solution in a book that I'm reading that they do it as follows:
SELECT MAX(count) FROM (SELECT COUNT(*) AS count FROM A GROUP BY id);
But this won't work :/ Could be that it works in newer T-SQL servers? Currently I'm using 2008 R2.
You can make use of TOP
SELECT TOP 1 Id,COUNT(*) AS MAXCOUNT
FROM A
GROUP BY Id
ORDER BY MAXCOUNT DESC
If you wants the result with same max count use TOP WITH TIES
SELECT TOP 1 WITH TIES Id,COUNT(*) AS MAXCOUNT
FROM A
GROUP BY Id
ORDER BY MAXCOUNT DESC
Is there a better way of doing that?
We could try using analytic functions:
WITH cte AS (
SELECT id, COUNT(*) cnt, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) rn
FROM A
GROUP BY id
)
SELECT cnt
FROM cte
WHERE rn = 1;
This approach is to turn out a row number, ordered descending by the count, during your original aggregation query by id. The id with the highest count then should be the first record (and this result should hold valid even if more than one id be tied for the highest count).
Regarding your original max query, see the answer by #apomene, and you are just missing an alias.
You also need to add an alias name for your sub query. Try like:
SELECT MAX(sub.count1) FROM (SELECT COUNT(*) AS count1 FROM A GROUP BY id) sub;

SELECT MAX of COUNT

I have a table "well". It contains a column app_rate_unit (type: nvarchar).
My goal is to count every distinct value in the table and let the DBMS (MS Server 2005) give me the most occurring one.
This is my code:
SELECT MAX(app_rate_unit) AS MAX_APP
FROM (SELECT app_rate_unit, COUNT(*) AS co
FROM dbo.well AS w
GROUP BY app_rate_unit
) AS derivedtbl_1
The poblem with it is however, that my DBMS actually delivers the lowest count to me.
SideQuestion: How do I filter for a foreign key (in the table) and NOT NULL (in app_rate_unit) when counting?
select top 1 app_rate_unit, count(*) from dbo.well
group by app_rate_unit
order by count(*) desc
Try this
SELECT
COUNT(app_rate_unit)AS MAX_APP ,
app_rate_unit
FROM
dbo.well
WHERE
app_rate_unit IS NOT NULL
GROUP BY
app_rate_unit
ORDER BY
MAX_APP DESC
The above script will give you the count and the item. You can change the count if you are not sure only one item will have the maximum number of occurrence.
select top 1 count(*) as co from dbo.well as w group by app_rate_unit
order by count(*) desc
In PostgreSQL we can write query which using max of count as
select max(count) from (
select count(id) from Table _name group by created_by,status_id having status_id = 6 ) as Alias
eg
select max(count) from (
select count(id) from orders group by created_by,status_id having status_id = 6 ) as foo

Oracle - select most voted items by distinct users

I have oracle tables like below:
User - UserId,
Item - ItemId,
UserVote - UserVoteId, UserId, ItemId.
Now a user can vote multiple times. I am having a hard time with this query: Get item(s) most voted uniquely - meaning multiple votes from the same person count only as one.
If it was SQL Server, I might have created temp table and all, but I do not know how to handle in Oracle. I'm also having a hard time thinking how to handle tie, meaning if two items both have 18 "unique" votes. I would want both items in that case.
SELECT *
FROM (
SELECT q.*,
DENSE_RANK() OVER (ORDER BY votes DESC) AS dr
FROM (
SELECT itemId, COUNT(DISTINCT userId) AS votes
FROM userVote
GROUP BY
itemId
) q
)
WHERE dr = 1
select ItemID,
VoteCount
from
(
select ItemID,
count(distinct UserId) as VoteCount,
rank() over(order by count(distinct UserId) desc) as rn
from UserVote
group by ItemID
) U
where rn = 1;
Maybe something like this:
WITH CTE
AS
(
SELECT
COUNT(DISTINCT UserId) AS votes,
item.ItemId
FROM
UserVote
GROUP BY
item.ItemId
)
SELECT
*
FROM
item
LEFT JOIN CTE
CTE.ItemId=item.ItemId
ORDER BY
votes DESC;
This will COUNT the users that has voted distinct. So you will have unique users per item id. I don't know what output you want so I ordered so that the item with the most votes are first. If you want just a top 10 or something you can quite easy add it to the select.
How about
SELECT "ItemId", COUNT(*) AS "VoteCount"
FROM (SELECT DISTINCT "ItemId", "UserID"
FROM "UserVote") a
GROUP BY "ItemId"
ORDER BY COUNT(*) DESC
Share and enjoy.
The following ANSI query returns the most voted Items, not considering multiple votes by the same user (you will have to limit the returned rows into your application):
SELECT ItemId, COUNT(DISTINCT UserId) AS "votes"
FROM UserVote
GROUP BY ItemId
ORDER BY "votes" DESC;
If you really need to limit the number of rows into the query, you can do it by using Oracle SQL dialect:
SELECT ItemId, votes
FROM (
SELECT ItemId, COUNT(DISTINCT UserId) AS "votes"
FROM UserVote
GROUP BY ItemId
ORDER BY "votes" DESC
)
WHERE ROWNUM <= :n; -- :n is a placeholder for the number of rows to return

sql query to find the duplicate records

what is the sql query to find the duplicate records and display in descending, based on the highest count and the id display the records.
for example:
getting the count can be done with
select title, count(title) as cnt from kmovies group by title order by cnt desc
and the result will be like
title cnt
ravi 10
prabhu 9
srinu 6
now what is the query to get the result like below:
ravi
ravi
ravi
...10 times
prabhu
prabhu..9 times
srinu
srinu...6 times
If your RDBMS supports the OVER clause...
SELECT
title
FROM
(
select
title, count(*) OVER (PARTITION BY title) as cnt
from
kmovies
) T
ORDER BY
cnt DESC
You can do it in a single query:
Select t.Id, t.title, z.dupCount
From yourtable T
Join
(select title, Count (*) dupCount
from yourtable
group By title
Having Count(*) > 1) z
On z.title = t.Title
order By dupCount Desc
This query uses the Group By and and Having clauses to allow you to select (locate and list out) for each duplicate record. The As clause is a convenience to refer to Quantity in the select and Order By clauses, but is not really part of getting you the duplicate rows.
Select
Title,
Count( Title ) As [Quantity]
From
Training
Group By
Title
Having
Count( Title ) > 1
Order By
Quantity desc
select distinct title, (
select count(title)
from kmovies as sub
where sub.title=kmovies.title) as cnt
from kmovies
group by title
order by cnt desc
You can't do it as a simple single query, but this would do:
select title
from kmovies
where title in (
select title
from kmovies
group by title
order by cnt desc
having count(title) > 1
)

how to calculate count in sql?

I have the following table:
memberid
2
2
3
4
3
...and I want the following result:
memberid count
2 2
3 1 ---Edit by gbn: do you mean 2?
4 1
I was attempting to use:
SELECT MemberID,
COUNT(MemberID)
FROM YourTable
GROUP BY MemberID
...but now I want find which record which has maximum count. IE:
memberid count
2 2
SELECT memberid, COUNT(*) FROM TheTable GROUP BY memberid
Although, it won't work for your desired output because you have "memberid = 3" twice.
Edit: After late update to question...
SELECT TOP 1 WITH TIES --WITH TIES will pick up "joint top".
memberid, COUNT(*)
FROM
TheTable
GROUP BY
memberid
ORDER BY
COUNT(*) DESC
SELECT MemberID, COUNT(MemberID) FROM YourTable GROUP BY MemberID
What if there is a tie (or more) for the max? Do you want to display one or all?
This is how I would do this
SELECT memberid, COUNT(1)
FROM members
GROUP BY memberid
HAVING COUNT(1) = (
SELECT MAX(result.mem_count)
FROM (
SELECT memberid, COUNT(1) as mem_count
FROM members
GROUP BY memberid
) as result
)
I would love to see a more efficient approach though.
Do it like this:
SELECT memberid, COUNT(memberid) AS [count] FROM [Table] GROUP BY memberid
This should do the trick with no subselects required:
select top 1 memberid, COUNT(*) as counted
from members
group by memberid
order by counted desc
Can be done quite easy:
SELECT TOP 1 MemberId, COUNT(*) FROM YourTable GROUP BY MemberId ORDER By 2 DESC
I believe the original poster requested 2 result sets.
The only way I know of to get this (in SQL Server) is to dump the original records into a temp table and then do a SELECT and MAX on that. I do welcome an answer that requires less code!
-- Select records into a temp table
SELECT
Table1.MemberId
,CNT = COUNT(*)
INTO #Temp
FROM YourTable AS Table1
GROUP BY Table1.MemberId
ORDER BY Table1.MemberId
-- Get original records
SELECT * FROM #Temp
-- Get max. count record(s)
SELECT
Table1.MemberId
,Table1.CNT
FROM #Temp AS Table1
INNER JOIN (
SELECT CNT = MAX(CNT)
FROM #Temp
) AS Table2 ON Table2.CNT = Table1.CNT
-- Cleanup
DROP TABLE #Temp
How about this query:
SELECT TOP 1 MemberID,
COUNT(MemberID)
FROM YourTable
GROUP BY MemberID
ORDER by count(MemberID) desc
SELECT count(column_name)
FROM your_table;
You need to use a subselect:
SELECT MemberID, MAX(Count) FROM
(SELECT MemberID, COUNT(MemberID) Count FROM YourTable GROUP BY MemberID)
GROUP BY MemberID
The second group by is needed to return both, the count and the MemberID.