我有一个要求,我需要根据电子邮件(帐单邮寄地址电子邮件地址)选择最近一年的订单。我需要显示订单号,发货名,运送姓氏,账单地址电子邮件ID和项目描述以及提交日期。相同的地址表用于存储货运(ship_to 1)和帐单地址(ship_to始终为0)。送货地址中的电子邮件字段是可选的,如果两个地址仅匹配,则会将帐单地址写入DB。
地址:
Order_num first_name last_name email ship_to_num
-----------------------------------------------------------
ord1 abc abc abc@c.com 0
ord1 cdf ccc XXc@m.com 1
我写了一个如下的初始查询:
select
addr.first_name, addr.last_name, addr.order_num, addr.Update_Date_Time,
ord.Order_Amt, item.Item_Desc
from
ADDR addr
inner join
ORDER ord on ord.Order_num = addr.Order_Num
inner join
ITEM item on ord.Order_num = item.Order_Num
where
addr.Order_Num in (select Order_num
from TOEADDR addr
where addr.ShipTo_Num = 0
and addr.EM_EMAIL_ADDR = 'avc@abc.com'
and addr.Update_Date_Time > DATEADD(year,-1, GETDATE()))
order by
addr.Update_Date_Time desc
有什么办法可以将这个逻辑添加到上面的查询中:
(SELECT TOP 1 First_Name, LAST_NAME FROM ADDR ORDER BY ShipTo_Num ASC)
谢谢,CTE就像魅力一样。以下是最终查询:
;with cte_addr
AS
(SELECT First_Name,LAST_NAME, EM_EMAIL_ADDR, order_num,Update_Date_Time,ShipTo_Num
, ROW_NUMBER() OVER (PARTITION BY order_num ORDER BY ShipTo_Num desc) as ROWID
FROM ADDR
)
SELECT addr.first_name , addr.last_name, addr.order_num, addr.Update_Date_Time,
ord.Order_Amt, item.Item_Desc
FROM cte_addr addr
inner join ORDER ord on ord.Order_num = addr.Order_Num
inner join ITEM item on ord.Order_num = item.Order_Num
WHERE addr.ROWID =1 and
addr.Order_Num in(
select Order_num from ADDR billAddress where
billAddress.ShipTo_Num = 0 and billAddress.EM_EMAIL_ADDR = 'afv@abv.com'
and billAddress.Update_Date_Time > DATEADD(year,-1,GETDATE())
)
order by addr.Update_Date_Time desc
答案 0 :(得分:1)
您可以使用CTE来实现它。你可以写下面的查询。这可以是您正在寻找的逻辑的示例查询
;with cte_addr
AS
(SELECT First_Name,LAST_NAME, email EM_EMAIL_ADDR, order_num,Update_Date_Time,ShipTo_Num
, ROW_NUMBER() OVER (PARTITION BY First_Name,LAST_NAME ORDER BY ShipTo_Num) ROWID
FROM ADDR
)
SELECT addr.first_name , addr.last_name, addr.order_num, addr.Update_Date_Time,
ord.Order_Amt, item.Item_Desc
FROM cte_addr addr
inner join ORDER ord on ord.Order_num = addr.Order_Num
inner join ITEM item on ord.Order_num = item.Order_Num
WHERE t.ROWID =1
and addr.Order_Num in(
select Order_num from TOEADDR addr where
addr.ShipTo_Num = 0 and addr.EM_EMAIL_ADDR = 'avc@avc.com'
and addr.Update_Date_Time > DATEADD(year,-1,GETDATE())
)
order by addr.Update_Date_Time desc