-1

当从下面的查询返回多个值时,我需要将地址类型值添加到列中。例如,如果返回单个结果,那么我希望地址类型列中的值为 Business。但是,如果返回的值超过一个,我希望它在第一个结果为备用​​业务 1、备用业务 2、备用业务 3 等之后增加一个值。

谁能帮我吗?

SELECT al.ADDRESS_ID,
       addr.LINE1 + ' (' + addr.LABEL + ')' AS ModifiedLine1,
       addr2.ADDR_TYP_ID,
       addr2.LABEL,
       addr2.LINE2,
       addr2.LINE3,
       addr2.CITY,
       addr2.STATE,
       addr2.COUNTRY,
       addr2.POSTAL_CD
FROM   INT_AUX_LST_ADDR al
       LEFT JOIN INT_AUX_ADDRESS addr
              ON addr.ADDRESS_ID = al.ADDRESS_ID
       LEFT JOIN INT_AUX_ADDRESS addr2
              ON addr2.ADDRESS_ID = al.ADDRESS_ID
       LEFT JOIN INT_RELATION_TYP rt
              ON rt.RLTN_TYP_ID = al.RLTN_TYP_ID
WHERE  al.LISTING_ID = 1 
4

1 回答 1

1

这是一份工作row_number()。. . 唯一需要注意的是,您需要一些订购。但它是这样的:

SELECT al.ADDRESS_ID,
       addr.LINE1 + ' (' + addr.LABEL + ')' AS ModifiedLine1,
       addr2.ADDR_TYP_ID,
       addr2.LABEL,
       addr2.LINE2,
       addr2.LINE3,
       addr2.CITY,
       addr2.STATE,
       addr2.COUNTRY,
       addr2.POSTAL_CD,
       (case row_number() over (order by (select NULL))
             when 1 then 'Business'
             else 'Alternate Business '+cast(-1 + row_number() over (order by (select NULL)) as varchar(255))
        end) as WhatYouWant
FROM   INT_AUX_LST_ADDR al
       LEFT JOIN INT_AUX_ADDRESS addr
              ON addr.ADDRESS_ID = al.ADDRESS_ID
       LEFT JOIN INT_AUX_ADDRESS addr2
              ON addr2.ADDRESS_ID = al.ADDRESS_ID
       LEFT JOIN INT_RELATION_TYP rt
              ON rt.RLTN_TYP_ID = al.RLTN_TYP_ID
WHERE  al.LISTING_ID = 1 ;

顺便说一句,对于order by上面示例中的不确定,不能保证两个row_number()调用返回相同的值——但实际上它们会返回。如果您将其替换为正确的订购字段,那么这不是问题。

于 2013-08-22T01:30:32.683 回答