我正在努力寻找总价至少250美元的客户订单。然后我需要比较他们每个订单购买的实际商品,看看有多少价值低于或低于100美元。
所以说他们共购买了5件商品。两个价值至少100美元。三个少了。结果将是:
OrderID LargeItems SmallItems Total
1112 2 3 5
这就是我所追求的一个粗略的例子。
现在我有:
--Total Items purchased in orders worth $250 or more
SELECT O.OrderID,COUNT(OP.Price) as 'Total'
FROM dbo.tblOrder O WITH (NOLOCK)
INNER JOIN dbo.tblOrderProduct OP WITH (NOLOCK)
ON O.OrderID=OP.OrderID
WHERE O.OrderDate BETWEEN '2011-01-01' AND '2013-01-01'
and O.Total >= 250
group by O.OrderID
order by O.OrderID
如果你不能轻易说出来:
我错过了大项目和小项目列。我怎样才能将这些单独的计数加入?
谢谢!请询问您是否需要任何额外信息。
答案 0 :(得分:5)
您可以使用CASE
语句执行此操作:
SELECT O.OrderID
,SUM(CASE WHEN OP.Price >= 100 THEN 1 ELSE 0 END)'LargeItems'
,SUM(CASE WHEN OP.Price < 100 THEN 1 ELSE 0 END)'SmallItems'
,COUNT(OP.Price) as 'Total'
FROM dbo.tblOrder O WITH (NOLOCK)
INNER JOIN dbo.tblOrderProduct OP WITH (NOLOCK)
ON O.OrderID=OP.OrderID
WHERE O.OrderDate BETWEEN '2011-01-01' AND '2013-01-01'
and O.Total >= 250
group by O.OrderID
order by O.OrderID