开发中的项目是具有以下订阅级别的业务目录: 白金,金,银,铜牌
我有3个表对此任务有疑问。我将把重要的列放在括号中。
BD_Listing(ListingID,LevelID,Active)
BD_ListingOwner(UserID,ListingID)
BD_Storefront(RecurringSubscriptionID,Quantity,VariantID,Status)
购买后,用户将进入可以开始创建商家信息的页面。该页面上有一个看起来像桌子的模块:
等级----------主动/剩余----------操作
Platinum ------ 1/0 ------------------------------购买附加许可证
黄金----------- 0/2 ------------------------------创造黄金清单
Silver ---------- 0/0 ------------------------------购买附加许可
青铜-------- 0/0 ------------------------------购买额外许可证
基本上,我需要了解执行以下操作的正确SQL查询:
我需要确保获得每种类型的总数量,记住约翰可以在一个订单中购买2个黄金,在BD_Storefront表中显示数量2,一个月后可以购买另一个黄金,创建另一行在数量为1的表中,总共给出了3个许可证。
这是我到目前为止提出的SQL:
SELECT
a.[RecurringSalesOrderID]
,a.[UserID]
,a.[PortalID]
,a.[ProductVariantID]
,a.[Quantity]
,a.[NextRecurringDate]
,a.[Status]
,a.[OriginalSalesOrderID]
,a.[CreateDate]
,a.[UpdateDate]
,b.[UserID]
,b.[ListingID] AS OwnerListingID
,c.[ListingID] AS ListingListingID
,c.[LevelID]
,(SELECT SUM(Quantity) FROM BD_Storefront WHERE (UserID = @passedUserID) AND (ProductVariantID = 1) AND (Status = 1)) AS ActiveBronze
,(SELECT SUM(Quantity) FROM BD_Storefront WHERE (UserID = @passedUserID) AND (ProductVariantID = 2) AND (Status = 1)) AS ActiveSilver
,(SELECT SUM(Quantity) FROM BD_Storefront WHERE (UserID = @passedUserID) AND (ProductVariantID = 3) AND (Status = 1)) AS ActiveGold
,(SELECT SUM(Quantity) FROM BD_Storefront WHERE (UserID = @passedUserID) AND (ProductVariantID = 4) AND (Status = 1)) AS ActivePlatinum
,(SELECT COUNT(ListingID) FROM BD_ListingOwner WHERE (UserID = @passedUserID)
FROM [BD_Storefront] a
JOIN [BD_ListingOwner] b
ON a.[UserID] = b.[UserID]
JOIN [BD_Listing] c
ON b.[ListingID] = c.[ListingID]
WHERE a.[UserID] = @passedUserID
AND Status = 1
正如您所看到的,我不太清楚如何分析BD_Listing表以了解特定用户已创建的每种类型的列表,并从上面的每个SUMS中减去该数量以获得剩余的允许值
如果有人能帮助我,那将是非常棒的。
非常感谢你。
答案 0 :(得分:0)
你的问题并不完全清楚,但这是你在寻找什么?
SELECT lsum.UserID
,lsum.LevelID
,SUM(ISNULL(sf.Quantity,0)) Active
,lsum.ListingTotal-SUM(ISNULL(sf.Quantity,0)) Remaining
FROM
(SELECT lo.UserID
,l.LevelID-3 LevelID
,COUNT(l.Active) ListingTotal
FROM [BD_Listing] l
INNER JOIN
[BD_ListingOwner] lo ON lo.[ListingID] = l.[ListingID]
WHERE l.Active=1
GROUP BY lo.UserID
,l.LevelID) lsum
LEFT JOIN
[BD_Storefront] sf ON sf.[UserID] = lsum.[UserID]
AND
sf.VariantID=lsum.LevelID
AND sf.Status = 1
GROUP BY lsum.UserID
,lsum.LevelID
,lsum.ListingTotal
请参阅此SqlFiddle