简体   繁体   中英

Insert row into table where value not in column

I have a table with three columns: Day , Key , Value . If there is a value absent from the Key column, I want to be able to insert it:

DAY | KEY | VALUE
------------------
Mon   Run   50    
Mon   Bike  20
Tues  Run   25
Tues  Bike  60
Wed   Run   20
Wed   Swim  5

I want to be able to identify the row with the missing 'Bike' value from the column and insert it. So there would be an additional row

Wed Bike 20

How should I go about achieving this?

Can you please try this? It's the hard-coded approach:

INSERT INTO <yourtable> (day, key, value)
SELECT DISTINCT t1.day AS day, 'Bike' as key, 20 as value
FROM
    <yourtable> AS t1
    LEFT OUTER JOIN 
    (SELECT day, key FROM <yourtable> WHERE key='Bike') AS t2
    ON t1.day = t2.day
WHERE t2.key IS NULL;

Or if you can, please use stored procedures (which will allow you to choose the activity and value:

CREATE PROCEDURE dbo.InsertActivityWhereMissing 
      @activity VARCHAR(50)
    , @activityValue INT
AS
BEGIN
    INSERT INTO <yourtable> (day, key, value)
    SELECT t1.day AS day, @activity as key, @activityValue as value
    FROM
        (SELECT day FROM <yourtable> GROUP BY day) AS t1
        LEFT OUTER JOIN 
        (SELECT day, key FROM <yourtable> WHERE key = @activity) AS t2
        ON t1.day = t2.day
    WHERE t2.key IS NULL;
END

This way, you can perform the same action for any particular "activity" (I'm just naming it that way, but I'm referring to Run , Bike , Swim or anything else)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM