我有一张桌子上有一些记录
主表
x------x--------------------x-------x
| Id | PERIOD | QTY |
x------x--------------------x-------x
| 1 | 2014-01-13 | 10 |
| 2 | 2014-01-06 | 30 |
x------x--------------------x-------x
我还有另一个带有此记录(ID)参数的表
TABLE2
x------x--------------------x------------x
| Id | Parameter | Value |
x------x--------------------x------------x
| 1 | Humidty | 10 |
| 1 | Temperature | 30 |
| 2 | Humidty | 50 |
| 2 | Temperature | 40 |
x------x--------------------x------------x
结果,我想要这个:(根据ID组合)
结果表
x------x--------------------x-------------------------x
| Id | Period | Humidty | Temperature |
x------x--------------------x-------------------------x
| 1 | 2014-01-13 | 10 | 30 |
| 2 | 2014-01-06 | 50 | 40 |
x------x--------------------x-------------------------x
我该怎么做?我认为内部加入是行不通的。
答案 0 :(得分:4)
加入表,并与case
一起使用条件聚合来提取2列:
select t1.id, t1.period,
max(case when t2.parameter = 'Humidty' then t2.value end) Humidty,
max(case when t2.parameter = 'Temperature' then t2.value end) Temperature
from mastertable t1 inner join table2 t2
on t2.id = t1.id
group by t1.id, t1.period
答案 1 :(得分:0)
您可以pivot
:
SELECT * FROM
(
SELECT
t_m.Id
, t_m.Period
, t_2.Parameter
, t_2.Value
FROM @tbl_Master t_m
INNER JOIN @tbl_2 t_2 ON t_2.Id = t_m.Id
)AS t
PIVOT
(
MAX(t.Value)
FOR t.Parameter IN ([Humidity], [Temperature])
)pvt
和示例数据:
DECLARE @tbl_Master TABLE
(
Id int,
Period Date,
QTY int
)
DECLARE @tbl_2 TABLE
(
Id int,
Parameter varchar(30),
[Value] int
)
INSERT INTO @tbl_Master
(
Id,
Period,
QTY
)
VALUES
(1, '2014-01-13', 10)
, (2, '2014-01-06', 30)
INSERT INTO @tbl_2
(
Id ,
Parameter ,
[Value]
)
VALUES
( 1, 'Humidity', 10)
, ( 1, 'Temperature' , 30)
, ( 2, 'Humidity', 50)
, ( 2, 'Temperature' , 40)
输出:
Id Period Humidity Temperature
1 2014-01-13 10 30
2 2014-01-06 50 40
答案 2 :(得分:0)
尝试一下
DECLARE @Mastertable AS TABLE(Id INT,PERIOD DATE,QTY INT)
INSERT INTO @Mastertable
SELECT 1 ,'2014-01-13', 10 UNION ALL
SELECT 2 ,'2014-01-06', 30
DECLARE @Childtable AS TABLE(Id INT,Parameter VARCHAR(100), Value INT)
INSERT INTO @Childtable
SELECT 1 ,'Humidty' , 10 UNION ALL
SELECT 1 ,'Temperature' , 30 UNION ALL
SELECT 2 ,'Humidty' , 50 UNION ALL
SELECT 2 , 'Temperature' , 40
SELECT Id,Period,[Humidty],[Temperature]
FROM
(
SELECT c.Id,
m.PERIOD,
Parameter,
c.Value
FROM @Mastertable m
INNER JOIN @Childtable c
ON m.Id = c.Id
) AS srC
pivot
(MAX(Value) FOR Parameter IN ([Humidty],[Temperature])
) AS PVT
结果
Id Period Humidty Temperature
----------------------------------
1 2014-01-13 10 30
2 2014-01-06 50 40