Oracle SQL - 仅当列X等于Y时才选择第一个结果

时间:2013-07-09 11:47:20

标签: sql oracle oracle-sqldeveloper

SELECT location, property_id, MIN(year_week) 
FROM mytable 
WHERE first_day='Mon' AND part_full_flag='F' 
GROUP BY location, property_id, full_week_start

这为我提供了第一个可用日期的列表,其中包含星期一的开始日期。

该表有另一列 - “full_week_start” - 它给出了格式为'DD-MM-YYYY'的确切开始日期

我现在要做的只是显示开始日期是月初的结果。

如果我在查询中添加full_week_start,它会显示从该月的第一行开始的第一行,而不是第一行,只是从该月的第一行开始。

有什么想法吗?

编辑:示例数据

location | property_id | year_week | first_day | part_full_flag | full_week_start
---------------------------------------------------------------------------------
A        | 1           | 201434    | Mon       | F              | 18-08-2014
A        | 1           | 201435    | Mon       | F              | 25-08-2014
A        | 1           | 201436    | Mon       | F              | 01-09-2014
A        | 2           | 201434    | Mon       | F              | 18-08-2014
A        | 2           | 201435    | Mon       | F              | 25-08-2014
A        | 2           | 201449    | Mon       | F              | 01-12-2014

我只想从这些行返回2行 - 看起来像这样......

location | property_id | MIN(year_week)
---------------------------------------
A        | 1           | 201436
A        | 2           | 201449

这是一个SQL小提琴...... http://sqlfiddle.com/#!4/e9d64/3

3 个答案:

答案 0 :(得分:0)

如果你这样做会发生什么:

SELECT location, property_id, MIN(year_week) 
FROM mytable 
WHERE first_day='Mon' 
AND part_full_flag='F' 
AND full_week_start like '01%'
GROUP BY location, property_id, full_week_start

更新

SELECT location, property_id, MIN(year_week) 
FROM mytable
WHERE first_day='Mon' 
AND part_full_flag='F' 
AND property_id IN (SELECT distinct property_id FROM mytable where full_week_start like '01%')
GROUP BY location, property_id

答案 1 :(得分:0)

SELECT location, property_id, MIN(year_week) 
FROM mytable 
WHERE first_day='Mon' AND part_full_flag='F'
AND TO_CHAR(full_week_start,'MM/DD/YY') LIKE '01%'
GROUP BY location, property_id

答案 2 :(得分:0)

这可以满足您的需求吗?

SELECT location, property_id, MIN(year_week) 
FROM mytable 
WHERE first_day='Mon' AND part_full_flag='F' 
GROUP BY location, property_id, full_week_start
HAVING full_week_start LIKE '01%'