我有一张桌子如下。
customer_number note loayltystatus Tier_code
123 yes
123 yes 1
123 1
如何在select语句中组合上面两行中的一行?
EG:
customer_number note loayltystatus Tier_code
123 yes 1 1
答案 0 :(得分:4)
SELECT customer_number, MAX(note),MAX(loyaltyStatus),MAX(Tier_code)
FROM yourTable
GROUP BY customer_number
答案 1 :(得分:0)
我使用SQL Server FOR XML
语句将多行组合成一行。这将考虑每个行中具有不同值的任意数量的行。
IF OBJECT_ID(N'tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t
(
customer_number INT,
note NVARCHAR(100),
loyaltystatus INT,
Tier_code INT
)
INSERT INTO #t SELECT 123, N'yes', NULL, NULL
INSERT INTO #t SELECT 123, N'yes', 1, NULL
INSERT INTO #t SELECT 123, N'yes', NULL, 1
INSERT INTO #t SELECT 123, N'something else', NULL, NULL
SELECT
customer_number,
STUFF(
(SELECT DISTINCT N',' + note
FROM #t AS s
WHERE s.customer_number = t.customer_number
ORDER BY N',' + note
FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
,1,1,N'') AS note,
STUFF(
(SELECT DISTINCT N',' + CAST(loyaltystatus AS NVARCHAR(100))
FROM #t AS s
WHERE s.customer_number = t.customer_number
ORDER BY N',' + CAST(loyaltystatus AS NVARCHAR(100))
FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
,1,1,N'') AS loyaltystatus,
STUFF(
(SELECT DISTINCT N',' + CAST(Tier_code AS NVARCHAR(100))
FROM #t AS s
WHERE s.customer_number = t.customer_number
ORDER BY N',' + CAST(Tier_code AS NVARCHAR(100))
FOR XML PATH(''), TYPE).value('.',N'nvarchar(max)')
,1,1,N'') AS Tier_code
FROM
#t AS t
GROUP BY customer_number