SQL Query用于组合两个表中的行

时间:2014-11-16 19:25:42

标签: sql sql-server

我有桌子,我们称之为Master。

+--------+------+------+
| Master | Name | Vaue |
+--------+------+------+
|    101 | A    |   12 |
|    202 | B    |   14 |
|    303 | C    |   12 |
|    404 | D    |   18 |
|    505 | E    |   16 |
+--------+------+------+

我有一个名为Steps的第二个表。

+--------+----------+-------+
| StepID | MasterID | Time  |
+--------+----------+-------+
|      1 |      101 | 14:53 |
|      2 |      101 | 15:24 |
|      1 |      202 | 02:23 |
|      2 |      202 | 05:15 |
|      3 |      202 | 07:42 |
|      1 |      303 | 22:10 |
|      2 |      303 | 22:15 |
|      1 |      505 | 11:59 |
|      2 |      505 | 12:25 |
|      3 |      505 | 12:48 |
+--------+----------+-------+

我想查询将3列(3 StepID)和时间值添加到Master表。

第一列是时间值,其中Master.MasterID = Steps.MasterID和StepID = 1.

第二列是时间值,其中Master.MasterID = Steps.MasterID和StepID = 2.

第三列是时间值,其中Master.MasterID = Steps.MasterID和StepID = 3.

创建的表必须与主表具有相同的行数。

+--------+------+------+-------+-------+-------+
| Master | Name | Vaue | Time1 | Time2 | Time3 |
+--------+------+------+-------+-------+-------+
|    101 | A    |   12 | 14:53 | 15:24 | -     |
|    202 | B    |   14 | 02:23 | 05:15 | 07:42 |
|    303 | C    |   12 | 22:10 | 22:15 | -     |
|    404 | D    |   18 | -     | -     | -     |
|    505 | E    |   16 | 11:59 | 12:25 | 12:48 |
+--------+------+------+-------+-------+-------+

3 个答案:

答案 0 :(得分:0)

select m.Master, m.Name, m.Value,  
       max(case when s.StepId = 1 then s.Time else NULL end) as Time1,
       max(case when s.StepId = 2 then s.Time else NULL end) as Time2,
       max(case when s.StepId = 3 then s.Time else NULL end) as Time3
from Master m left join Steps s on m.Master = s.MasterID
group by m.Master, m.Name, m.Value;

答案 1 :(得分:0)

您可以为每个步骤组合单独的联接,并使用与此类似的查询:

SELECT m.Master, m.Name, m.Value, s1.Time as Time1, s2.Time as Time2, s3.Time as Time3
FROM Master m
    LEFT JOIN Steps s1 ON m.Master = s1.MasterID AND s1.StepId = 1
    LEFT JOIN Steps s2 ON m.Master = s2.MasterID AND s2.StepId = 2
    LEFT JOIN Steps s3 ON m.Master = s3.MasterID AND s3.StepId = 3

答案 2 :(得分:0)

如果您使用SQL Server,另一种方法是使用pivot运算符:

select 
    Master,
    Name,
    Value, 
    [1] as Time1, 
    [2] as Time2, 
    [3] as Time3 
from Master m
left join Steps s on m.Master = s.MasterID
pivot (
    max ([Time]) for StepID IN ([1], [2], [3])
) AS p