1

I've searched for this answer, there are a lot of "similar" issues but not exactly the same thing. I want to pull the value from a column, but it matches different ids.

I want both values in the same row after the query runs.

Example table:

+--field_id--+--ticket_id--+--value--+
+     16     +    423      +   PO123 +
+     16     +    344      +   PO101 +
+     7      +    423      +   17    +
+     7      +    344      +   24    +
+------------------------------------+

The main variable here is the ticket_id, however I want the value of field_id = 16 and field_id = 7 to show up on my query on the same row, so as a result I want:

+--ticket--+--PO#--+--Est Hours--+
+   423    + PO123 +    17       +
+   344    + PO101 +    24       +
+--------------------------------+

Currently I have a select statement that includes "value", but it only pulls the information from field_id = 16, I can't get the value from field_id = 7 into the same row.

Please assist. I apologize if this is a duplicate and I just didn't spot it or understand the other answers I've seen where people had problems "similar" but they didn't seem exactly the same. *Note: I cannot change the table layout I'm retrieving data from in any way to make this work better.

2 Answers 2

1

You simply need to join the table to itself by ticket_id AND field_id conditions at the same time

SELECT
    P.ticket_id AS ticket, P.value AS PONum, H.value AS EstHours
FROM
              Table P
    LEFT JOIN Table H ON P.ticket_id = H.ticket_id AND H.field_id = 7
WHERE
    P.field_id = 16
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this worked. I guess I forgot to mention, I have 3 other joins so I just added this in and it worked. I just needed this small piece really.
0

Use conditional aggregation:

select ticket_id,
       max(case when field_id = 16 then value end) as po,
       max(case when field_id = 7 then value end) as est_hours
from t
group by ticket_id;

2 Comments

Thank you for your response. I tried this however it didn't work, though that might have been because I didn't disclose the WHOLE project. I have multiple other joins and another join worked just fine. When I tried this one, I only retrieved one row and it didn't have the correct est_hours.
@dcary . . . This answers the question that you asked. It really isn't possible to read your mind to answer a different question. You are doing something wrong if this returns only one row when you have multiple ticket_ids.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.