选择某个键SQL

时间:2015-12-19 11:23:27

标签: mysql sql database

如何为连续的所有CustomerID选择特定的日期数(让它为第三个) 例如我有DB看起来像

+---------+------------+------------+------------+-----------+
| OrderID | CustomerID | EmployeeID | OrderDate  | ShipperID |
+---------+------------+------------+------------+-----------+
|   10308 |          2 |          7 | 1996-09-18 |         3 |
|   10365 |          3 |          3 | 1996-11-27 |         2 |
|   10355 |          4 |          6 | 1996-11-15 |         1 |
|   10383 |          4 |          8 | 1996-12-16 |         3 |
|   10278 |          5 |          8 | 1996-08-12 |         2 |
|   10280 |          5 |          2 | 1996-08-14 |         1 |
|   10384 |          5 |          3 | 1996-12-16 |         3 |
|   10265 |          7 |          2 | 1996-07-25 |         1 |
|   10297 |          7 |          5 | 1996-09-04 |         2 |
|   10360 |          7 |          4 | 1996-11-22 |         3 |
|   10436 |          7 |          3 | 1997-02-05 |         2 |
+---------+------------+------------+------------+-----------+

并且作为输出我们必须得到

╔══╦════════════╦══╦════════════╦══╗
║  ║ CustomerID ║  ║ OrderDate  ║  ║
╠══╬════════════╬══╬════════════╬══╣
║  ║          5 ║  ║ 1996-12-16 ║  ║
║  ║          7 ║  ║ 1996-11-22 ║  ║
╚══╩════════════╩══╩════════════╩══╝

类似这样的事情

我使用MySQL

4 个答案:

答案 0 :(得分:3)

select customerid , orderdate from table where GROUP BY customerid

SQLFiddle

答案 1 :(得分:-1)

试试这个,

CRefBase **refs = new CRefBase*[200];

for(size_t i = 0; i < 200; ++i)
    refs[i] = new CRef<whatever>(pointer_to_whatever_instance);

答案 2 :(得分:-1)

如果你想要所有列,那么最快的方法可能是使用变量:

select t.*
from (select t.*,
             (@rn := if(@c = CustomerId, @rn + 1,
                        if(@c := CustomerId, 1, 1)
                       )
             ) as rn
      from table1 t cross join
           (select @c := 0, @rn := 0) params
      order by customerId, OrderDate
     ) t
where rn = 3;

答案 3 :(得分:-1)

您可以使用变量在MySQL中模拟row_number()。下面的子查询计算row_number() over (partition by CustomerID order by OrderDate)。获得行号后,可以轻松选择第3行:

SELECT  *
FROM    (
        SELECT  @rn := if(@prev_cust = CustomerID, @rn + 1, 1) as rn
        ,       @prev_cust := CustomerID
        ,       Table1.*
        FROM    Table1
        CROSS JOIN
                (
                SELECT  @prev_cust :=0
                ,       @rn := 0
                ) AS InitAlias
        ORDER BY
                CustomerID
        ,       OrderDate
        ) as SubQueryAlias
WHERE   rn = 3

Example at SQL Fiddle.