donc j'ai ce genre de table:
Ce que vous pouvez voir est que j'ai un numéro de mois manquant qui est 1. Ce que je veux est d'insert une valeur qui est comme ceci à ma table:
Month Year Col1 Forecast Customer 1 2015 HD/FB/BK/ 0 AFC
comme c'était un mois manquant, je veux que la prévision soit de 0 valeur.
Et mes parameters pour une telle insertion seraient par année, col1 et client.
Tout d'abord, générez des lignes de toutes les combinaisons mois-année en fonction de vos parameters. Utilisez ensuite NOT EXISTS
pour insert des lignes manquantes:
DECLARE @yr INT, @col1 VARCHAR(50), @customer VARCHAR(50); WITH Cte(mnt, yr, col1, customer) AS( SELECT *, @yr, @col1, @customer FROM(VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12) )t(N) ) INSERT INTO tbl(Month, Year, Col1, Forecast, Customer) SELECT mnt, yr, col1, 0, customer FROM Cte c WHERE NOT EXISTS( SELECT 1 FROM tbl WHERE Col1 = c.col1 AND Customer = c.customer AND Month = c.mnt AND Year = c.yr )
L'approche ici est de générer des combinaisons de month
et de col1
et de faire correspondre avec la table actuelle et de générer l'insertion pour les lignes manquantes. Vous pouvez prolonger ceci avec d'autres combinaisons requirejses de customer
et d' year
. Cela fonctionne bien s'il n'y a pas d'input unique pour une combinaison particulière.
SELECT * FROM (SELECT 1 month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months JOIN (SELECT 'HD/FB/BK' colname UNION ALL SELECT 'HD/FB/BL') col1
select expected.* from data_table dt right join (SELECT * FROM (SELECT 1 month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months JOIN (SELECT 'HD/FB/BK' colname UNION ALL SELECT 'HD/FB/BL') col1) expected on (dt.month = expected.month and dt.Col1 = expected.colname) where dt.col1 is null
insert into data_table select datainsert.month, 2015, datainsert.colname, 0.0, 'AFC' FROM (select expected.* from data_table dt right join (SELECT * FROM (SELECT 1 month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12) months JOIN (SELECT 'HD/FB/BK' colname UNION ALL SELECT 'HD/FB/BL') col1) expected on (dt.month = expected.month and dt.Col1 = expected.colname) where dt.col1 is null) datainsert;