SQL 使用 VALUES 生成带数据的临时表实例代码详解
(编辑:jimmy 日期: 2024/11/25 浏览:3 次 )
VALUES 是 INSER 命令的子句。
INSERT INOT 表名(列名1,列名2,…) VALUES(值1,值2,…)
--语法: --SELECT * FROM ( --VALUES -- (1,2,3,......) -- ,(1,2,3,......) -- ,(1,2,3,......) -- ,(1,2,3,......) -- ,(1,2,3,......) -- ,(1,2,3,......) --) AS t(c1,c2,c3......) SELECT * FROM ( VALUES (123456),(123456),(123456),(123456),(123456) ) AS T(c1)
试检1
-- 试检1 SELECT * FROM ( VALUES (123456),(123456),(123456),(123456),(123456) ) AS T(c1)
试检2
-- 试检2 生成1个列的临时表 select * into #tmpTable FROM ( VALUES (123456),(123456),(123456),(123456),(123456) ) AS T(c1)
试检3
-- 生成5个列的临时表 #tmpTable2 select * into #tmpTable2 FROM ( VALUES (1,2,3,4,123456) ,(2,3,4,5,123456) ,(3,4,5,6,123456) ,(4,100,100,3,123456) ,(23,4,5,5,123456) ) AS T(c1,c2,c3,c4,c5) select * from #tmpTable2
成功了高级一点的例子
计算5列的平均值,求各,最大值,最小值,计数
使用values子句,将每行数据构造为只有一个字段的表,以后求最大值,非常巧妙
-- 计算5列的平均值,求各,最大值,最小值,计数 select * into #tmpTable3 FROM ( VALUES (1,2,3,4,123456) ,(2,3,40000,5000,123456) ,(3,4222,5,6000,123456) ,(4,100,100,3,123456) ,(23,4,5,5,123456) ) AS T(c1,c2,c3,c4,c5) select a.* ,(select Max(NewData) from (values (C1),(C2),(C3),(C4),(C5)) as #temp(NewData)) as nMax ,(select Min(NewData) from (values (C1),(C2),(C3),(C4),(C5)) as #temp(NewData)) as nMai ,(select Sum(NewData) from (values (C1),(C2),(C3),(C4),(C5)) as #temp(NewData)) as nSum ,(select Avg(NewData) from (values (C1),(C2),(C3),(C4),(C5)) as #temp(NewData)) as nAvg ,(select count(NewData) from (values (C1),(C2),(C3),(C4),(C5)) as #temp(NewData)) as nCount from #tmpTable3 as a
下一篇:推荐SQL Server 重新恢复自动编号列的序号的sql代码