将多行合并为一行

时间:2016-09-16 04:25:55

标签: sql sql-server database

比如说我有一张表,其中包含客户在咖啡馆时的活动说明。 (我正在处理的实际表的隐喻)

Customer    Borrowed Book   Ordered Drink   Has Company
1               1       
1                                1  
1                                               Yes
2                                1  
3                                1  
3                                               Yes
4               1                1  
4                                1  

我希望以这种方式组合行

Customer    Borrowed Book   Ordered Drink   Has Company
1               1                 1            Yes
2                                 1 
3                                 1            Yes
4               1                 2

我自己加入了coalesce,但它没有给出我想要的结果。

4 个答案:

答案 0 :(得分:1)

您可以通过分组

执行此操作
select Customer,sum([borrowed book]), sum([ordered drink]), max([has company])
from customeractivity group by Customer

答案 1 :(得分:0)

根据你的评论,初始表是临时表, 尝试将结果作为cte结果,然后对其进行聚合,如下面的查询。

   ; WITH cte_1
      AS
     (  //your query to return the result set)
   SELECT customer,sum([borrowed book]) BorrowedBook, 
        sum([ordered drink]) OrderedDrink, 
        max([has company]) HasCompany
   FROM cte_1
   GROUP BY Customer

答案 2 :(得分:0)

使用分组依据:

DECLARE @tblTest as Table(
    Customer INT,
    BorrowedBook INT,
    OrderedDrink INT,
    HasCompany BIt
)

INSERT INTO @tblTest VALUES
(1,1,NULL,NULL)
,(1,NULL,1,NULL)
,(1,NULL,NULL,1)
,(2,NULL,1,NULL)
,(3,NULL,1,NULL)
,(3,NULL,NULL,1)
,(4,1,1,NULL)
,(4,NULL,1,NULL)

SELECT 
    Customer,
    SUM(ISNULL(BorrowedBook,0)) AS BorrowedBook,
    SUM(ISNULL(OrderedDrink,0)) AS OrderedDrink,
    CASE MIN(CAST(HasCompany AS INT)) WHEN 1 THEN 'YES' ELSE '' END AS HasCompany
FROM @tblTest
GROUP BY Customer

答案 3 :(得分:0)

不确定,为什么你会在群组中遇到错误。

你的合并应该是正确的。请参阅以下方式。

Select customer
, case when [borrowed] = 0 then NULL else [borrowed] end as [borrowed]
, case when [ordered] = 0 then NULL else [ordered] end as [ordered]
, case when [company] = 1 then 'Yes' end as company
from 
(
    Select customer,
    coalesce(
    case when (case when borrowed = '' then null else borrowed end) = 1 then 'borrowed' end,
    case when (case when ordered = '' then null else ordered end) = 1 then 'ordered' end,
    case when (case when company = '' then null else company end) = 'Yes' then 'company' end
    ) val
    from Table
) main
PIVOT
(
    COUNT (val)
    FOR val IN ( [borrowed], [ordered], [company] )
) piv

输出:

customer | borrowed | ordered | company
---------------------------------------
1           1           1           Yes
2           NULL        1           NULL
3           NULL        1           Yes