我正在运行一个查询,需要连接2个表,即Order表和OrderItem。当我加入它们时,它将在OrderItem表中为每个产品创建一行。我只需要OrderItem来检查一列是否有值。如何将结果分组以仅显示一个OrderId?
SELECT a.[Id]
,CustomerId
,OrderTotal
,ShippingMethod
,AffiliateId
,OrderDiscount
,OrderSubTotalDiscountInclTax
-- , b.DiscountAmountInclTax
FROM Order a JOIN OrderItem b ON a.Id = b.OrderId
WHERE AffiliateId = 11 AND b.DiscountAmountInclTax = 0.0000 AND OrderSubTotalDiscountInclTax = 0.0000 AND OrderDiscount = 0.0000 AND OrderStatusId = 30 AND CreatedOnUtc > '2018-07-01'
ORDER BY a.Id DESC
这将返回
Id CustomerId OrderTotal xxx xxx xxx xxx
1 1 5.00 x x x x
1 1 5.00 x x x x
2 2 5.00 x x x x
2 2 5.00 x x x x
我想按ID或OrderId分组
Id CustomerId OrderTotal xxx xxx xxx xxx
1 1 5.00 x x x x
2 2 5.00 x x x x
我知道这可能是一个无聊的问题,在此先感谢您的帮助。
答案 0 :(得分:0)
添加一个分组依据,应该为您工作,尽管通常情况下,您可能希望执行sum()使其有意义。
SELECT a.[Id]
,CustomerId
,OrderTotal
,ShippingMethod
,AffiliateId
,OrderDiscount
,OrderSubTotalDiscountInclTax
-- , b.DiscountAmountInclTax
FROM Order a JOIN OrderItem b ON a.Id = b.OrderId
WHERE AffiliateId = 11 AND b.DiscountAmountInclTax = 0.0000 AND OrderSubTotalDiscountInclTax = 0.0000 AND OrderDiscount = 0.0000 AND OrderStatusId = 30 AND CreatedOnUtc > '2018-07-01'
ORDER BY a.Id DESC
group by a.id
答案 1 :(得分:0)
只需添加distinct
SELECT distinct a.[Id] , CustomerId ,OrderTotal ,ShippingMethod ,AffiliateId ,OrderDiscount ,OrderSubTotalDiscountInclTax -- , b.DiscountAmountInclTax
FROM Order a
JOIN OrderItem b
ON a.Id = b.OrderId
WHERE AffiliateId = 11 AND b.DiscountAmountInclTax = 0.0000 AND
OrderSubTotalDiscountInclTax = 0.0000 AND OrderDiscount = 0.0000 AND OrderStatusId = 30 AND
CreatedOnUtc > '2018-07-01' ORDER BY a.Id DESC
答案 2 :(得分:0)
尝试类似的方法,我没有数据库和数据,但是您可以尝试执行以下步骤(将查询分为几个小步骤)
- 首先执行查询以按OrderId获取“订单”总计组,我认为一个订单与客户之间是一对一的关系
- 使用OrderID与订单表进行联接
此后,您可以在查询中添加订单或位置
SELECT a.[Id],
,CustomerId
,OrderTotal
,ShippingMethod
,AffiliateId
,OrderDiscount
,OrderSubTotalDiscountInclTax
FROM Order a JOIN (SELECT SUM(ItemTotalPrice),
CustomerId
,ShippingMethod
,AffiliateId
,OrderDiscount
,OrderSubTotalDiscountInclTax
GROUP BY b.OrderId) B
ON a.Id = b.OrderId
致谢