Home > Software design >  How to create SQL statement for listing top 5 items for Chart.js?
How to create SQL statement for listing top 5 items for Chart.js?

Time:01-17

I have a database and wish to display the top 5 no. of asked questions for Chart.js by using the question as label and no. of ask as value. May I know how can I do?

enter image description here

CodePudding user response:

To display the top 5 by number of asks, in mySQL you can write

SELECT `question`, `no_asks`
FROM `yourtablename`
ORDER BY `no_asks` DESC
LIMIT 5

The

ORDER BY `no_asks` DESC 

lists the results in descending order of the number of asks (so you'll get the most asks first)

and the

LIMIT 5

restricts the results to a maxmimum of 5 rows.

More info

CodePudding user response:

Use dense_rank() function to display the top 5 number of asks in case of duplication.

Assume that your table name is chart_testSO

select question,no_ask from(
select dense_rank() 
OVER (  order by no_ask desc )  as r,* from chart_testSO
)temp
where temp.r<=5

On different MySQL versions there is no dense_rank() function. You can use following query

set @val =1;
set @pk1:=(select no_ask from chart_testSO order by no_ask desc limit 1);

SELECT  question,
no_ask,
denseRank
FROM
(
SELECT  question,
no_ask,
@val := if(@pk1=no_ask,  @val, @val 1) as denseRank,
@pk1 := no_ask
FROM
(  SELECT  question, no_ask
FROM    chart_testSO
ORDER BY no_ask desc) A
) B where denseRank<=5;
  •  Tags:  
  • Related