我正在尝试编写一个查询,每个employerid
只生成一行,而不是每个雇主生成多行,并且一次只填充一列。我通过查询获得以下内容:
我正在使用的查询是:
SELECT Employer.employerid,
CASE WHEN Service.xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END AS Service1,
CASE WHEN Service.xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END AS Service2,
CASE WHEN Service.xxserviceid = '3' THEN 'Number 2' ELSE 'NULL' END AS Service3
FROM Employer
INNER JOIN Service
ON Service.employerid = Employer.employerid;
所以我希望每个雇主在一行中填写Service1
,Service2
,Service3
列,而不是每个雇主多行。
答案 0 :(得分:1)
您可以使用GROUP BY
+ MAX
将结果减少到每位员工一行:
SELECT Employer.employerid,
max(CASE WHEN Service.xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END) AS Service1,
max(CASE WHEN Service.xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END) AS Service2,
max(CASE WHEN Service.xxserviceid = '3' THEN 'Number 3' ELSE 'NULL' END) AS Service3
FROM Employer
INNER JOIN Service
ON Service.employerid = Employer.employerid
GROUP BY Employer.employerid;
如果你考虑一下,你甚至不需要加入Employer
表,因为你所使用的只是employerid
列,它已经存在于Service
。
因此,查询可以简化为:
SELECT employerid,
max(CASE WHEN xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END) AS Service1,
max(CASE WHEN xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END) AS Service2,
max(CASE WHEN xxserviceid = '3' THEN 'Number 3' ELSE 'NULL' END) AS Service3
FROM Service
GROUP BY employerid;
SQLFiddle:http://www.sqlfiddle.com/#!6/004a9/2
答案 1 :(得分:0)
SELECT Employer.employerid,
MAX(CASE WHEN Service.xxserviceid = '1' THEN 'Number 1' ELSE 'NULL' END) AS Service1,
MAX(CASE WHEN Service.xxserviceid = '2' THEN 'Number 2' ELSE 'NULL' END) AS Service2,
MAX(CASE WHEN Service.xxserviceid = '3' THEN 'Number 2' ELSE 'NULL' END) AS Service3
FROM Employer
INNER JOIN Service
ON Service.employerid = Employer.employerid;
GROUP BY Employer.employerID
答案 2 :(得分:0)
据我了解您的问题,您可能只需要一个服务列。 这篇文章中提供的其他答案应该有效。如果您只需要一个“服务”列,则可以尝试以下操作:
SELECT Employer.employerid,
'Number ' + Max(Service.xxserviceid) AS Service1
FROM Employer
INNER JOIN Service
ON Service.employerid = Employer.employerid;
GROUP BY Employer.employerid