0

我有需要创建的特定报告。我有两张表,一张是我公司的工作数据,另一张是在那里工作的人的数据。在工作表中有一个数据字段,其中包含有多少人可以从事某项工作的数据(工作名称和 1、2 或其他人数)。我需要显示工作名称的报告,然后列出从事该工作的人员列表,但这是个问题,如果人少,那么工作地点我需要为每个空的工作地点添加空行。例子:

job name 1 = 3 places
job name 2 = 4 places

报告:

JOB NAME 1
---------------------- 
WORKING MAN NAME 1   
WORKING MAN NAME 2   
--- empty place ---  

JOB NAME 2
----------------------
WORKING MAN NAME 1   
WORKING MAN NAME 2   
--- empty place --- 
--- empty place --- 

我忘了提到我正在 IBM 系统 Z 上使用 DB2 数据库,并且我正在使用 Visual Studio 10 构建报告。我的两个表是:

工作:job_id、job_name、job_num_places

工人:worker_id,worker_name,job_id

我正在加入 job_id 上的表格

4

1 回答 1

0
WITH JobPositions AS (
    SELECT 'Job1' AS JobName, 3 AS Positions
  UNION ALL
    SELECT 'Job2', 4 AS Positions
)
,Workers AS (
    SELECT 'Worker1' AS WorkerName, 'Job1' AS JobName
  UNION ALL
    SELECT 'Worker2' AS WorkerName, 'Job1' AS JobName
  UNION ALL
    SELECT 'Worker3' AS WorkerName, 'Job2' AS JobName
)
-- Real query starts here.
-- Create a line for each position in each job
, JobPositionNumber AS (
    SELECT JobName, Positions, 1 AS PositionNumber
    FROM JobPositions
  UNION ALL
    SELECT JobName, Positions, PositionNumber + 1
    FROM JobPositionNumber
    WHERE PositionNumber < Positions
)
-- Number the workers from 1 and up per job
, WorkerPositionNumber AS (
    SELECT WorkerName
          ,JobName
          ,ROW_NUMBER() OVER (PARTITION BY JobName
                              ORDER BY WorkerName) AS PositionNumber
    FROM Workers
)
-- Now just join numbered jobs with numbered workers
SELECT JobPositionNumber.JobName
      ,CASE WHEN WorkerPositionNumber.WorkerName IS NULL 
            THEN '--- empty place ---' 
            ELSE WorkerName 
       END AS WorkerName 
FROM JobPositionNumber
     LEFT JOIN WorkerPositionNumber
         ON JobPositionNumber.JobName = WorkerPositionNumber.JobName
            AND JobPositionNumber.PositionNumber = WorkerPositionNumber.PositionNumber
ORDER BY JobPositionNumber.JobName
        ,JobPositionNumber.PositionNumber
于 2013-11-10T00:01:57.123 回答