需要根据日期订购输出 - 子查询

时间:2013-10-08 03:20:27

标签: sql sql-server-2012

我有一个简单的子查询,其中有两个表。第一个表包含客户ID,名字和姓氏。第二个表有客户ID和订单日期。我想生成一个显示名字,姓氏和订单日期的查询。

我已经尝试了以下代码,我不知道基于日期的输出顺序

Select 
    Customerid, 
    FirstName, 
    LastName 
From 
    Customer
Where 
   CustomerID IN (select 
                     CustomerID
                  from 
                     orders
                  where 
                     orderdate is not null);

我显示的输出只是客户ID,名字和姓氏。如何在输出中包含订单日期。

2 个答案:

答案 0 :(得分:1)

你选择了什么=为你显示什么,在你的选择陈述中包括日期

Select A.Customerid, A.firstname, A.lastname, B.orderdate
From tableA A
Inner join Tableb  B on A.customerid = B.customerid

对于您修改过的问题,请尝试以下查询

Select A.firstname, A.lastname, B.orderdate
From tableA A
Inner join Tableb  B on A.customerid = B.customerid
Order By B.orederdate

答案 1 :(得分:1)

;with CustomerProductOrderOrdinal( OrderId, Ordinal )
as
(
    select
        o.OrderId
        , row_number() over ( partition by o.CustomerId, o.ProductId order by o.OrderDate ) Ordinal
    from
        Orders o
    where
        o.OrderDate is not null
        -- filter for product here if so desired
        -- and o.ProductId = <whatever>
)
,FirstCustomerProductOrder( OrderId )
as
(
    select
        OrderId
    from
        CustomerProductOrderOrdinal
    where
        Ordinal = 1
)

select
    c.CustomerId
    , c.FirstName
    , c.LastName
    --, p.ProductId
    , o.OrderDate
From
    Customer c
    inner join Orders o
     on c.CustomerId = o.CustomerId
    inner join FirstCustomerProductOrder fcpo
     on o.OrderId = fcpo.OrderId
    -- join with product if you want product info
    --inner join Product p
    -- on o.ProductId = p.ProductId