在sql

时间:2017-09-07 02:42:50

标签: sql postgresql pivot crosstab

我正在使用Psql,需要通过创建一个数据透视表从名为activities的表中获取值。

目前我有这样的查询,它会生成一个包含first_name|email|signup_hash列的表:

SELECT COALESCE(profile.first_name, signup_hash.first_name) AS first_name,
       users.email,
       signup_hash.hash_id,

FROM signup_hash
LEFT OUTER JOIN users ON users.id = signup_hash.user_id
LEFT OUTER JOIN profiles ON profiles.user_id = users.id
INNER JOIN memberships ON memberships.hash_id = signup_hash.hash_id
WHERE memberships.member_id =?

activities表包含以下字段:user_id|activity_name|date_completed|date_created

每个用户的活动都包含activity_name“first_login”和“profile_complete”(例如,activity.name =“first_login”和activity.name =“profile_complete”)。

我如何加入活动表,以便最终查询生成一个包含列的表:first_name|email|first_login|profile_complete|signup_hash

修改 1)对于特定用户,没有多行activity_name为“first_login”和“profile_complete” 2)列first_login&列应该是什么值? profile_complete包含在最终结果中?如果值存在则应显示date_completed,否则显示“N / A”

1 个答案:

答案 0 :(得分:0)

您可以按如下方式再使用2个LEFT OUTER JOIN,并使用CASE在结果中选择所需的表达式。请注意,我在此处将date_completed视为date列。如果是字符列,则不需要TO_CHAR

    SELECT COALESCE(profile.first_name, signup_hash.first_name) AS first_name,
       users.email,
       CASE
           WHEN f_login.user_id IS NULL THEN 'N/A'
           ELSE TO_CHAR(date_completed)
       END first_login,
       CASE
           WHEN p_complete.user_id IS NULL THEN 'N/A'
           ELSE TO_CHAR(date_completed)
       END profile_complete,
       signup_hash.hash_id
FROM signup_hash
LEFT OUTER JOIN users ON users.id = signup_hash.user_id
LEFT OUTER JOIN profiles ON profiles.user_id = users.id
INNER JOIN memberships ON memberships.hash_id = signup_hash.hash_id
LEFT OUTER JOIN
  (SELECT user_id,
          date_completed
   FROM activities
   WHERE activity_name = 'first_login') f_login ON f_login.user_id = signup_hash.user_id
LEFT OUTER JOIN
  (SELECT user_id,
          date_completed
   FROM activities
   WHERE activity_name = 'profile_complete') p_complete ON p_complete.user_id = signup_hash.user_id
WHERE memberships.member_id = ?