SQL Server 2014:INSERT INTO值&子查询

时间:2016-12-03 22:23:40

标签: sql sql-server tsql

我正在尝试通过输入值并从子查询中获取1来将值插入到1个表中,我不确定如何将SaleEventID, PoolName & CurrentUPB的STATIC VALUES与给出值的SELECT语句结合起来PoolID

我会扩展它以包含更多列,我可能需要包含其他选择子查询。

什么是正确的格式?

SELECT DISTINCT [PoolID] 
FROM TESTLOANS
WHERE SaleEventID = 0

尝试将它们组合在一起,但它不起作用。

INSERT INTO TESTPOOLS (SaleEventID, PoolID, PoolName, CurrentUPB)
VALUES ('55', [POOLID], 'SouthernFL', '45,000')

SELECT DISTINCT [PoolID] 
FROM TESTLOANS
WHERE SaleEventID = 55

更新:现在返回我可以使用的CurrentUPB值

SELECT SUM(CurrentUPB) CurrentUPB 
FROM TESTLOANS
WHERE SaleEventID = 0

如果我还有一些这样的select语句给我一些INSERTS的值,我该如何将它们添加到主查询中?

1 个答案:

答案 0 :(得分:5)

按原样使用select并在同一语句中包含静态值。

INSERT INTO TESTPOOLS (SaleEventID, PoolID, PoolName, CurrentUPB)
SELECT DISTINCT '55', [POOLID], 'SouthernFL', '45,000'
FROM TESTLOANS
WHERE SaleEventID=0

编辑:使用窗口函数来获取计数或总和。

例如:

INSERT INTO TESTPOOLS (SaleEventID, PoolID, PoolName, CurrentUPB,somecount)
SELECT DISTINCT '55', [POOLID], 'SouthernFL'
,sum(currentUPB) over(partition by poolid) --if you don't need the sum by poolid just use sum(currentUPB) over()
,count(*) over(partition by poolid) --if you don't need the count by poolid just use count(*) over()
FROM TESTLOANS
WHERE SaleEventID=0