I have table as following in my database
----------------------
id | keyword | location
----------------------
1 | Test-New | 1
2 | Test | 1
3 | Test | 1
4 | Test | 1
----------------------
I need to get results based on location so I used group by
select keyword, location ,count(*) as count from table_name group by location
Now i get following results
----------------------------
keyword | Location | count
---------------------------
Test-New | 1 | 4
---------------------------
but I want most popular keyword for each location and count of each location. In this example I need Test instead of Test-New for location 1 (Because in the actual table Test appeared 3 times and Test-New appeared 1 time).
So I need results like this
--------------------------
keyword | Location | count
--------------------------
Test | 1 | 4
--------------------------
this is working properly ......enjoy RaGu bhai
SELECT
temp.keyword,temp.location,SUM(temp.TotalLocation) AS COUNT
FROM (SELECT
keyword,location,
COUNT(location) AS TotalLocation
FROM
`test`
GROUP BY location,keyword ORDER BY TotalLocation DESC)
temp GROUP BY location;
demo execute here
Can you try this query:
select keyword ,count(keyword) as TotalKeyword from table_name group by location
SELECT a.*
FROM
( SELECT keyword
, location
, COUNT(*) cnt
FROM my_table
GROUP
BY keyword
, location
) a
JOIN
( SELECT keyword
, MAX(cnt) max_cnt
FROM
( SELECT keyword
, location
, COUNT(*) cnt
FROM my_table
GROUP
BY keyword
, location
) x
GROUP
BY keyword
) b
ON b.keyword = a.keyword
AND b.max_cnt = a.cnt;
Your Question is a bit confusion, are you asking for something like this ?
select *,
count(location) as location_count
from test1 group by location, keyword
Related
Here's what I'm trying to do. Let's say I have this table t:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
2 | 18 | 2012-05-19 | y
3 | 18 | 2012-08-09 | z
4 | 19 | 2009-06-01 | a
5 | 19 | 2011-04-03 | b
6 | 19 | 2011-10-25 | c
7 | 19 | 2012-08-09 | d
For each id, I want to select the row containing the minimum record_date. So I'd get:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
4 | 19 | 2009-06-01 | a
The only solutions I've seen to this problem assume that all record_date entries are distinct, but that is not this case in my data. Using a subquery and an inner join with two conditions would give me duplicate rows for some ids, which I don't want:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
5 | 19 | 2011-04-03 | b
4 | 19 | 2009-06-01 | a
How about something like:
SELECT mt.*
FROM MyTable mt INNER JOIN
(
SELECT id, MIN(record_date) AS MinDate
FROM MyTable
GROUP BY id
) t ON mt.id = t.id AND mt.record_date = t.MinDate
This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.
I could get to your expected result just by doing this in mysql:
SELECT id, min(record_date), other_cols
FROM mytable
GROUP BY id
Does this work for you?
To get the cheapest product in each category, you use the MIN() function in a correlated subquery as follows:
SELECT categoryid,
productid,
productName,
unitprice
FROM products a WHERE unitprice = (
SELECT MIN(unitprice)
FROM products b
WHERE b.categoryid = a.categoryid)
The outer query scans all rows in the products table and returns the products that have unit prices match with the lowest price in each category returned by the correlated subquery.
I would like to add to some of the other answers here, if you don't need the first item but say the second number for example you can use rownumber in a subquery and base your result set off of that.
SELECT * FROM
(
SELECT
ROW_NUM() OVER (PARTITION BY Id ORDER BY record_date, other_cols) as rownum,
*
FROM products P
) INNER
WHERE rownum = 2
This also allows you to order off multiple columns in the subquery which may help if two record_dates have identical values. You can also partition off of multiple columns if needed by delimiting them with a comma
This does it simply:
select t2.id,t2.record_date,t2.other_cols
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2
where t2.rownum = 1
If record_date has no duplicates within a group:
think of it as of filtering. Simpliy get (WHERE) one (MIN(record_date)) row from the current group:
SELECT * FROM t t1 WHERE record_date = (
select MIN(record_date)
from t t2 where t2.group_id = t1.group_id)
If there could be 2+ min record_date within a group:
filter out non-min rows (see above)
then (AND) pick only one from the 2+ min record_date rows, within the given group_id. E.g. pick the one with the min unique key:
AND key_id = (select MIN(key_id)
from t t3 where t3.record_date = t1.record_date
and t3.group_id = t1.group_id)
so
key_id | group_id | record_date | other_cols
1 | 18 | 2011-04-03 | x
4 | 19 | 2009-06-01 | a
8 | 19 | 2009-06-01 | e
will select key_ids: #1 and #4
SELECT p.* FROM tbl p
INNER JOIN(
SELECT t.id, MIN(record_date) AS MinDate
FROM tbl t
GROUP BY t.id
) t ON p.id = t.id AND p.record_date = t.MinDate
GROUP BY p.id
This code eliminates duplicate record_date in case there are same ids with same record_date.
If you want duplicates, remove the last line GROUP BY p.id.
This a old question, but this can useful for someone
In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql
select t.*
from (select m.*, #g := 0
from MyTable m --here i have a big query
order by id, record_date) t
where (1 = case when #g = 0 or #g <> id then 1 else 0 end )
and (#g := id) IS NOT NULL
Basically I ordered the result and then put a variable in order to get only the first record in each group.
The below query takes the first date for each work order (in a table of showing all status changes):
SELECT
WORKORDERNUM,
MIN(DATE)
FROM
WORKORDERS
WHERE
DATE >= to_date('2015-01-01','YYYY-MM-DD')
GROUP BY
WORKORDERNUM
select
department,
min_salary,
(select s1.last_name from staff s1 where s1.salary=s3.min_salary ) lastname
from
(select department, min (salary) min_salary from staff s2 group by s2.department) s3
I have a table in mysql
==================================================
ID | TEAM_ID | PTS | COMPETITION
==================================================
1 | 1 | 10 | zc
--------------------------------------------------
2 | 1 | 15 | po
--------------------------------------------------
3 | 1 | 5 | sp
I'm trying to find out the right query to get result of SUM of columns PTS where column team id equals 1. This is what I've got
SELECT SUM(pts) FROM
(SELECT SUM(pts) FROM `stats_2016/2017` WHERE `team_id`='1' AND `competition`='zc'
UNION ALL
SELECT SUM(pts) FROM `stats_2016/2017` WHERE `team_id`='1' AND `competition`='po'
UNION ALL
SELECT SUM(pts) FROM `stats_2016/2017` WHERE `team_id`='1' AND `competition`='sp'
)
I would like to get a result of 30 (10+15+5)...
Three changes:
Assign an alias to the inline view (derived table)
Assign an alias to the expression in the first SELECT of the inline view. (That alias will be used the column name in the derived table.(
in the outer query, reference the column in the inline view by the assigned alias.
SELECT SUM(v.totpts) AS totpts
-- 3.-- ^^^^^^
FROM ( SELECT SUM(pts) AS totpts FROM `stats_2016/2017` ...
-- 2.-- ^^ ^^^^^^
UNION ALL
SELECT SUM(pts) FROM `stats_2016/2017` ...
) v
-- 1.-- ^
Try with Group by and IN mysql operator,which work with dynamic value of team_id
Like this
SELECT SUM(pts) FROM `stats_2016/2017` WHERE `competition` in ('zc','po','sp')
group by `team_id`
I have a table like
+------+----------+
| id | location |
+------+----------+
| 1 | TVM |
| 2 | KLM |
| 3 | EKM |
+------+----------+
And I have an array of id like [1,2,1,3,1]. I need to get the result as
+------+----------+
| id | location |
+------+----------+
| 1 | TVM |
| 2 | KLM |
| 1 | TVM |
| 3 | EKM |
| 1 | TVM |
+------+----------+
I am already tried WHERE IN like conditions but no luck.
A where statement cannot multiply the number of rows. It can only filter rows out. You want a join:
select tl.*
from tablelike tl join
(select 1 as n union all select 2 union all select 1 union all
select 3 union all select 1
) n
on tl.id = n.n;
Note: if you are already generating the list via a query or from a table, then use that for the query rather than passing the list out of the database and then back in.
You could also return this result with a query like this; this uses a separate SELECT to return each occurrence of row with id=1.
( SELECT id, location FROM mytable WHERE id IN (1,2)
ORDER BY id
)
UNION ALL
( SELECT id, location FROM mytable WHERE id IN (1,3)
ORDER BY id
)
UNION ALL
( SELECT id, location FROM mytable WHERE id IN (1)
ORDER BY id
)
Following a similar pattern, the result could be obtained by combining the results from five SELECT statements, each returning a separate row. That would probably be a little simpler to achieve from a small array, e.g.
$glue = ") ) UNION ALL
(SELECT id, location FROM mytable WHERE id IN (";
$sql = "(SELECT id, location FROM mytable WHERE id IN ("
. implode($glue, $myarray)
. ") )";
I am trying to select distinct rows within my SQL table, however I'm not having luck in labeling the returned rows appropriately using the code below:
SELECT #row:=#row+1 as rank,
a.id,
a.name
FROM table a,
( SELECT #row:=0) b
GROUP BY a.id
ORDER BY a.name ASC
This query will return the following:
| RANK | ID | NAME
--------------------------
2 | 4483 | Bob
8 | 9453 | Joe
10 | 4543 | Maurice
What I want it to return is this, however:
| RANK | ID | NAME
--------------------------
1 | 4483 | Bob
2 | 9453 | Joe
3 | 4543 | Maurice
Would it be more appropriate for me to use a DISTINCT query for a query of this magnitude?
As per Marc B's solution, I decided to wrap my query with another one however instead I decided to Select DISTINCT columns rather than grouping them which would remove my margin of error, by using this code
SELECT #row:=#row+1 as rank, a.id, a.name FROM
(
SELECT DISTINCT id, name
FROM Table1
) a, (SELECT #row:=0) b
ORDER BY a.name ASC
I have the below table and I want to do the following:
Count the number of times each item appears in the table
Count the DISTINCT number of items
Group the items by name
+-------+---------+
| id | names |
+-------+---------+
| 1 | Apple |
| 2 | Orange |
| 3 | Grape |
| 4 | Apple |
| 5 | Apple |
| 6 | Orange |
| 7 | Apple |
| 8 | Grape |
+-------+---------+
For the 1. and 3. points I have the following query which works quite well:
SELECT * ,
COUNT(names) as count_name,
FROM tbl_products WHERE type = '1'
GROUP BY names
So I get:
Apple (4)
Orange (2)
Grape (2)
Now I want to also count the number of grouped by rows and added a line to count the distinct elements, however there is some problem, since MySQL accepts the query but cannot output a result:
SELECT * ,
COUNT(names) as count_name,
COUNT(DISTINCT names) as count_total
FROM tbl_products WHERE type = '1'
GROUP BY names
Can anyone advice what might be the problem?
EDIT: For more clearance I want to get a table like this:
+-------+---------+------------+-------------+
| id | names | count_ctg | count_total |
+-------+---------+------------+-------------+
| 1 | Apple | 4 | 3 |
| 2 | Orange | 2 | 3 |
| 3 | Grape | 2 | 3 |
+-------+---------+------------+-------------+
Why not just use the query you are using:
SELECT * ,
COUNT(names) as count_name,
FROM tbl_products WHERE type = '1'
GROUP BY names
This query achieves all three objectives.
1) You get a count of the number of each name value in count_name.
2) The number of distinct names values will be equal to the number of rows in the result set , since you are grouping by names. Pretty much any client-side MySQL DB connection library will enable you to retrieve this value.
3) You meet your third criteria of grouping by name by explictly using GROUP BY names
Of course the value for id in the result set is meaningless, you may want to only select names and count_names.
1-.Count the number of times each item appears in the table:
SELECT names, count(names) FROM tbl_products WHERE type = '1' group by names
2-. How many distinct items exist in the table:
SELECT DISTINCT names FROM tbl_products WHERE type = '1'
3-. Group the items by name:
SELECT count(DISTINCT names) as Total FROM tbl_products WHERE type = '1'
As your last EDIT (ALL IN ONE):
SELECT id, names, count(names), total FROM tbl_products, (select count(distinct names) as total from tbl_products) as total WHERE type = '1' group by names
You can get the count of distinct names in a subquery, then OUTER JOIN that thing back into your main query where you already solved for 1 and 3:
SELECT names ,
COUNT(names) as count_name,
Total
FROM tbl_products
OUTER JOIN (SELECT count(DISTINCT names) as Total FROM tbl_products) t2
WHERE type = '1'
GROUP BY names
You can use the SQL Windowing OVER()
This query returns the row_number() function as the id column in the results, and the over(...) for row_number requires an order by clause. You could order by whatever you want, but it most be ordered by something.
;WITH vwGroups (name, Quantity) AS
(
SELECT name
, COUNT(*)
FROM tbl_products
GROUP BY name
)
SELECT ROW_NUMBER() OVER(ORDER BY Quantity DESC, name) AS id
, name
, Quantity AS count_name
, COUNT(*) OVER () AS count_total
FROM vwGroups