私はPostgresqlで2つのテーブルを持っており、ハッシュタグが場所によって繰り返される回数を取得しようとしています。SQLクエリで2つのフィールドをグループ分けするには?
私はこのクエリを作りました:場所、つぶやきのIDとハッシュタグを返し
SELECT tweets_with_location.user_location,
tweets_with_location.my_new_id,
all_hashtags_with_location.regexp_split_to_table
FROM tweets_with_location, all_hashtags_with_location
WHERE tweets_with_location.my_new_id = all_hashtags_with_location.my_new_id;
:
USER_LOCATIONを| MY_NEW_ID | HASHTAG
ニューヨーク、ニューヨーク州| 33 |ハッピー
ニューヨーク、ニューヨーク州| 40 | BigApple
Bronx、NY | 12 |ハッピー
ブロンクス、ニューヨーク州| 45 |ハッピー
クイーンズランド州| 23 |トランプ
クイーンズランド州| 20 |トランプ
その後
は、私は別のSQLクエリを作りましたが、それはハッシュタグが場所によって表示された回数を集計していない、カウント値が常に1であるようだ:
SELECT tweets_with_location.user_location,
all_hashtags_with_location.regexp_split_to_table,
COUNT(DISTINCT all_hashtags_with_location.regexp_split_to_table) AS CountOf
FROM tweets_with_location, all_hashtags_with_location
WHERE tweets_with_location.my_new_id = all_hashtags_with_location.my_new_id
GROUP BY tweets_with_location.user_location,
all_hashtags_with_location.regexp_split_to_table
ORDER BY CountOf DESC;
私はこの結果である必要があります: - HASHTAG -
USER_LOCATION COUNT
ニューヨーク、NY |ハッピー| 1
Bronx、NY |ハッピー| 2
Queens、NY |トランプ| 2
ニューヨーク、ニューヨーク州|ハッピー| 1
どうすればよいですか?私のSQLクエリで何が問題になっていますか?
SELECT tweets_with_location.user_location,
all_hashtags_with_location.regexp_split_to_table,
COUNT(DISTINCT tweets_with_location.my_new_id) AS CountOf
FROM tweets_with_location, all_hashtags_with_location
WHERE tweets_with_location.my_new_id = all_hashtags_with_location.my_new_id
GROUP BY tweets_with_location.user_location,
all_hashtags_with_location.regexp_split_to_table
ORDER BY CountOf DESC;
これは、ハットタグIDではなく、ツイートIDです。 1つのつぶやきは3つ以上のハッシュタグを持つことができるので...とにかく試してみます。 –
それはうまくいったようですが、私はなぜ理解できませんでしたか...それを私に説明してもらえますか?私はそれを学びたいと思っています... –
@JaquelinePassos - それはあなたのデータに大きく依存します。あなたの最初の投稿から 'my_new_id'はあなたが' count'しようとしているフィールドです。しかし、あなたの試みでは、別々の 'hashtag'フィールドを数え、それらを使ってグループ化しました。常に1を返します。別のカウントが必要ない場合は、distinctを削除するだけで、クエリもうまくいきます。重複があり、それらを何回も数えたくない場合は、この方法を使用してください。 – sgeddes