sql cuenta los votos y devuelve el ganador

The objective is to return the image with the most stars(votes). If there's a tie, its broken by the dateTime stamp; the first image to get the most votes. There's 3 columns, imageName, stars, dateTime. To populate this table, a user has cast a vote using a 5 star rating system. Each image can have 1 to 5 stars, and multiple combinations of. The statement needs to add up the total stars associated with each unique imageName, and then evaluate the dateTime stamp, if there's a tie. This is where I get lost. There could be 4 occurrences of a unique imageName, each with 1-star for total of 5 votes. Another imageName could occur once and have a single rating of 4-stars.

Tabla de muestra:

imagName ----- stars ----- DT
____________________________________________________
endeavourLiftOff.jpg ----- 1 ----- 2011-08-25 20:51:18
Image0016.jpg ------- ---- 1 ----- 2011-08-25 20:53:16
Image0016.jpg ------------ 3 ----- 2011-08-25 20:53:17
mantas_05-06.jpg --------- 4 ----- 2011-08-25 20:53:18
help.jpg ----------------- 3 ----- 2011-08-25 20:53:20
txHoldem.jpg ------------- 1 ----- 2011-08-25 20:53:21
Image0016.jpg  ----------- 1 ----- 2011-08-25 20:55:37

preguntado el 28 de agosto de 11 a las 00:08

2 Respuestas

Assuming Microsoft SQL

select top 1 xx.imagName
FROM
(
select imagName,min(dt),sum(stars)
from yourTable
group by imagName
ORDER BY 3 DESC,2 
) xx

Other dialects have other ways of getting the first occurrence

Respondido 28 ago 11, 05:08

Fixed the query after seeing sample data, sorry - Sparky

In MySQL you'd use LIMIT 1 instead of TOP 1 - Derek Kromm

You are getting lost on evaluating the time stamp, because your requirements are ambiguous.

Do you want to take the first timestamp, the last timestamp? The earliest vote overall as the tiebreaker?

I'm going to assume that you want to use the earliest-vote at the tiebreaker.

SELECT 
  A.*
FROM
  ( SELECT 
     I.imagName, 
     SUM(I.stars) as StarVotes,
     MIN(I.DT) as TieBreaker -- "Earliest Vote Tiebreaker"
    FROM 
      MyTable as I 
    GROUP BY I.imagName ) as A
ORDER BY
  A.StarVotes DESC, 
  A.TieBreaker 

You may also care to use "average timestamp" as the tiebreaker, or "average timestamp per star" as the tiebreaker.

Respondido 28 ago 11, 05:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.