2

I have two tables, Table1 and Table 2. Some columns are the same in both. I would like to pull the data depending on whether the column in table2 has an entry or not. I mean, if a data has an entry one of the column in both tables, then I would like to pull data from table2 if not table 1.

Following is the example of the table structure.

TABLE 1 : Ticket_details

   TIcketID| SubmittedBy|Priority| Ticket_description|current_status
    2010       1000       High      blah...blah        current_assigned
    2020       1000       Normal    gggggggggg         current_assigned
    2030       1100        Low      hhhhhhhhhhhh       current_description

TABLE 2: TICKET_EDIT_DETAILS

    TIcketID| Priority| Ticket_description|
      2020       Low    gggggggggghhhh        

In this example, the ticketId 2020 has an entry in Table2. So I would like to pull Priority and ticket_description from Table 2. But TicketIds 2010 and 2030 have no entry in Table 2, so I would like to pull the columns Priority and ticket_description from Table 1.

How can I do this?

4

2 回答 2

3

我想这就是你要找的东西:

SELECT t1.ticketId, t1.submittedBy,
  COALESCE(t2.priority, t1.priority),
  COALESCE(t2.ticket_description, t1.ticket_description),
  t1.current_status
FROM table1 t1
LEFT JOIN table2 t2 ON t1.ticketId = t2.ticketId

在这里拉小提琴。

请记住,此解决方案实际上是假设优先级和 TIcket_description 在 table2 上不为空。如果它们为空,则将使用 table1 中的那些字段。

于 2013-09-05T05:23:09.530 回答
3

试试这个。我想,它给了你想要的。

SELECT
    td.[TIcketID],
    td.[SubmittedBy],
    (CASE WHEN ted.[Priority] IS NOT NULL THEN ted.[Priority] ELSE td.[Priority] END)AS [priority],
    (CASE WHEN ted.[Ticket_description] IS NOT NULL THEN ted.[Ticket_description] ELSE td.[Ticket_description] END)AS [Ticket_description],
    td.[current_status]
FROM Ticket_details td
LEFT OUTER JOIN TICKET_EDIT_DETAILS ted ON td.[TIcketID]=ted.[TIcketID]

这是SQLFiddle

于 2013-09-05T05:25:30.997 回答