0

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

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

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

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

4

2 回答 2

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
于 2013-10-08T03:59:40.140 回答
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
于 2013-10-08T03:25:04.693 回答