日期:2014-05-18  浏览次数:20510 次

求助一个简单的sql 语句
SELECT ZYH, HCRQ, ZZRQ
FROM ZY_HCMX
WHERE (HCLX = 0) AND (HQCH IS NULL) AND (HCRQ >= '2012-1-1') AND (HCRQ < '2012-2-1')
ORDER BY ZYH


结果:
21816 2012-01-01 8:01:38 NULL
21818 2012-01-01 10:25:37 NULL
21819 2012-01-01 9:11:52 NULL
21820 2012-01-01 10:07:57 NULL
21821 2012-01-01 10:15:24 NULL
21821 2012-01-20 15:57:53 NULL


我想要的结果是(每一个 住院号,只取日期小的一个数据)
21816 2012-01-01 8:01:38 NULL
21818 2012-01-01 10:25:37 NULL
21819 2012-01-01 9:11:52 NULL
21820 2012-01-01 10:07:57 NULL
21821 2012-01-01 10:15:24 NULL

如何处理?

------解决方案--------------------
SQL code

SELECT ZYH, HCRQ, ZZRQ
FROM ZY_HCMX t
WHERE (HCLX = 0) AND (HQCH IS NULL) AND (HCRQ >= '2012-1-1') AND (HCRQ < '2012-2-1')
    and not exists (select 1 from ZY_HCMX WHERE (HCLX = 0) AND (HQCH IS NULL) AND (HCRQ >= '2012-1-1') AND (HCRQ < '2012-2-1')
                    and ZYH=t.ZYH and HCRQ<t.HCRQ)
ORDER BY ZYH

------解决方案--------------------
SQL code
SELECT ZYH, (select min(HCRQ)from ZY_HCMX WHERE ZYH=z.ZYH  )HCRQ, ZZRQ
FROM ZY_HCMX z
WHERE (HCLX = 0) AND (HQCH IS NULL) AND (HCRQ >= '2012-1-1') AND (HCRQ < '2012-2-1')
ORDER BY ZYH

------解决方案--------------------
顶一下吧,坐等楼下解释