Figure 1 denotes the current state of the TABLE A and TABLE B.
The current implementation is to fetch the new MIds to Table B and copy the SqlQuery from base process, in case of a new market or an existing market. Below query is used for this:
SELECT A.MId, B1.Loop, B1.Segment, B1.SqlQuery, B1.UseDefault
FROM TableB B1 WITH (NOLOCK)
INNER JOIN TableA A WITH (NOLOCK) ON B1.MId IN (100, 200)
AND B1.MId = A.BaseMarket
AND ISNULL(A.POCId, 0) > 0
LEFT JOIN TableB B2 WITH (NOLOCK) ON A.MId = B2.MId
WHERE B2.MId IS NULL
Figure 2 shows the updated data in Table A and the desired state of Table B. The required implementation would be:
Here's the complete flow for Table A and B. The base configurations (100 and 200) in both tables were inserted manually initially including the loop and segments.
A new market is introduced and a new MId is created in Table A. Let's assume that to be 1001 and 1002 for Market ABC.
Corresponding records are inserted in Table B for each MId and it copies data from Base Configuration in Table B. Inserted Records (SqlId - 3 and 4)
SqlQuery column in Table B is updated manually due to a specific business request. (SqlId - 3 and 4). Hence, the different query.
Market ABC is updated in front end, which creates two new entries in Table A. (MId - 1003 and 1004). Also, new market XYZ (MId - 2001 and 2002) is created.
Corresponding entries created in Table B should refer Base Configuration for Market XYZ (SqlId - 7 and 8), since it's a new market but should copy the existing configuration for Market ABC (MId - 1001 and 1002) since it's configuration already existed.
I am looking for a suggestions if a single query can implement this requirement using Case statement. I'll appreciate your help!
I guess by market configuration already exists you actually mean the combination of MarketName
and Type
. So here's the query
SELECT
A.NewId, B.Loop, B.Segment, B.SqlQuery, B.UseDefault
FROM (
SELECT
A1.MId AS NewId, A2.MId AS RefId
FROM
TableA A1
INNER JOIN
TableA A2
ON
(A1.MarketName = A2.MarketName AND A1.Type = A2.Type) -- use your market configuration logic here
OR
A1.BaseMarket = A2.BaseMarket
WHERE
A1.Mid NOT IN (SELECT MId FROM TableB)
) As A
INNER JOIN
TableB B
ON (A.RefId = B.MID)
At first we are self-joining TableA
to get the reference MId as RefId
here. Then we are joining the new derived table with TableB
.
Hope this helps. Thank you!
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.