2012-03-11 39 views
2

我有表作为与respectives选择不同的列名值

P_Id | userid | year | month | day 
-----+--------+------+-------+------ 
3 |  3 | 2011 |  2 | 2 
5 |  1 | 2011 |  2 | 3 
16 |  8 | 2011 |  3 | 4 
5 |  3 | 2011 |  4 | 4 
17 |  1 | 2011 |  4 | 6 
8 |  4 | 2011 |  7 | 7 
9 |  3 | 2011 |  8 | 8 
10 |  8 | 2011 |  9 | 9 

我要选择不同的列即用户ID,而且这是首次遇到年年份和月份的相应值。

对于上表中给出以下应该是输出

P_Id | userid | year | month | day 
-----+--------+------+-------+------ 
    3 |  3 | 2011 |  2 | 2 
    5 |  1 | 2011 |  2 | 3 
    16 |  8 | 2011 |  3 | 4 
    8 |  4 | 2011 |  7 | 7 

或 如果我按年,月,日 用户ID这是首先遇到只能选择和其他必须不能选择排序表

+0

您到目前为止尝试过哪些查询? – 2012-03-11 10:48:20

+0

我在尝试但无法获得userid的各自的值 – 2012-03-11 10:54:48

+1

@Sunny:如果您认为以下答案之一是正确的,那么请接受它...这是如何工作... – 2012-03-11 13:25:49

回答

1

把年,月,日,以原生日期列,这样做:

select p_id, userid, min(the_date) from table group by p_id, userid 

它会提供最快的结果。

如果您不能修改您的表格,并且应该使用年份+月份+日期,那么您可以将此值转换为日期并仍然使用分钟函数。

+0

谢谢asktomsk – 2012-03-11 11:26:33

+1

我不清楚,这不会给他一行像'17 | 1 | 2011 | 2 | 3'。 – 2012-03-11 13:48:05

+0

感谢它的工作 – 2012-03-11 14:21:39

1
SELECT ta.* 
FROM 
    (SELECT DISTINCT userid 
     FROM tableX 
    ) AS di 
    JOIN 
    tableX AS ta 
     ON ta.P_id = 
     (SELECT ti.P_id 
      FROM tableX AS ti 
      WHERE ti.userid = di.userid 
      ORDER BY ti.year, ti.month, ti.day 
      LIMIT 1 
     ) 
1

您的查询如下;

select * from (select min(p_id)p_id,userid, min(year)year,min(month)month,min(day)day from tsil group by userid) t order by p_id; 

这里是测试;

create table tsil(p_id int, userid int, year int, month int, day int); 
insert into tsil values (3,3,2011,2,2) 
           ,(5,1,2011,2,3) 
           ,(16,8,2011,3,4) 
           ,(5,3,2011,4,4) 
           ,(17,1,2011,4,6) 
           ,(8,4,2011,7,7) 
           ,(9,3,2011,8,8) 
           ,(10,8,2011,9,9); 
commit; 
select * from (select max(p_id)p_id,userid, min(year)year,min(month)month,min(day)day from tsil group by userid) t order by p_id; 
drop table tsil; 

这里是结果;你的预期。

+------+--------+------+-------+------+ 
| p_id | userid | year | month | day | 
+------+--------+------+-------+------+ 
| 3 |  3 | 2011 |  2 | 2 | 
| 5 |  1 | 2011 |  2 | 3 | 
| 8 |  4 | 2011 |  7 | 7 | 
| 16 |  8 | 2011 |  3 | 4 | 
+------+--------+------+-------+------+ 
+0

通过使用min函数我得到错误的列,我想 – 2012-03-11 11:43:30

+0

我已经提高了我的回应。 – dursun 2012-03-11 12:20:31

+0

此查询不起作用。对于相同用户标识的日期(2011,2,10)和(2010,4,10),主要的问题是。您的查询将返回不存在的日期(2010,2,10) – asktomsk 2012-03-11 14:34:58