从查询中选择不同的行

时间:2016-06-29 18:57:19

标签: sql-server distinct

我有以下SQL Server查询:

select flujo, FECHA from El_Bosque 
where fecha between CONVERT(DATETIME,'2016-06-22 10:00:00',102) 
and CONVERT(DATETIME,'2016-06-28 00:00:00',102) and ( flujo >=0 ) 
order by fecha asc

它返回:

0.84    2016-06-22 10:00:00.000
0.84    2016-06-22 10:00:00.000
0.83    2016-06-22 10:15:00.000
0.83    2016-06-22 10:15:00.000
0.81    2016-06-22 10:30:00.000
0.81    2016-06-22 10:30:00.000

我想过滤此查询,因此我只能获得不同的行:

0.84    2016-06-22 10:00:00.000
0.83    2016-06-22 10:15:00.000
0.81    2016-06-22 10:30:00.000

提前谢谢。

2 个答案:

答案 0 :(得分:0)

DISTINCT关键字可用于仅返回不同(不同)的值。

SELECT DISTINCT column_name,column_name
FROM table_name;

所以你的SQL查询看起来像

select DISTINCT  flujo, FECHA from El_Bosque 
where fecha between CONVERT(DATETIME,'2016-06-22 10:00:00',102) 
and CONVERT(DATETIME,'2016-06-28 00:00:00',102) and ( flujo >=0 ) 
order by fecha asc

答案 1 :(得分:-1)

尝试使用不同的关键字

select 
DISTINCT -- this keyword
flujo, FECHA from El_Bosque 
where fecha between CONVERT(DATETIME,'2016-06-22 10:00:00',102) 
and CONVERT(DATETIME,'2016-06-28 00:00:00',102) and ( flujo >=0 ) 
order by fecha asc

另请注意,您的查询使用CONVERT函数,您可以通过编写

来改善
DECLARE @t1 datetime
DECLARE @t2 datetime
SELECT @t1=CONVERT(DATETIME,'2016-06-22 10:00:00',102) , @t2=CONVERT(DATETIME,'2016-06-28 10:00:00',102) 
select 
DISTINCT -- this keyword
flujo, FECHA from El_Bosque 
where fecha between @t1 and @t2 and ( flujo >=0 ) 
order by fecha asc
相关问题