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

下面的表中,怎么能让MIN返回NULL值?
CREATE TABLE tbl (ID int,Date DATETIME)

insert into tbl select 1 , '2011-09-05 17:41:07.820'
insert into tbl select 2 , '2011-09-08 18:12:23.013'
insert into tbl select 1 , '2011-09-08 18:12:48.943'
insert into tbl select 2 , NULL

SELECT ID,MIN(Date) FROM tbl GROUP BY ID

想得到如下的结果:
1 2011-09-05 17:41:07.820
2 NULL

------解决方案--------------------
SQL code
SELECT * FROM tbl AS a WHERE NOT EXISTS(SELECT 1 FROM tbl WHERE ID=a.ID AND ISNULL(Date,'')<ISNULL(a.Date,''))

------解决方案--------------------
SQL code
CREATE TABLE tbl (ID int,Date DATETIME)

insert into tbl select 1 , '2011-09-05 17:41:07.820'
insert into tbl select 2 , '2011-09-08 18:12:23.013'
insert into tbl select 1 , '2011-09-08 18:12:48.943'
insert into tbl select 2 , NULL
--DROP TABLE tbl
SELECT ID,MIN(Date) AS Date FROM tbl AS a WHERE NOT EXISTS(SELECT 1 FROM tbl WHERE ID=a.ID AND ISNULL(Date,'')<ISNULL(a.Date,'')) GROUP BY ID

------解决方案--------------------
SQL code
SELECT ID,isnull (MIN(Date),0)date FROM tbl GROUP BY ID

------解决方案--------------------
SQL code
CREATE TABLE tbl (ID int,Date DATETIME)

insert into tbl select 1 , '2011-09-05 17:41:07.820'
insert into tbl select 2 , '2011-09-08 18:12:23.013'
insert into tbl select 1 , '2011-09-08 18:12:48.943'
insert into tbl select 2 , NULL

SELECT ID,MIN(Date) FROM tbl GROUP BY ID

WITH TT
AS(
SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY [date]) AS num ,* FROM tbl)

SELECT id,date FROM TT WHERE num = 1

/*
id    date
1    2011-09-05 17:41:07.820
2    NULL*/

------解决方案--------------------
SQL code
CREATE TABLE tbl (ID int,Date DATETIME)

insert into tbl select 1 , '2011-09-05 17:41:07.820'
insert into tbl select 2 , '2011-09-08 18:12:23.013'
insert into tbl select 1 , '2011-09-08 18:12:48.943'
insert into tbl select 2 , NULL

SELECT distinct id ,Date = (case when date is null then null else (select top 1 date from tbl where id = t.id order by date) end) from tbl t


drop table tbl 

/*
id          Date                                                   
----------- ------------------------------------------------------ 
1           2011-09-05 17:41:07.820
2           NULL

(所影响的行数为 2 行)
*/

------解决方案--------------------
SQL code
CREATE TABLE tbl (ID int,Date DATETIME)

insert into tbl select 1 , '2011-09-05 17:41:07.820'
insert into tbl select 2 , '2011-09-08 18:12:23.013'
insert into tbl select 1 , '2011-09-08 18:12:48.943'
insert into tbl select 2 , NULL

select * from tbl t where not exists(select 1 from tbl where ID=t.ID and isnull(DATE,'')<isnull(t.Date,''))


drop table tbl

/*ID          Date
----------- -----------------------
1           2011-09-05 17:41:07.820
2           NULL

(2 行受影响)
*/

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

select * from tbl t where isnull(date,'')=(select MIN(isnull(date,'')) from tbl where ID=t.ID)

------解决方案--------------------
SQL code
--你是要null算最小么?
order by case when col is null then 1 else 0 end
--其他的自己润色吧