0

I'm trying to find orders placed by customers that total at least $250. Then I need to compare the actual items they purchased per order, and see how many are worth below or under $100.

So say they purchased 5 items total. Two are worth at least $100. Three are less. The results would be:

OrderID  LargeItems  SmallItems  Total
1112     2           3           5

So that's a rough example of what I'm after.

Right now I have:

--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

If you can't easily tell:

  • OP.Pprice is the price of individual items in the order
  • O.Total is the order total

I'm missing the Large and Small item columns. How can I put those separate counts in as well?

Thanks! Please ask if you need any extra info.

4

1 回答 1

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
于 2013-07-11T19:15:34.730 回答