简体   繁体   中英

Advice needed for sql query. Need to count the amount of time a song has been played in a festival and how many times it won during the finals

hope you can help me, this is the structure of the table: codIscr (identifies song, who plays it and the event in which it has been played) (Primary Key with dataser) dataser (the date of the event in which it was played) vote Posizione(the position relative to the date, the winner of the last date of the event is the final winner)

This is the query i used:

SELECT X.codIscr, count(X.codIscr=Y.codIscr),count(X.Posizione=1 AND Y.Posizione=1) 
    FROM concorre X, concorre Y 
     WHERE X.codIscr=Y.codIscr AND X.dataSer!=Y.dataSer AND 
            X.codIscr IN(SELECT DISTINCT codIscr FROM iscrizione WHERE codEv=1) 
     GROUP BY X.codIscr HAVING count(X.codIscr=Y.codIscr)>1

It should give me as result 4 different codIscr, 2 as the amount of time the songs were played in the event (for all 4 of them) and 1 as the amount of times they got first in the event (during "semifinals" and such) exept for the winner of the final date of the event which should have 2 as number of times it got first... Instead all 4 songs as last count give me 2... Can anyone help, plz?

The query doesn't look right. Assuming the question is as in the title: "Need to count the amount of time a song has been played in a festival and how many times it won during the finals", I don't expect to see a self-join in the query.

I think you just need conditional aggregation:

SELECT c.codIscr, count(*) as TimesPlayed, sum(c.Posizione = 1) as NumTimesFirst
FROM concorre c
GROUP BY c.codIscr;

I'm not sure what iscrizione is for, but if you want to limit the songs, you can do that in a where clause:

SELECT c.codIscr, count(*) as TimesPlayed, sum(c.Posizione = 1) as NumTimesFirst
FROM concorre c
WHERE c.codIscr IN (SELECT i.codIscr FROM iscrizione i WHERE i.codEv = 1) 
GROUP BY c.codIscr;

The distinct in the in clause is redundant.

If you want songs that have been played at least two times, then add a having clause:

HAVING count(*) > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM