--- /dev/null
+#include "fetch_top_chosen_songs_for_tournament.h"
+
+// small utility function so we can stick TopChosenSongs in a std::set
+bool TopChosen::operator< (const TopChosen &other) const
+{
+ if (title != other.title)
+ return (title < other.title);
+ return (frequency < other.frequency);
+}
+
+FetchTopChosenSongsForTournament::FetchTopChosenSongsForTournament(unsigned tournament, unsigned num, std::vector<TopChosen> *chosen)
+ : tournament(tournament), num(num), chosen(chosen) {}
+
+void FetchTopChosenSongsForTournament::operator() (pqxx::transaction<> &t)
+{
+ chosen->erase(chosen->begin(), chosen->end());
+
+ // Again, this will break if a song has more than one short title
+ pqxx::result res( t.exec(
+ "SELECT title, shorttitle, COUNT(*) AS frequency FROM scores NATURAL JOIN songs NATURAL LEFT JOIN songshorttitles WHERE tournament="
+ + pqxx::to_string(tournament) + " AND chosen='t' AND song is NOT NULL GROUP BY title,shorttitle ORDER BY COUNT(*) DESC LIMIT "
+ + pqxx::to_string(num)) );
+
+ for (pqxx::result::const_iterator i = res.begin(); i != res.end(); ++i) {
+ TopChosen ts;
+
+ ts.title = i["title"].as(ts.title);
+ ts.shorttitle = i["shorttitle"].as(ts.shorttitle);
+ ts.frequency = i["frequency"].as(ts.frequency);
+
+ chosen->push_back(ts);
+ }
+}