2017-10-20 45 views
1

Je le tableau suivant:SQL: Insérer nouvelle colonne dans la même table

create table Finance 
(
     [Product] int 
     ,[Timestamp] datetime 
     ,[Price] numeric(16, 4) 
) 

INSERT INTO Finance([Product], [Timestamp], [Price]) 
     VALUES 
       (5678, '20080101 12:00:00', 12.34) 
      ,(5678, '20080101 12:01:00', NULL) 
      ,(5678, '20080101 12:02:00', NULL) 
      ,(5678, '20080101 12:03:00', 23.45) 
      ,(5678, '20080101 12:04:00', NULL) 
      ,(5679, '20080101 13:04:00', NULL) 
      ,(5679, '20080101 13:05:00', 30.35) 
      ,(5679, '20080101 13:06:00', NULL) 

et retourne la requête suivante sortie désirée:

SELECT ISNULL(A.Price, B.Price) N_Price -- A.Product, A.Timestamp, A.Price, 
FROM Finance A 
OUTER APPLY ( SELECT TOP 1 * 
      FROM Finance 
      WHERE Product = A.Product AND Timestamp < A.Timestamp 
      AND Price IS NOT NULL 
      ORDER BY Product, Timestamp DESC) B 

Et je voudrais insérer la colonne N_Price retournée par requête dans la table Finance d'origine. Y at-il un moyen simple et rapide, comment faire cela?

+0

Au lieu d'insérer la colonne, je voudrais aller en vue – TheGameiswar

+0

C'est ce que je me demandais aussi, mais je dois insérer la colonne. – mateskabe

+0

Est-ce une insertion d'une fois? – TheGameiswar

Répondre

0

Cela devrait fonctionner pour une fois mise à jour

alter table finance add n_price numeric(16,1) 


update a 
set n_price=ISNULL(A.Price, B.Price) 
from finance a 
outer apply 
(
SELECT TOP 1 price 
      FROM Finance 
      WHERE Product = A.Product AND Timestamp < A.Timestamp 
      AND Price IS NOT NULL 
      ORDER BY Product, Timestamp DESC) B 
+0

Fonctionne très bien, merci beaucoup! – mateskabe