SQL:字段合并

时间:2012-12-02 23:23:42

标签: sql sql-server-2008-r2

使用此查询时,我有一个我想要的结果,但我需要合并Beer.Name实例。这样,当我想将CustomerID和Beer.Name合并为单个实体时,我的输出中有多个Beer.Name及其数量的条目。我该怎么做?

SELECT C.CustomerID, Beer.Name,sum (quantitysupplied)as 'Total Quantity'
FROM Customer C
INNER JOIN CustomerOrder
    ON C.CustomerID = CustomerOrder.CustomerID 
INNER JOIN CustomerOrderLine
    ON CustomerOrderLine.CustomerOrderID = CustomerOrder.CustomerOrderID 
INNER JOIN Product
    ON CustomerOrderLine.ProductID =Product.ProductID 
INNER JOIN Beer
    ON Product.BeerID = Beer.BeerID
GROUP BY C.CustomerID, Beer.Name, CustomerType
HAVING CustomerType LIKE 'C'

谢谢。

这是输出:

      CustomerID  Name                           Total Quantity
 ----------- ------------------------------ --------------
  1001        Ale Heads                      11
 1002        Ale Heads                      8
  1003        Ale Heads                      13
  1004        Ale Heads                      3
  1006        Ale Heads                      4
  1007        Ale Heads                      14
  1008        Ale Heads                      4
 1009        Ale Heads                      4

这很长,但这很有代表性,我希望只有一个啤酒名称和客户ID的实例合并到其他地方。

1 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

SELECT CAST(C.CustomerID AS varchar) + ': ' + Beer.Name AS CustomerBeer, Sum(quantitysupplied) AS 'Total Quantity'
FROM etc.