如何返回包含多个列值的行?

时间:2016-08-09 21:06:21

标签: sql sql-server select

我尝试为每个客户创建一行报告,但每个客户有多行。

目前的观点是:

Customer    Business    Dept    Type    Status
-----------------------------------------------
019        Public       null    null    null         
019         null        IT      null    null
019         null        null    Retail  0 --char(1) 

我希望的观点是:

Customer    Business    Dept    Type    Status
-----------------------------------------------
019        Public       IT      Retail   0

我正在使用SQL Server 2008 R2。我的数据集中有更多列,但这是一个示例。当我的数据类型是字符而不是基于INT时,我不确定如何实现结果。

2 个答案:

答案 0 :(得分:3)

如果这是一个有代表性的示例,并且每列都会有一行带有值,而其他列会有null s,则可以使用汇总maxmin ,忽略null s:

SELECT   customer, MAX(business), MAX(dept), MAX(type), MAX(status)
FROM     mytable
GROUP BY customer

答案 1 :(得分:1)

尝试一下这个:

CREATE TABLE #tmp ([Customer] CHAR(3), [Business] VARCHAR(20), [Dept] VARCHAR(20), [Type] VARCHAR(20), [Status] CHAR(1))
INSERT INTO #tmp (Customer, Business) VALUES (  '019',  'Public')
INSERT INTO #tmp (Customer,Dept) VALUES ('019','IT')
INSERT INTO #tmp (Customer,[Type]) VALUES ('019','Retail')
INSERT INTO #tmp (Customer,[Status]) VALUES ('019','0')
SELECT * FROM #tmp AS t

SELECT t.Customer, t.Business, t2.Dept, t3.[Type], t4.[Status] FROM #tmp AS t 
JOIN #tmp AS t2 ON t2.Customer = t.Customer 
JOIN #tmp AS t3 ON t3.Customer = t.Customer
JOIN #tmp AS t4 ON t4.Customer = t.Customer
WHERE t.Business IS NOT NULL AND t2.Dept IS NOT NULL AND t3.[Type] IS NOT NULL AND t4.[Status] IS NOT NULL