日期:2014-05-16  浏览次数:20349 次

求大侠帮写一个SQL。。。
ID      排放口编码      污染物编码        检测时间              折算浓度 
1 430100000002201   001     2014-01-21 16:15:32.000 1.000
2 430100000002201   002     2014-01-21 16:15:32.000 2.000
3 430100000002201   001     2014-01-21 16:13:32.000 3.000
4 430100000002201   002     2014-01-21 16:14:32.000 4.000
5 430100000002202   001     2014-01-21 16:15:32.000 5.000
6 430100000002202   002     2014-01-21 16:15:32.000 6.000
1 430100000002202   001     2014-01-21 16:13:32.000 7.000
2 430100000002202   002     2014-01-21 16:13:32.000 8.000
3 430100000002203   001     2014-01-21 16:15:32.000 9.000
4 430100000002203   002     2014-01-21 16:15:32.000 10.000
5 430100000002203   001     2014-01-21 16:14:32.000 11.000
6 430100000002203   002     2014-01-21 16:14:32.000 12.000

ID号请54....我想获得一大堆数据里...排放口编码..430100000002201   430100000002202 430100000002203  检测时间是最新的污染编码为01 02的折算浓度

也就是
430100000002201    001   2014-01-21 16:15:32.000  1
430100000002201    002   2014-01-21 16:15:32.000  2
430100000002202    001   2014-01-21 16:15:32.000  5
430100000002202    002   2014-01-21 16:15:32.000  6
430100000002203    001   2014-01-21 16:15:32.000  9
430100000002203    002   2014-01-21 16:15:32.000  10

我写的。。。
 SELECT  排放口编码, [污染物编码], max(折算浓度) AS 当前值, 
  MAX([监测时间])
  FROM [DHEPEMS].[dbo].[PollZs_430100000002]  
  GROUP BY  排放口编码, [污染物编码]
  order by 监测时间  desc

结果获得的这算值总是最大的(不知道为何。。另外一张表结构不同的就可以...逻辑上应该是不可以的)....求大神纠正




------解决方案--------------------
这个都求max,可能会有问题的,试试下面的代码,适合2005及以后的版本:


--drop table tb

create table tb(ID int, 排放口编码  varchar(20),污染物编码  varchar(10),检测时间 datetime,折算浓度 numeric(10,3))

insert into tb
select 1 ,'430100000002201',   001     ,'2014-01-21 16:15:32.000', 1.00 union all
select 2 ,'430100000002201',   002     ,'2014-01-21 16:15:32.000', 2.000  union all
select 3 ,'430100000002201',   001     ,'2014-01-21 16:13:32.000', 3.000 union all
select 4 ,'430100000002201',   002     ,'2014-01-21 16:14:32.000', 4.000 union all
select 5 ,'430100000002202',   001     ,'2014-01-21 16:15:32.000', 5.000 union all
select 6 ,'430100000002202',   002     ,'2014-01-21 16:15:32.000', 6.000 union all
select 1 ,'430100000002202',   001     ,'2014-01-21 16:13:32.000', 7.000 unio