Question

select stars
from business
where city = 'Avon';

Data:

+-------+
| stars |
+-------+
|   2.5 |
|   4.0 |
|   5.0 |
|   3.5 |
|   1.5 |
|   3.5 |
|   4.5 |
|   3.5 |
|   2.5 |
|   4.0 |
+-------+

Result Needed:

Star     Rating Count
0           0
1           0
1.5         1
2           0
2.5         2
3           0
3.5         3
4           2
4.5         1
5           1

No correct solution

OTHER TIPS

The basis of the query is

SELECT stars, COUNT(*) ratio_count FROM business
 where city = 'Avon'   GROUP BY  "stars"

Which would give amount üf the stars, but as you also wanted the number 0 for all the stars not given, you must add also a table that contains all stars

CREATE TABLE business
    ("stars" INTEGER,
    "city" varchar(10))
;
INSERT INTO business
    ("stars","city")
VALUES
    (2.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (4.0,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (5.0,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (3.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (1.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (3.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (4.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (3.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (2.5,'Avon')
;
INSERT INTO business
    ("stars","city")
VALUES
    (4.0,'Avon')
;
SELECT 
  t2."stars",  IFNULL(ratio_count,0) ratio_count
FROM 
  (select a as stars from
(select 0.5 as a union select 1 union select 1.5 
union select 2 union select 2.5  union select 3 
union select 3.5 union select 4 union select 4.5 union select 5 )) t2 
LEFT JOIN (SELECT stars, COUNT(*) ratio_count FROM business
where city = 'Avon'   GROUP BY  "stars") t1 
ON t2.stars = t1.stars
stars | ratio_count
----: | ----------:
  0.5 |           0
    1 |           0
  1.5 |           1
    2 |           0
  2.5 |           2
    3 |           0
  3.5 |           3
    4 |           2
  4.5 |           1
    5 |           1

db<>fiddle here

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top