<code> Jag tolkar det som att du bara vill ha ut detta för ett visst voteCategoryId? I sådana fall borde detta fungera: såhär blev den.. tror den är braMS SQL hämta ut en rad som är unik men som är MAX i en group by
SELECT voteCategories.title, MAX(DISTINCT votes.count) AS voteCount, MAX(DISTINCT votes.articleId) AS articleId
FROM voteCategories INNER JOIN
votes ON voteCategories.id = votes.voteCategoryId
GROUP BY voteCategories.id, voteCategories.title
ORDER BY voteCount
</code>
Denna kod funkar inte... Bara ett exempel
jag har två tabeller
voteCategories
och votes
voteCategories innehåller bara två fält, id och title (id på kategori och namn på kategori)
votes innehåller id, articleId, voteCategoryId och count (articleId är vilken artikel som röstningen hör till, voteCategoryId vilken vategori röstningne hör till samt hur många som röstat på denna artikel för denna röstkategori
Vad jag nu vill göra är att slumpa En röstkategori och få ut artikeln som leder denna kategori.
Queryn ovan hämtar ut max counten för varje kategori, men hur hämtar jag ut articelId som hör till den counten? MAX() kommer ju vara returnera det Id som är högst. inte som är kopplat till counten
Tack på förhand, AndersSv: MS SQL hämta ut en rad som är unik men som är MAX i en group by
SELECT TOP 1 voteCategories.title, votes.count AS voteCount, votes.articleId
FROM voteCategories INNER JOIN
votes ON voteCategories.id = votes.voteCategoryId
WHERE voteCategories.id = 1
ORDER BY voteCount DESC
/JohanSv:MS SQL hämta ut en rad som är unik men som är MAX i en group by
<code>
SELECT leader.*, MIN(categories.title) AS categoryTitle, MIN(categories.type) AS categoryType, MAX(persons.name) AS personName
FROM (
SELECT TOP 1 articles.id, articles.publishDate, articles.title, articles.headTitleId, articles.pathTitle, votes.count AS voteCount, voteCategories.title AS voteCategoryTitle
FROM articles
INNER JOIN votes ON votes.articleId = articles.id
INNER JOIN voteCategories ON votes.voteCategoryId = voteCategories.id
WHERE articles.publishDate >= @publishDate AND (votes.voteCategoryId =
(SELECT TOP 1 id
FROM voteCategories AS randomVoteCat
ORDER BY NEWID())) AND articles.activeStatus = @activeStatus
ORDER BY voteCount DESC, articles.title) AS leader
INNER JOIN articleContexts ON leader.id = articleContexts.articleId
LEFT OUTER JOIN persons ON articleContexts.personId = persons.id
LEFT OUTER JOIN categories ON articleContexts.categoryId = categories.id
GROUP BY leader.id, leader.publishDate, leader.title, leader.headTitleId, leader.pathTitle, leader.voteCount, leader.voteCategoryTitle
</code>