在我的SQL Server数据库中,一个客户可以拥有许多产品。
使用此包装时:
CASE
WHEN br.Ptype# = 'LE' THEN 'Y'
ELSE 'N'
END AS [Legal],
CASE
WHEN br.Ptype# = 'BR' THEN 'Y'
ELSE 'N'
END AS [BR],
CASE
WHEN br.Ptype# = 'WS' THEN 'Y'
ELSE 'N'
END AS [Screen],
CASE
WHEN br.Ptype# = 'TW' THEN 'Y'
ELSE 'N'
END AS [Van]
它返回:
Title FirstName LastName Email Legal BR Screen Van
Mr Aaaa Aaaa test.email@test.com N Y N N
Mr Aaaa Aaaa test.email@test.com Y N N N
如果此客户拥有这两种政策类型,我如何才能将返回的结果作为单行显示,其中Legal为Y,BR为Y?据我所知,这个客户有2种保险类型,我指定4我搜索我希望它返回结果如下:
Title FirstName LastName Email Legal BR Screen Van
Mr Aaaa Aaaa test.email@test.com Y Y N N
提前感谢您的帮助。
SELECT DISTINCT --TOP 1000
dbo.PARSE_NAME_UDF(yy.Name#,'H') AS [Title],
dbo.PARSE_NAME_UDF(yy.Name#,'F') AS [FirstName],
dbo.PARSE_NAME_UDF(yy.Name#,'L') AS [LastName],
yy.Email# AS [Email],
--br.PolRef@ AS [PolicyReference],
--bc.Datecreated# AS [Date Sold],
--br.Idat# AS [PolicyStartDate],
CASE
WHEN br.Ptype# = 'LE' THEN 'Y'
ELSE 'N'
END AS [Legal],
CASE
WHEN br.Ptype# = 'BR' THEN 'Y'
ELSE 'N'
END AS [BR],
CASE
WHEN br.Ptype# = 'WS' THEN 'Y'
ELSE 'N'
END AS [Screen],
CASE
WHEN br.Ptype# = 'TW' THEN 'Y'
ELSE 'N'
END AS [Van]
FROM brpolicy AS br
LEFT JOIN yyclient AS yy ON br.Ref@ = yy.Ref@ AND br.B@ = yy.B@
LEFT JOIN brcledger AS bc ON br.PolRef@ = bc.PolRef@ AND br.B@ = bc.B@
WHERE
br.Ref@ = 'AAAA06'
AND (br.Ptype# = 'WS'
OR br.Ptype# = 'LE'
OR br.Ptype# = 'BR'
OR br.Ptype# = 'TW'
)
请从where子句中忽略我的br.Ref @作为我的测试客户记录
答案 0 :(得分:0)
您可以使用MAX
:
SELECT Title,
FirstName,
LastName,
MAX(CASE
WHEN br.Ptype# = 'LE' THEN 'Y'
ELSE 'N'
END) AS [Legal],
MAX(CASE
WHEN br.Ptype# = 'BR' THEN 'Y'
ELSE 'N'
END) AS [BR],
CASE
WHEN br.Ptype# = 'WS' THEN 'Y'
ELSE 'N'
END AS [Screen],
MAX(CASE
WHEN br.Ptype# = 'TW' THEN 'Y'
ELSE 'N'
END) AS [Van]
FROM dbo.YourTable
GROUP BY Title,
FirstName,
LastName
答案 1 :(得分:-1)
试试这个
Select * from (SELECT Title,
FirstName,
LastName,
CASE
WHEN br.Ptype# = 'LE' THEN 'Y'
ELSE 'N'
END AS [Legal],
CASE
WHEN br.Ptype# = 'BR' THEN 'Y'
ELSE 'N'
END AS [BR],
CASE
WHEN br.Ptype# = 'WS' THEN 'Y'
ELSE 'N'
END AS [Screen],
CASE
WHEN br.Ptype# = 'TW' THEN 'Y'
ELSE 'N'
END AS [Van]
FROM dbo.YourTable
GROUP BY Title,
FirstName,
LastName) as tProduct where Legal = 'Y' and BR = 'Y'