0

我根据特定的 id 从数据库中得到两行

ID         Address    Res_Address     Office_Address
-------------------------------------------------
4          C 60            0               1
4          D 90            1               0

我只想在 ResAddress 中选择具有标志 res_address 1 的地址,并通过 select 语句选择具有 Office_address 1 作为 OfficeAddress 的标志。我不想使用存储过程。

4

1 回答 1

2

尝试

SELECT ID,
       MIN(CASE WHEN Res_Address    = 1 THEN Address END) ResidentAddress,
       MIN(CASE WHEN Office_Address = 1 THEN Address END) OfficeAddress
FROM 
(
  SELECT -- your subquery that returns two rows goes here
) q
 GROUP BY ID

样本输出:

| 身份证 | 居民地址 | 办公地址 |
--------------------------------------
| 4 | D 90 | C 60 |

这是SQLFiddle演示

更新如果我正确理解您的评论,您可以使用COALESCE()

SELECT ID,
       COALESCE(MIN(CASE WHEN Res_Address = 1    THEN Address END), '0') ResidentAddress,
       COALESCE(MIN(CASE WHEN Office_Address = 1 THEN Address END), '0') OfficeAddress
FROM 
(
  SELECT * FROM Table1
) q
 GROUP BY ID

这是SQLFiddle演示

于 2013-07-26T06:00:51.373 回答