0

First, I already read all post with same title post. But no solution solve my problem.

I want my query result's like this

kategori | hitung

 Good    |   2

 Nice    |   0

great    |   1 

with this query:

SELECT kategori, COALESCE(COUNT(kategori), 0) AS hitung FROM tb_cust WHERE id_sales=9 GROUP BY kategori DESC

But the result only return 2 data:

kategori | hitung

 Good    |   2

great    |   1 

Did my query is wrong?

Edit:

this is my table and the data inside of it

table name: tb_cust

id_cust  |  name_cust  |  kategori  |  id_sales

   1     |  Name 1     |  Good      |     9

   2     |  Name 2     |  Good      |     9

   3     |  Name 3     |  Great     |     9
3
  • 3
    share sample data from where you want this output Commented Nov 17, 2018 at 5:51
  • Please share your table data so someone can help you Commented Nov 17, 2018 at 6:08
  • Read this may help you stackoverflow.com/q/3597577/2893413 Commented Nov 17, 2018 at 6:28

2 Answers 2

1

The values of kategori that are available in tb_cust according to your condition(WHERE id_sales=9) is 'Good', 'Great'.

What you could have instead is

Step 1.First have a block in cte -> kategori_val to show all the possible values of kategori

Step 2. Left join with the data in tb_cust and get the count of records

--I guess "with" isnt working in mysql database

   select a.kategori,count(b.kategori) as hitung
     from (select distinct kategori /*I am assuming we have Good,Great and Nice available in tb_cust*/
             from tb_cust) a
left join tb_cust b
       on a.kategori=b.kategori
      and b.id_sales=9 
group by a.kategori 
order by 2 DESC
Sign up to request clarification or add additional context in comments.

4 Comments

I have updated the "with" clause to be an inline query. Please check
It nearly close, but my "nice" kategori return hitung 1 not 0
Was a silly mistake to have used count(*), it should be count(b.kategori), i have updated the answer
Tq this is perfect
0

You can probably do this with conditional aggregation:

SELECT kategori, SUM(id_sales = 9) as hitung
FROM tb_cust
GROUP BY kategori DESC;

This assumes that the categories have some record in the table.

If not, you can use the lookup table for the categories:

SELECT k.kategori, SUM(c.id_sales = 9) as hitung
FROM tb_kategori k LEFT JOIN
     tb_cust c
     ON k.kategori = c.kategori
GROUP BY k.kategori DESC;

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.