插入max+;1基于SQL中的数据组

插入max+;1基于SQL中的数据组,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有如下表1 1 Data1 type1 price1 2 Data2 type1 price2 3 Data3 type2 price3 4 Data4 type2 price4 第一列1、2、3、4为非同一列(手动递增) 我想插入另一张桌子 Table1(max+1) Data1 type1 price1 Table1(max+1) Data2 type1 price2 Table1(max+1) Data3 type2 price3 Table1(max+1) Data4 ty

我有如下表1

1 Data1 type1 price1
2 Data2 type1 price2
3 Data3 type2 price3
4 Data4 type2 price4
第一列1、2、3、4为非同一列(手动递增)

我想插入另一张桌子

Table1(max+1)  Data1 type1 price1
Table1(max+1)  Data2 type1 price2
 Table1(max+1)  Data3 type2 price3
Table1(max+1)  Data4 type2 price4
结果应该是这样的,基于type1,type2,它应该递增

5  Data1 Apple price1
5  Data2 Apple price2
6  Data3 Orange price3
6  Data4 Orange price4
给你

SELECT
    CAST(SUBSTRING(t1.Type, 5, 100) AS INT) + 4,
        /* In place of 4, use whatever base value you want */
    t1.Data,
    t1.Type,
    t1.Price    
FROM TestTable1 t1;
输出:

|   |  Data |  Type |  Price |
|---|-------|-------|--------|
| 5 | Data1 | type1 | price1 |
| 5 | Data2 | type1 | price2 |
| 6 | Data3 | type2 | price3 |
| 6 | Data4 | type2 | price4 |

尝试使用窗口功能:

select
    max(id) over() + dense_rank() over(order by type) as id,
    data,
    type,
    price   
from table
max(id)over()
这将为您提供id的最大值


densite_rank()over(按类型排序)
这将为从1开始的相同类型对具有相同值的行进行排序。

如果我们这样插入,您的查询将出现错误--插入TestTable1选择1,'Data1','Apple','price1'UNION ALL SELECT 2,'Data2','Apple','price2'UNION ALL SELECT 3','Data3','Orange','price3'UNION ALL SELECT 4',Data4',‘橙色’、‘价格4’@Venkat单击SQL Fiddle链接。我使用了相同的链接,将varchar值“e”转换为int数据类型时转换失败。Type1、Type2将是任何类似APPLE的文本,Orange@Venkat啊,在最初的问题中,这将是一个很好的信息。你能更新它吗?让我们看看。与类型“Apple”和“Orange”相关的数值在哪里?不,这只是我使用的示例,类型1,类型2,它可以是任何字符串,但你希望你的
INT
根据
类型
字段以某种方式递增。您需要描述这两个值之间的关系。