简体   繁体   中英

SQL: Inserting rows into a table for multiple values at one

See file attached for more clarity and example.

I have a table that tracks the profit made, per fruit/variety/country for a company that sells fruits.

[Profit Table] has 4 columns ( Fruit, Country, F Variety, Profit). For a specific, Country and Variety, some records will have "none" as a Variety.

For each of the records that has a "none", I want to be able to insert a duplicate record for the profit value for each of the [Variety List] varieties and apply the "none" record to it, but ignore any variety that already has a profit associated with it for a specific Fruit and Country.

I am able to do an insert into but for one country at a time...Would appreciate to know how do we use a lookup on VarietyList table ( knowing that this can't be harcoded as there may be new varieties )

The image has an example of the input tables and desired outputs:

在此处输入图像描述

You can select records in table profitTable that have fruitVariety set to 'None' , then cross join with varietyList , and use not exists to evict combinations that already exist in the table.

insert into profitTable (fruit, country, fruitVariety, profit)
select pt.fruit, pt.country, vl.variety, pt.profit
from profitTable pt
cross join varietyList vl 
where
    pt.fruitVariety = 'None'
    and not exists (
        select 1 
        from profitTable pt1
        where 
            pt1.fruit = pt.fruit
            and pt1.country = pt.country 
            and pt1.fruitVariety = vl.variety
    )

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