我有2个数据集:
1)
SELECT LocId
from map_Sites ms
inner join map_WaterSystems mw on mw.SiteId = ms.SiteId
inner join map_Locations ml on mw.SysID = ml.SysID
where ms.SiteId = 344 and LocId <> 9604
此数据集的结果是:
LocId
9605
9606
这是第二个数据集:
select dl.LocId, dl.ParamID, dl.alertNumExceed, dl.upperAlarm, dl.lowerAlarm, dl.alertOn, dl.EntryUserID, dl.ParamOrder
from data_LocParams dl where LocId = 9604
此数据集的结果是
LocId ParamID alertNumExceed upperAlarm lowerAlarm alertOn EntryUserID ParamOrder
9604 187 NULL NULL NULL 0 NULL NULL
9604 3057 NULL NULL NULL 0 NULL NULL
9604 3138 NULL NULL NULL 0 NULL NULL
我想要的最终结果是这样的:
LocId ParamID alertNumExceed upperAlarm lowerAlarm alertOn EntryUserID ParamOrder
9605 187 NULL NULL NULL 0 NULL NULL
9605 3057 NULL NULL NULL 0 NULL NULL
9605 3138 NULL NULL NULL 0 NULL NULL
9606 187 NULL NULL NULL 0 NULL NULL
9606 3057 NULL NULL NULL 0 NULL NULL
9606 3138 NULL NULL NULL 0 NULL NULL
注意每个LocId如何根据ParamID
重复答案 0 :(得分:0)
WITH ResultSet1 AS (
SELECT LocId
from map_Sites ms
inner join map_WaterSystems mw on mw.SiteId = ms.SiteId
inner join map_Locations ml on mw.SysID = ml.SysID
where ms.SiteId = 344 and LocId <> 9604
), ResultSet2 AS (
select dl.ParamID, dl.alertNumExceed, dl.upperAlarm, dl.lowerAlarm, dl.alertOn, dl.EntryUserID, dl.ParamOrder
from data_LocParams dl where LocId = 9604
)
select
ResultSet1.LocId, ResultSet2.*
from ResultSet1
cross join ResultSet2
在回答Nate的评论时,您可以使用WITH:
进行INSERTWITH ResultSet1 AS (
SELECT LocId
from map_Sites ms
inner join map_WaterSystems mw on mw.SiteId = ms.SiteId
inner join map_Locations ml on mw.SysID = ml.SysID
where ms.SiteId = 344 and LocId <> 9604
), ResultSet2 AS (
select dl.ParamID, dl.alertNumExceed, dl.upperAlarm, dl.lowerAlarm, dl.alertOn, dl.EntryUserID, dl.ParamOrder
from data_LocParams dl where LocId = 9604
)
insert into yourTable
select
ResultSet1.LocId, ResultSet2.*
from ResultSet1
cross join ResultSet2
或者你可以在没有WITH的情况下写这个:
insert into yourTable
select
ResultSet1.LocId, ResultSet2.*
from (
SELECT LocId
from map_Sites ms
inner join map_WaterSystems mw on mw.SiteId = ms.SiteId
inner join map_Locations ml on mw.SysID = ml.SysID
where ms.SiteId = 344 and LocId <> 9604
) as ResultSet1
cross join (
select dl.ParamID, dl.alertNumExceed, dl.upperAlarm, dl.lowerAlarm, dl.alertOn, dl.EntryUserID, dl.ParamOrder
from data_LocParams dl where LocId = 9604
) as ResultSet2