سؤال

For customer reviews on my products, I have them stored in SQL something like the below:

    durability | cost | appearance
  ----------------------------------
        5      |  3   |     4
        2      |  4   |     2
        1      |  5   |     5

Each value is an out of five score in the three categories.

When I want to print this information on page, I'd like to order them in descending order by the average score of an individual review.

SELECT *
    FROM reviews
    ORDER BY (durability+cost+appearance)/3 DESC

Obviously this doesn't work, but is there a way to get my result? I don't want to include an average column in SQL because outside of this one small application, it serves zero purpose.

هل كانت مفيدة؟

المحلول

Use ORDER BY instead of SORT BY:

SELECT *
FROM reviews
ORDER BY (durability+cost+appearance)/3 DESC

EDIT:

To see the order by value, try adding one more column in the select clause:

SELECT *,(durability+cost+appearance)/3 as OrderValue
FROM reviews
ORDER BY (durability+cost+appearance)/3 DESC

Sample output:

DURABILITY  COST    APPEARANCE  ORDERVALUE
5           3       4           4
1           5       5           3
2           4       2           2
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top