SQL从具有计算列的查询中插入值

时间:2017-02-09 18:32:33

标签: sql sql-server stored-procedures

我有一张这样的表:

id type | month | value

类型为ACFCBG

我想为每个不同的行ID创建,键入(其中type为ACFC)一个类型为AF且值为AC的新行(如果存在)或FC {AC值优先于FC值。

目前,我可以提取唯一列表,我必须为每个项目创建一个新行:

select id_prj,month  from table where type='AC' or type='FC' group by id_prj,month

如何为此查询返回的每个项目创建一个新行,其值可以根据其存在而采用AC或FC值。

下表示例

| ID_PRJ | TYPE | MONTH | VALUE |
-----------------------------
| 1  | AC   |  1    | 1000  |
-----------------------------
| 1  | FC   |  1    | 200  |
-----------------------------
| 3  | BG   |  1    | 1000  |
-----------------------------
| 4  | FC   |  2    | 100  |

插入后的表格应为:

| ID_PRJ | TYPE | MONTH | VALUE |
-----------------------------
| 1  | AC   |  1    | 1000  |
-----------------------------
| 1  | FC   |  1    | 200  |
-----------------------------
| 3  | BG   |  1    | 1000  |
-----------------------------
| 4  | FC   |  2    | 100  |
-----------------------------
| 1  | AF   |  1    | 1000  |
-----------------------------
| 4  | AF   |  2    | 100  |

3 个答案:

答案 0 :(得分:2)

怎么样:

insert into table (ID_PRJ, TYPE, Month, Value)


select id_prj,type,month,value from (
select id_prj,'FC' as type, month,value  , row_number() over ( partition by id_prj order by type asc) rowid
from table 
where type='AC' or type='FC' 
) as x where rowid = 1

答案 1 :(得分:1)

您似乎只是在改变类型。我认为这样做。

insert into table (ID_PRJ, TYPE, Month, Value)
Select ID_PRJ, 'AF' Type, Month, Value
from table where Type in ('AC','FC')

答案 2 :(得分:1)

一种相当简单的方法是使用完全连接到派生表。

创建并填充样本表(在将来的问题中保存此步骤):

DECLARE @T AS TABLE
(
    ID_PRJ int,
    TYPE char(2),
    MONTH int,
    VALUE int
)

INSERT INTO @T VALUES
(1, 'AC', 1, 1000),
(1, 'FC', 1, 200),
(3, 'BG', 1, 1000),
(4, 'FC', 2, 100)

insert ... select语句:

INSERT INTO @T (ID_PRJ, MONTH, TYPE, VALUE)
SELECT  ISNULL(t1.ID_PRJ, t0.ID_PRJ), 
        ISNULL(t1.MONTH, t0.MONTH), 
        'AF', 
        ISNULL(t1.VALUE, t0.VALUE)
FROM @T t0
FULL JOIN
(
    SELECT ID_PRJ, MONTH, TYPE, VALUE
    FROM @T 
    WHERE TYPE = 'AC'
) t1 ON t0.ID_PRJ = t1.ID_PRJ
    AND t0.MONTH = t1.MONTH
WHERE t0.TYPE IS NULL OR t0.TYPE = 'FC'

验证插入:

SELECT ID_PRJ, MONTH, TYPE, VALUE
FROM @T

结果:

ID_PRJ  MONTH   TYPE    VALUE
1       1       AC      1000
1       1       FC      200
3       1       BG      1000
4       2       FC      100
1       1       AF      1000
4       2       AF      100