[英]Insert row into table where value not in column
I have a table with three columns: Day
, Key
, Value
. 我有一个包含三列的表:
Day
, Key
, Value
。 If there is a value absent from the Key
column, I want to be able to insert it: 如果“
Key
列中没有值,我希望能够插入它:
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) 这样,您可以对任何特定的
"activity"
执行相同的操作(我只是以这种方式命名,但我指的是Run
, Bike
, Swim
或其他任何东西)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.