Essaie de faire une requête pour trouver les champs personnalisés remplis par l'utilisateur

J’ai une requête d’exploration de données où je tente de trouver tous les utilisateurs ayant rempli les champs personnalisés utilisateur 1 à 4, et j’aimerais que seuls ceux ayant les 4 champs soient affichés sous forme de colonnes pour chaque utilisateur, mais mes compétences en PostgreSQL sont limitées et je n’ai pas réussi à trouver la solution :

SELECT user_id, name, value
FROM user_custom_fields
WHERE name IN ('user_field_1','user_field_2','user_field_3','user_field_4')
    AND value IS NOT NULL
ORDER BY user_id ASC, name ASC
3 « J'aime »

I’m sure there are better ways of approaching this, but this should work to give you a single row containing all of the fields for each user who has filled out at least one of your user fields.

WITH user_field_1 AS (
SELECT ucf.value,
ucf.user_id
FROM user_custom_fields ucf
WHERE ucf.name = 'user_field_1'
AND ucf.value IS NOT NULL
AND ucf.value != ''
),
user_field_2 AS (
SELECT ucf.value,
ucf.user_id
FROM user_custom_fields ucf
WHERE ucf.name = 'user_field_2'
AND ucf.value IS NOT NULL
AND ucf.value != ''
),
user_field_3 AS (
SELECT ucf.value,
ucf.user_id
FROM user_custom_fields ucf
WHERE ucf.name = 'user_field_3'
AND ucf.value IS NOT NULL
AND ucf.value != ''
),
user_field_4 AS (
SELECT ucf.value,
ucf.user_id
FROM user_custom_fields ucf
WHERE ucf.name = 'user_field_4'
AND ucf.value IS NOT NULL
AND ucf.value != ''
),
target_fields AS (
SELECT
u.id AS user_id,
uf1.value AS user_field_1,
uf2.value AS user_field_2,
uf3.value AS user_field_3,
uf4.value AS user_field_4
FROM users u
LEFT JOIN user_field_1 uf1
ON uf1.user_id = u.id
LEFT JOIN user_field_2 uf2
ON uf2.user_id = u.id
LEFT JOIN user_field_3 uf3
ON uf3.user_id = u.id
LEFT JOIN user_field_4 uf4
ON uf4.user_id = u.id
)

SELECT
*
FROM target_fields tf
WHERE tf.user_field_1 IS NOT NULL
OR tf.user_field_2 IS NOT NULL
OR tf.user_field_3 IS NOT NULL
OR tf.user_field_4 IS NOT NULL
ORDER BY tf.user_id
4 « J'aime »

If there is a better way I am so ok with trying/doing it! I’ll give this a shot though.

1 « J'aime »

By ‘better’ I mean more elegant and more efficient. This should give you the results that you are looking for. I was stuck for a while on how to get the results in a single row for each user. If that isn’t a requirement, the query could be simplified a lot.

1 « J'aime »

Ce sujet a été automatiquement fermé après 2230 jours. De nouvelles réponses ne sont plus autorisées.