4

我正在尝试获取最新记录并找到不NULL匹配的记录。问题是我的子查询返回多个结果。

数据集

| 身份证 | DD | SIG_ID | DCRP |
--------------------------------------
| 1 | 2010-06-01 | 1 | 专家 |
| 2 | 2010-09-01 | 1 | 专家 |
| 3 | 2010-12-01 | 1 | 专家 |
| 4 | 2010-12-01 | 1 | 专家二 |
| 5 | 2011-03-01 | 1 | 专家二 |
| 6 | 2011-06-01 | 1 | (空) |
| 7 | 2010-06-01 | 2 | 高级 |
| 8 | 2010-09-01 | 2 | 高级 |
| 9 | 2010-09-01 | 2 | 高级 |
| 10 | 2010-12-01 | 2 | 高级二 |
| 11 | 2011-03-01 | 2 | (空) |
| 12 | 2011-03-01 | 2 | 高级 |
| 13 | 2010-06-01 | 3 | (空) |
| 14 | 2010-09-01 | 3 | (空) |
| 15 | 2010-12-01 | 3 | (空) |

询问

SELECT a.sig_id, a.id, 
  CASE
    WHEN b.dcrp IS NULL
      THEN
        (SELECT dcrp
         FROM tbl
         WHERE sig_id = a.sig_id
           AND id < a.id
           AND dcrp IS NOT NULL)
      ELSE b.dcrp
  END AS dcrp
FROM
  (SELECT sig_id, MAX(id) id
  FROM tbl
  GROUP BY sig_id) a
LEFT JOIN
  (SELECT id, dcrp
   FROM tbl
   WHERE dcrp IS NOT NULL) b ON b.id = a.id

期望的结果

dcrp获取每个最新的sig_id

| 身份证 | DD | SIG_ID | DCRP |
--------------------------------------
| 5 | 2011-03-01 | 1 | 专家二 |
| 12 | 2011-03-01 | 2 | 高级 |
| 15 | 2010-12-01 | 3 | (空) |

SQL小提琴

4

3 回答 3

10

您可以使用以下内容:

;WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY SIG_ID 
                                ORDER BY CASE WHEN DCRP IS NOT NULL THEN 0 ELSE 1 END,
                                DD DESC) RN
    FROM tbl
)
SELECT *
FROM CTE 
WHERE RN = 1

还有小提琴

于 2013-03-05T16:32:03.317 回答
2
;with si as (
  select distinct sig_id from tbl
)

select * 
from si
cross apply (select top 1 * from tbl where si.sig_id=tbl.sig_id order by case when dcrp is null then 1 else 0 end asc,dd desc) sii

和提琴手: http ://sqlfiddle.com/#!3/8e267/2/0

于 2013-03-05T16:37:14.460 回答
-2

由于子查询返回超过 1 行,SQLFiddle 中的查询失败。
添加TOP 1修复。请检查是否正常。

THEN
        (SELECT TOP 1 dcrp
         FROM tbl
         WHERE sig_id = a.sig_id
           AND id < a.id
           AND dcrp IS NOT NULL)
于 2013-03-05T16:31:00.400 回答