2016-09-16 135 views
2

舉例來說,我有一張表,其中包含客戶在咖啡館中活動的描述。 (比喻實際的表的我的工作)將多行組合成一行

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 

我做自聯接與聚結結合,但它並沒有給我想要的結果。

+0

想必你只是想'總和([借來的書]),SUM([下令飲料]),MAX([有公司])'和組按客戶? – ZLK

+0

@ZLK,是的,有點..但初始表實際上是一個結果集的臨時表,我不能通過聚合問題 –

+0

哼。如果不知道原始數據是什麼以及爲什麼會遇到聚合問題,很難提供幫助。注意:當執行總和時,您可能還需要一個'isnull(x,0)'語句。 – ZLK

回答

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 
1

您可以通過組做到這一點,

select Customer,sum([borrowed book]), sum([ordered drink]), max([has company]) 
from customeractivity group by Customer 
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 
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 

OUTPUT:

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