1

having this question in mind

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

How can I get count of distinct row by condition

SELECT COUNT(DISTINCT productId -- THIS IS WHERE I NEED TO PUT CONDITION --) WHERE keyword='$keyword'

I need to cont distinct rows if that row doesn't have type <> 1

3
  • If you need distinct productId and multiple exist - which row to take - it can be important because rows having the same productid can have different types values Commented Sep 8, 2014 at 10:08
  • Does the condition necessarily have to to be inside the COUNT function? Commented Sep 8, 2014 at 10:11
  • I want all records to be selected, because I'm doing calculation on them, I just don't want count of products if they have type 1 Commented Sep 8, 2014 at 10:12

3 Answers 3

2

I am not sure but are you looking for this:

SELECT COUNT(DISTINCT productId) from table_name WHERE keyword='$keyword' and type!=1

EDIT:

SELECT COUNT(DISTINCT CASE WHEN type <> 1 
                           THEN productId 
                      ELSE NULL 
                      END
             ) 
FROM table_name
WHERE keyword='$keyword'
Sign up to request clarification or add additional context in comments.

2 Comments

no I want all records to be selected, because I'm doing calculation on them, I just don't want count of prodcuts if they have type 1
@tinybyte:- You may use the CASE then. See the update
1

Assuming there is an issue with modifying the WHERE clause, you can use CASE operator or IF function:

SELECT COUNT(DISTINCT CASE WHEN type <> 1 THEN productId ELSE NULL END) 
FROM <table>
WHERE keyword = '<keyword>'

Comments

0

The extra condition goes in the WHERE clause, not in the SELECT clause.

SELECT COUNT(DISTINCT productId)
WHERE keyword = '$keyword'
AND type != 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.