我有一个表,它是3个表的连接,显示以下信息。
|| OrderID || Order Date || Customer || Customer City || Product || Amount ||
如果客户在同一天订购的产品超过一次,我希望另一列为|| Dual Purchase ||
?
值应为YES
或NO
因此,如果John于6月16日以2个单独的顺序购买可口可乐,那么对两个订单ID都应该YES
答案 0 :(得分:2)
你可以这样做:
SELECT OrderID
, OrderDate
, Customer
, CustomerCity
, Product
, Amount
, Case when Count(Product) Over(Partition by OrderDate, Customer, Product) > 1
then 'Yes' else 'No' end as DualPurchase
FROM TableName
答案 1 :(得分:0)
使用窗口功能ROW_NUMBER()
按OrderID
和Customer
定义双重记录。检查,如果行大于1:
DECLARE @Table TABLE (OrderID int, Customer int, OrderDate date)
INSERT INTO @Table
VALUES
(1,2, Getdate()),
(1,2, DATEADD(day,1,Getdate())),
(1,2, DATEADD(day,1,Getdate())),
(2,3, Getdate()),
(2,3, DATEADD(day,1,Getdate()))
SELECT
*,
IIF(ROW_NUMBER() OVER (PARTITION BY t.OrderID, t.Customer ORDER BY t.OrderID) > 1, 'YES', 'NO') AS DualPurchase
FROM @Table AS t
答案 2 :(得分:0)
我认为这会对你有帮助..
Select
O.OrderID,O.[Order Date],c.Customer,c.[Customer City],P.Product,O.Amount,a.[More then Once]
from Orders O
inner join Customers C
on O.Customer_Id=C.Customer_Id
inner join Product P
On O.Product_Id=P.Product_Id
Cross Apply ( select Case when count(1)>1 then 'Yes' Else 'No' [More then Once] end from Orders
where Customer_Id=O.Customer_Id and cast([Order Date] as date)=cast(O.[Order Date] as date)
group by Customer_Id,cast([Order Date] as date)
) a