하나의 매개변수 @DeductionCount 를 받아서
2개의 로우(무료,유료)를 차감하는 로직인데 좀더 나이스한 방법 없을까요??
테이블구조
USER_ID
ITEM_ID
ITEM_COUNT
(PK USER_ID,ITEM_ID)
USER_ID ITEM_ID ITEM_COUNT
123 1 200
123 11 300
DECLARE @DeductionCount bigint= 400
@USER_ID bigint = 123
SELECT ITEM_ID
,ITEM_COUNT
,CASE WHEN ITEM_ID = 1 THEN IIF(@DecreaseValue <= (LEAD(ITEM_COUNT,1,0) OVER(ORDER BY ITEM_ID) ),0, @DecreaseValue-(LEAD(ITEM_COUNT,1,0) OVER(ORDER BY ITEM_ID)))
WHEN ITEM_ID = 11 THEN IIF(@DecreaseValue <= ITEM_COUNT ,@DecreaseValue ,ITEM_COUNT)
ELSE 0
END AS CunsumeITEM_COUNT
FROM (
SELECT ITEM_ID
,ITEM_COUNT
,IIF(ITEM_ID=1,ITEM_COUNT,0) AS FreeRuby
,IIF(ITEM_ID=11,ITEM_COUNT,0) AS PayRuby
FROM dbo.PlayerITEM WITH(NOLOCK)
WHERE USER_ID = @USER_ID
AND ITEM_ID IN (1, 11)
) AS A
ORDER BY ITEM_ID ASC
|