简体   繁体   中英

SQL if there is no row, insert row

Preface: I have a query that pulls sales data and measures against their target. The issue is that only people who have sold an item appears on the chart for a given month. Eventually everyone gets a sale and gets on the chart. To alleviate this issue, I have created a 2nd statement that assigns a dummy row of data (used as a placeholder) and made the datepart(M, SOLD_DATE) = to datepart(M, getdate()) so that as of the 1st everyone is on the board.

My question: How can I set it to remove the placeholder as people get added to the board?

SELECT
    USER_ID,
    SOLD_DATE,
    DATEPART(M, SALE_ID)
    **Target Case Statement in a nutshell**:
    insert monthly target value to 1st instance of sold item
    else 0
    End as 'target_amt' -- this is summed and aggregated in excel chart.
FROM 
   Sales

UNION ALL

SELECT    
    USER_ID,
    DATEPART(M, getdate()) as SOLD_DATE,
    Sale_ID,
    TARGET_AMT,
FROM 
    Sales
WHERE
    Sale_ID = **this contains on made up sale_id per person as a place holder.

So you can see that as of the 1st of every month, The UNION statement adds an item for each person. Now how to remove it when someone makes a sale is the question.

I am thinking some sort of subquery with "not in" or "except". Or perhaps something involving a case statement???

I'd post the full query but it's a beast (8 pages) and uses a few CTE's to derive the top select statement.

You should select from your User table and left join against your sales table. By doing this, it solves the original problem that users aren't showing up when they haven't sold something.

I agree with SpectralGhost - the best way to solve this issue is to change the selection criteria for the original query so that it includes a join from both tables - people with no sales will show null entries.

However, if you want to do it the hard way, then a simple if exists should suffice for checking and removing dummy records when other sales records have been added. Or do you mean to say that within the statements for adding sales it should be checking, adding dummy records, or deleting dummy records if they already exist but a sale is being added? Seems like trying to push on a string to me.

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