1

StackOverflowデータダンプで遊んでいます。今私はT-SQLの問題を抱えています:

1か月および1年あたりの質問数のリストを次のように選択できます。

select datepart(year, posts.creationdate) as year,
datepart(month, posts.creationdate) as month, 
count(distinct posts.id) as questions
from posts
inner join posttags on posttags.postid = posts.id
inner join tags on tags.id = posttags.tagid
where posts.posttypeid = 1
group by datepart(month, posts.creationdate), 
datepart(year, posts.creationdate)
order by datepart(year, posts.creationdate), 
datepart(month, posts.creationdate)

-rowを追加するand tags.tagname = 'scala'と、すべての「scala-questions」の数がわかります。WHERE質問の総数と特定のタグを含む質問の数の両方を同じ結果セット(異なる列)に表示する方法はありますか?

追加するand tags.tagname = 'scala'と、1か月あたりの質問の総数が表示されなくなるためです。

これらの結果セットを1つにまとめる方法について何かアイデアはありますか?

4

2 に答える 2

2

2セットのデータ(月ごとの質問と月ごとのscala質問)があるため、これを行うには2つのクエリが必要になります。考えられる解決策の1つは、一般的なテーブル式を使用して、データの2つの「一時ビュー」を作成することです。例として:

with total as (
    select datepart(year, posts.creationdate) as year,
           datepart(month, posts.creationdate) as month, 
           count(distinct posts.id) as questions
    from posts
        inner join posttags on posttags.postid = posts.id
        inner join tags on tags.id = posttags.tagid
    where posts.posttypeid = 1
    group by datepart(month, posts.creationdate), datepart(year, posts.creationdate)
), scala as (
    select datepart(year, posts.creationdate) as year,
           datepart(month, posts.creationdate) as month, 
           count(distinct posts.id) as questions
    from posts
        inner join posttags on posttags.postid = posts.id
        inner join tags on tags.id = posttags.tagid
     where posts.posttypeid = 1 and tags.tagname = 'scala'
    group by datepart(month, posts.creationdate), datepart(year, posts.creationdate)
)
select total.year, total.month, total.questions as total_questions, scala.questions as scala_questions
from total
    join scala on total.year = scala.year and total.month = scala.month
order by total.year, total.month​

その結果はここで見ることができます。

于 2011-07-30T13:31:30.277 に答える
2

left outer joinに対してを使用するとposttagscount(posttags.tagid)null以外の値のみがカウントされます。また、左側の外部結合にはタグのみが含まれているため、 inscalaをスキップできます。distinctcount(distinct posts.id)

select datepart(year, posts.creationdate) as year,
       datepart(month, posts.creationdate) as month,
       count(*) as questions,
       count(posttags.tagid) as sc
from posts
  left outer join posttags
    on posttags.postid = posts.id and
       posttags.tagid = (select id
                         from tags
                         where tagname = 'scala')
where posts.posttypeid = 1
group by datepart(month, posts.creationdate),
         datepart(year, posts.creationdate)
order by datepart(year, posts.creationdate),
         datepart(month, posts.creationdate)

ここで試してください:https ://data.stackexchange.com/stackoverflow/q/107948/

于 2011-07-30T14:42:00.287 に答える