-1

我有这个查询:

select Keyword, Keywords.QuoteId, count(*) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword, Keywords.QuoteId

该查询有效,除了 TotalTags 始终为 1,在我添加它工作的联接之前。

对于应具有 TotalTags=5 的关键字,它会显示关键字 5 次,计数为 1。

如果我Keywords.QuoteId从组中删除该查询将返回错误。

4

3 回答 3

1

这行得通吗?

select Keyword, count(QuoteImages.QuoteId) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword

正如@Nenad 指出的那样,可能是 QuoteId 导致了问题。您不想看到每个 QuoteId 的单独结果。

于 2013-03-30T19:41:27.943 回答
1

You've added an additional column to your grouping, so if you have 5 unique quotes for any keyword, of course the count for each combination will be 1. Try:

select k.Keyword, k.QuoteId, 
  count(*) OVER (PARTITION BY k.Keyword) AS TotalTags 
from [enter_your_database_name_here].[dbo].Keywords AS k
INNER JOIN [enter_your_database_name_here].[dbo].QuoteImages AS q
ON k.QuoteId = q.QuoteId
group by k.Keyword, k.QuoteId;

If you don't want to see a row for each QuoteId, then take it out of both the SELECT list and the GROUP BY. You might also not care about the join at all, why not gamble to maybe get slightly better performance (or, at worst, the same):

SELECT k.Keyword, COUNT(*) AS TotalTags
FROM [enter_your_database_name_here_if_you_want_to
  run_from_another_database_for_some_reason].dbo.Keywords AS k
WHERE EXISTS
(
  SELECT 1 FROM [enter_your_database_name_here_if_you_want_to
  run_from_another_database_for_some_reason].dbo.QuoteImages
  WHERE QuoteID = k.QuoteID
)
GROUP BY k.Keyword;

If you don't care about the individual Quotes then I have no idea why you added . You say you got an error, but is this because you added it only to the SELECT list or only to the GROUP BY list? Why would you introduce it to either list?

于 2013-03-30T20:28:27.037 回答
0

当你join用 a替换时会发生什么left outer join

select Keyword, Keywords.QuoteId, count(*) AS TotalTags 
from [QuotesTemple].[dbo].Keywords 
left outer join [QuotesTemple].[dbo].QuoteImages 
ON QuoteImages.QuoteId=Keywords.QuoteId
group by Keyword, Keywords.QuoteId

我能想到两件事。一个是您在添加联接keywords.QuoteId时也添加了。每个报价都有一个标签。

另一个是只有一些关键字有引号。

于 2013-03-30T13:09:38.647 回答