我有一个三联接,看起来像这样:
select DATE_FORMAT(Posts.PostDate, '%Y-%m-%d'), (Tags.TagName)
from Posts
join PostTags
on Posts.PK_PostID = PostTags.FK_PostID
join Tags
on Tags.PK_TagID = PostTags.FK_TagID
where Tags.TagName = 'Money'
结果如下:
但是我希望它按日期分组,然后在它旁边标记的使用次数。我无法弄清楚。像这样:
2012-12-26 10
2012-12-27 4
答案 0 :(得分:1)
没有小提琴,我相信你想要的是这个:
select DATE_FORMAT(Posts.PostDate, '%Y-%m-%d'), count(Tags.TagName)
from Posts
join PostTags
on Posts.PK_PostID = PostTags.FK_PostID
join Tags
on Tags.PK_TagID = PostTags.FK_TagID
where Tags.TagName = 'Money'
group by DATE_FORMAT(Posts.PostDate, '%Y-%m-%d')
答案 1 :(得分:0)
我没有你的桌子,但试试这个:
SELECT DATE_FORMAT(Posts.PostDate, '%Y-%m-%d') as PDate, COUNT(*) FROM Posts
JOIN PostTags ON Posts.PK_PostID = PostTags.FK_PostID
JOIN Tags ON Tags.PK_TagID = PostTags.FK_TagID
WHERE Tags.TagName = 'Money'
GROUP BY PDate
有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
答案 2 :(得分:0)
这是一个简单的聚合查询。我选择使用您的查询作为子查询来编写它,尽管这不是绝对必要的:
select thedate,
sum(case when tagname = 'Money' then 1 else 0 end) as NumMoney
from (select DATE_FORMAT(Posts.PostDate, '%Y-%m-%d') as thedate, (Tags.TagName)
from Posts join
PostTags
on Posts.PK_PostID = PostTags.FK_PostID join
Tags
on Tags.PK_TagID = PostTags.FK_TagID
) t
group by thedate
答案 3 :(得分:0)
你必须使用group By子句,如果标签名在输出中,你也必须按标签名称进行gropup。 (否则,如果有多个行具有相同的日期但标签名称不同,那么应该为具有任何特定日期的一行输出哪个标签名称?....
select DATE_FORMAT(p.PostDate, '%Y-%m-%d'), (t.TagName),
Count(Distinct t.tagname) tagCount
from Posts p
join PostTags pt
on pt.FK_PostID - p.PK_PostID
join Tags t
on t.PK_TagID = pt.FK_TagID
group by DATE_FORMAT(p.PostDate, '%Y-%m-%d'), (t.TagName)
如果可能有多个行具有相同的日期但标签名称不同,您需要为每个不同的tagName计数,那么您还需要按标记名进行分组。这就是你想要的吗?
答案 4 :(得分:0)
您需要按以下方式对组进行SUB-SELECT:
SELECT T.*, Tags.TagName
FROM (select DATE_FORMAT(Posts.PostDate, '%Y-%m-%d'), PostTags.FK_TagID, count(*) PostsCount
from Posts
join PostTags
on Posts.PK_PostID = PostTags.FK_PostID
group by DATE_FORMAT(Posts.PostDate, '%Y-%m-%d'), PostTags.FK_TagID) as P
inner join Tags
on Tags.PK_TagID = P.FK_TagID