Question

Really difficult problem at the moment, as this is something that I am trying to do in SQL but I know should be done with another language such as PHP.

Essentially what I have is a database which has order numbers, and product codes related to policies.

For some orders there are multiple phases such as a cancellation, and an upgrade (for example when an upgrade is made the original policy is cancelled and then an upgrade is made for the difference)

What I want to do, is run a query that will exclude all cancellations related to an upgrade order (dictated as UP in product code) but keep all cancellations related to a change of detail (dictated as CD in product code).

So in short; The query will need to find all orders including cancellations, but then delete any cancellation which has the same order number as a UP.

I know that this essentially could be done with a 'foreach' which finds all UP product codes, and the related order number, and then deletes all cancellations associated with that order number - but I don't know how to achieve this in SQL without creating multiple tables on a temporary basis and deleting them after.

Table Structure is as such:

| Order Number | Product Code | Transaction Value |
|    1         |    RRCN      |    -30            |
|    1         |    RRUP      |     12            |
|    2         |    SMFP      |     30            |
|    3         |    SMCN      |    -12            |
|    3         |    SMCD      |     12            |
|    4         |    HUCN      |    -30            |

So I would need the query to show all the table, but remove the RRCN related to the RRUP. So query should look for RRUP, see it is order 1, then find the RRCN related to order 1 and remove this from the results - please note, results NOT the original table.

Any ideas? Much appreciated! (I am running SQL Server 2008)

Was it helpful?

Solution

This query should do the job:

SELECT * FROM Q19427600
WHERE RIGHT(ProductCode,2) <> 'CN'
OR (RIGHT(ProductCode,2) = 'CN' AND 
    OrderNumber NOT IN (SELECT OrderNumber FROM Q19427600 WHERE RIGHT(ProductCode,2) = 'UP'));

Returns results:

OrderNumber ProductCode TransactionValue
1           RRUP        12
2           SMFP        30
3           SMCN        -12
3           SMCD        12
4           HUCN        -30
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top