【问题标题】:Using If Statement within SQL query在 SQL 查询中使用 If 语句
【发布时间】:2013-09-05 05:15:36
【问题描述】:

我有两个表,表 1 和表 2。两者中的某些列是相同的。我想根据 table2 中的列是否有条目来提取数据。我的意思是,如果一个数据在两个表中都有一个列的条目,那么如果不是表 1,我想从表 2 中提取数据。

以下是表结构的示例。

表 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

表 2:TICKET_EDIT_DETAILS

    TIcketID| Priority| Ticket_description|
      2020       Low    gggggggggghhhh        

在此示例中,ticketId 2020 在表 2 中有一个条目。所以我想从表2中拉出Priorityticket_description。但是TicketIds 2010和2030在表2中没有条目,所以我想从表1中拉出Priorityticket_description列。

我该怎么做?

【问题讨论】:

  • 你可以使用'case when'

标签: sql sql-server if-statement case


【解决方案1】:

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

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

小提琴here.

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • @Raghu,现在添加了 SQL Fiddle 链接。
    猜你喜欢
    • 2013-01-08
    • 2016-12-23
    • 2014-02-11
    • 1970-01-01
    • 2015-05-04
    • 2014-10-18
    • 2011-12-09
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多