简体   繁体   English

SQL JOIN - Select 值到非不同行

[英]SQL JOIN - Select values to non distinct rows

This is hard to explain, but I'm doing an inner join on 2 tables where the values in the 2nd table are creating new rows instead of adding the values to the same row but adding the values to the columns instead.这很难解释,但我正在对 2 个表进行内部联接,其中第二个表中的值正在创建新行,而不是将值添加到同一行,而是将值添加到列。

So, my results look like this:所以,我的结果是这样的:

 Employee 1 | Supervisor 1
 Employee 1 | Supervisor 2
 Employee 1 | Supervisor 3

What I want the results to look like are like this我希望结果看起来像这样

Employee 1 | Supervisor 1 | Supervisor 2 | Supervisor 3`

This way I can formulate my WHERE clause to be a bit more specific这样我就可以更具体地制定我的WHERE子句

This is the query I'm using so far这是我目前使用的查询

SELECT HR.EMPLOYEE, HR_SUPERVISOR.Name
FROM data.dbo.HR
INNER JOIN data.dbo.HR_SUPERVISOR
ON HR.ID = hr_supervisor.ID
WHERE HR.EMPLOYEE IN
  (SELECT HR.EMPLOYEE FROM data.dbo.HR GROUP BY HR.EMPLOYEE HAVING COUNT(*) > 1) AND
  HR_SUPERVISOR.Name like '%Test%' 
  GROUP BY HR_SUPERVISOR.name, HR.EMPLOYEE
  ORDER BY HR.EMPLOYEE ASC

If the maximum number of supervisors is small (1-10) you can use the following method:如果监督者的最大数量较小(1-10),您可以使用以下方法:

  1. Get the inner join as base data for the final query获取内部连接作为最终查询的基础数据
  2. Generate a row number for the supervisors为主管生成行号
  3. Make it horizontal with some sub select (which will run fast enough if you pre-filter the baseData query with where clause)使其与一些子 select 水平(如果您使用 where 子句预过滤 baseData 查询,它将运行得足够快)
create view vw_Supervisors as
with baseData as 
(
    SELECT 
        HR.id id, 
        ROW_NUMBER() OVER (partition by HR.id order by HR_SUPERVISOR.Name asc) rowNo, 
        HR.EMPLOYEE employee, 
        HR_SUPERVISOR.Name supervisor 
    FROM HR INNER JOIN HR_SUPERVISOR ON HR.ID = hr_supervisor.ID
)
select 
    b.id,
    b.EMPLOYEE, 
    SUPERVISOR1=(select supervisor from baseData b1 where b1.id=b.id and rowNo=1), 
    SUPERVISOR2=(select supervisor from baseData b1 where b1.id=b.id and rowNo=2), 
    SUPERVISOR3=(select supervisor from baseData b1 where b1.id=b.id and rowNo=3),
    SUPERVISOR4=(select supervisor from baseData b1 where b1.id=b.id and rowNo=4),
    SUPERVISOR5=(select supervisor from baseData b1 where b1.id=b.id and rowNo=5)
from baseData b 
group by b.id, b.employee;

In case of many possible cols you should use the XML way to make it horizontal you can find examples for it (rows to cols t-sql) but it takes more effort for the server to run and harder to handle in frontend because of the changing number of columns.如果有许多可能的 cols,您应该使用 XML 方式使其水平,您可以找到它的示例(行到 cols t-sql)但是由于更改,服务器运行需要更多的努力并且在前端更难处理列数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM