SQL计算客户的特定项目

时间:2014-07-21 12:45:45

标签: sql sql-server

我需要渲染下表,以便现在客户支付了多少汉堡

  

客户|汉堡1数量|汉堡2数量|

我有两张桌子:

  • 客户表:使用CustomerID,名称
  • 交易订单:使用TransactionOrderID CustomerID和BurgerCode

我有6个汉堡代码,每个我需要添加一个列,最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

如果你不想使用支点,你可以尝试这样的事情。

   WITH cte AS
   ( 
   SELECT 
       CustomerID,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode1' THEN 1 ELSE 0 END) AS Burger1Qty,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode2' THEN 1 ELSE 0 END) AS Burger2Qty,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode3' THEN 1 ELSE 0 END) AS Burger3Qty,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode4' THEN 1 ELSE 0 END) AS Burger4Qty,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode5' THEN 1 ELSE 0 END) AS Burger5Qty,
       SUM(CASE WHEN BurgerCode LIKE 'BurgerCode6' THEN 1 ELSE 0 END) AS Burger6Qty
    FROM TransactionOrders
    GROUP BY CustomerID
    )
    SELECT c.*, ct.Name CustomerName FROM cte c JOIN CustomerTable ct ON ct.CustomerID = c.CustomerID