下面的表中,怎么能让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
[解决办法]
SELECT * FROM tbl AS a WHERE NOT EXISTS(SELECT 1 FROM tbl WHERE ID=a.ID AND ISNULL(Date,'')<ISNULL(a.Date,''))
[解决办法]
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 tblSELECT 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
[解决办法]
SELECT ID,isnull (MIN(Date),0)date FROM tbl GROUP BY ID
[解决办法]
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 , NULLSELECT ID,MIN(Date) FROM tbl GROUP BY IDWITH TTAS(SELECT ROW_NUMBER() OVER(PARTITION BY id ORDER BY [date]) AS num ,* FROM tbl)SELECT id,date FROM TT WHERE num = 1/*id date1 2011-09-05 17:41:07.8202 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 , NULLSELECT 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 tdrop table tbl /*id Date ----------- ------------------------------------------------------ 1 2011-09-05 17:41:07.8202 NULL(所影响的行数为 2 行)*/
[解决办法]
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 , NULLselect * 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.8202 NULL(2 行受影响)*/
[解决办法]
select * from tbl t where isnull(date,'')=(select MIN(isnull(date,'')) from tbl where ID=t.ID)
[解决办法]
--你是要null算最小么?order by case when col is null then 1 else 0 end--其他的自己润色吧