To generate the 2 required rows, you can use a GROUP BY
query
SELECT t.YYYYMM, STATUS = 'AVAILABLE', t.BOOKNAME,
SUM (CASE WHEN t.STATUS = 'TOTAL' THEN +t.QUANTITY ELSE -t.QUANTITY END) AS QUANTITY
FROM a_table t
GROUP BY t.YYYYMM, t.BOOKNAME
You can insert that back into the table
Or
can use UNION ALL
in a SELECT
query when you need to display it
INSERT INTO table (yyyymm, status, bookname, quantity)
SELECT t1.yyyymm, 'AVAILABLE', t1.bookname, t1.quantity - t2.quantity
FROM table t1
JOIN table t2 USING (yyyymm, bookname)
WHERE t1.status = 'TOTAL'
AND t2.status = 'RENTED OUT'
table (yyyymm, status, bookname)
must be unique by proper constraint/index.
The record will be inserted only when both source records are present. If it is possible that 'RENTED OUT' is absent and its value must be assumed as zero, use LEFT JOIN ans COALESCE additionally (and move the condition by t2.status to ON clause).
Can you please be kind enough to edit your answer to include the assumption when 'RENTED OUT' is absent?
INSERT INTO table (yyyymm, status, bookname, quantity)
SELECT t1.yyyymm, 'AVAILABLE', t1.bookname, t1.quantity - COALESCE(t2.quantity, 0)
FROM table t1
LEFT JOIN table t2 ON t1.yyyymm = t2.yyyymm
AND t1.bookname = t2.bookname
AND t2.status = 'RENTED OUT'
WHERE t1.status = 'TOTAL'
This query will definitely works for you please see screen shot below Thank you
create table #temp (YYYYMM varchar(10),Status varchar(20),BOOKNAME
varchar(20),QUANTITY INT)
INSERT INTO #temp VALUES ('201912','TOTAL','PHYSICS101',260)
INSERT INTO #temp VALUES ('201912','RENTED OUT','PHYSICS101',100)
INSERT INTO #temp VALUES ('201912','TOTAL','CHEMISTRY101',250)
INSERT INTO #temp VALUES ('201912','RENTED OUT','CHEMISTRY101',50)
;WITH CTE AS (
SELECT YYYYMM,Status,BOOKNAME,QUANTITY,
CASE WHEN BOOKNAME IN('CHEMISTRY101','PHYSICS101') AND STATUS='TOTAL' THEN QUANTITY
END TOTAL
,CASE WHEN BOOKNAME IN('CHEMISTRY101','PHYSICS101') AND STATUS='RENTED OUT' THEN
QUANTITY END RENTED_OUT
FROM #temp
)
SELECT YYYYMM,Status,BOOKNAME,QUANTITY FROM #temp
UNION ALL
SELECT YYYYMM,'AVAILABLE' Status,BOOKNAME,SUM(ISNULL(TOTAL,0)-ISNULL(RENTED_OUT,0))
QUANTITY FROM CTE
GROUP BY YYYYMM,BOOKNAME
DROP TABLE #temp
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.