Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DISTINCT and COUNT together in a MySQL Query

Tags:

sql

mysql

People also ask

Can we use distinct with count in MySQL?

Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. Display all records from the table using select statement.

How do you use count and distinct together?

The correct syntax for using COUNT(DISTINCT) is: SELECT COUNT(DISTINCT Column1) FROM Table; The distinct count will be based off the column in parenthesis. The result set should only be one row, an integer/number of the column you're counting distinct values of.

How do I count distinct values in MySQL?

To count distinct values, you can use distinct in aggregate function count(). The result i3 tells that we have 3 distinct values in the table.

How use distinct and sum together in MySQL?

SELECT links.id, count(DISTINCT stats.id) as clicks, count(DISTINCT conversions.id) as conversions, sum(conversions. value) as conversion_value FROM links LEFT OUTER JOIN stats ON links.id = stats. parent_id LEFT OUTER JOIN conversions ON links.id = conversions. link_id GROUP BY links.id ORDER BY links.


use

SELECT COUNT(DISTINCT productId) from  table_name WHERE keyword='$keyword'

I would do something like this:

Select count(*), productid
from products
where keyword = '$keyword'
group by productid

that will give you a list like

count(*)    productid  
----------------------
 5           12345   
 3           93884   
 9           93493    

This allows you to see how many of each distinct productid ID is associated with the keyword.


You were close :-)

select count(distinct productId) from table_name where keyword='$keyword'

FYI, this is probably faster,

SELECT count(1) FROM (SELECT distinct productId WHERE keyword = '$keyword') temp

than this,

SELECT COUNT(DISTINCT productId) WHERE keyword='$keyword'

What the hell of all this work anthers

it's too simple

if you want a list of how much productId in each keyword here it's the code

SELECT count(productId),  keyword  FROM `Table_name` GROUP BY keyword; 

SELECTING DISTINCT PRODUCT AND DISPLAY COUNT PER PRODUCT

for another answer about this type of question this is my another answer for getting count of product base on product name distinct like this sample below:

Table Value

select * FROM Product

Counted Product Name

SELECT DISTINCT(Product_Name),
(SELECT COUNT(Product_Name) 
from Product  WHERE Product_Name = Prod.Product_Name)  
as `Product_Count`
from Product as Prod

Record Count: 4; Execution Time: 2ms