我有一个temptable临时存储数据,其中第一个字段是从查询中填充的,第二个字段是静态值
不是Temptable:
roomid
。isavailable
。现在我使用以下查询填充第一个字段,但是如何同时填充这两个字段?
以下是仅填充第一个字段的查询
insert into temptable (RoomID)
select t1.RoomId as RoomID
from Room t1
INNER JOIN
(
select RoomID, SUM(quantity) as QTY
from Room_Item
group by RoomID
having SUM(Quantity) > 0
) t2 on t1.RoomID = t2.RoomID
order by RoomID
答案 0 :(得分:3)
INNER JOIN
实际上只在房间可用时返回行。
你应该
LEFT JOIN
保留所有记录CASE
语句确定房间是否可用。SQL声明
insert into temptable (RoomID, IsAvailable)
select t1.RoomId as RoomID
, case when t2.qty IS NOT NULL then 1 ELSE 0 END
from Room t1
LEFT OUTER JOIN (
select RoomID, SUM(quantity) as QTY
from Room_Item
group by
RoomID
having SUM(Quantity) > 0
) t2 on t1.RoomID = t2.RoomID
答案 1 :(得分:3)
只需将静态值直接传递给SELECT
语句
INSERT INTO temptable (RoomID, isavailable)
SELECT t1.RoomId, 1 // static value
FROM Room t1
INNER JOIN
(
SELECT RoomID, SUM(quantity) AS QTY
FROM Room_Item
GROUP BY RoomID
HAVING SUM(Quantity) > 0
) t2 ON t1.RoomID = t2.RoomID
ORDER BY RoomID
答案 2 :(得分:1)
也许是这样的:
;WITH CTE
AS
(
select
RoomID,
SUM(quantity) OVER(PARTITION BY byRoomID) as QTY
from
Room_Item
)
insert into temptable
(
RoomID,
IsAvailable
)
select
Room.RoomId,
(
CASE
WHEN CTE.qty IS NOT NULL
THEN 1
ELSE 0
END
) AS IsAvailable
from
Room
LEFT JOIN CTE
ON t1.RoomId=CTE.RoomID
AND CTE.QTY>0
答案 3 :(得分:0)
insert into temptable (RoomID, IsAvailable)
select t1.RoomId as RoomID
, case when t2.qty IS NOT NULL then 1 ELSE 0 END
from Room t1
LEFT OUTER JOIN (
select RoomID, SUM(quantity) as QTY
from Room_Item
group byRoomID
having SUM(Quantity) > 0
) t2 on t1.RoomID = t2.RoomID
这可能会帮助您获得结果..
干杯... !!!