大家好我已经在我的SQL SERVER中创建了2个表,第一个表称为拍卖,第二个出价,每个拍卖都有一个状态,它们可以是有效的,过期的还是未售出的,当拍卖未售出时,它确实没有任何出价,但到期时拍卖应该有一个或出价,问题是我想选择每个有出价的拍卖并将其命名为成功,所有拍卖的状态未售出为不成功
这是我的代码
SELECT DATENAME(month, BID.Date) AS Years
,COUNT(DATENAME(Month, BID.Date)) AS Total
FROM Auction
INNER JOIN
BID ON Auction.AuctionID = BID.AuctionID
INNER JOIN
Item ON Auction.ItemID = Item.ItemID
WHERE (Auction.Status = 'Expired')
AND (BID.Status = 'Won')
GROUP BY DATENAME(month, BID.Date)
SELECT DATENAME(month, BID.Date) AS Years
, COUNT(DATENAME(Month, BID.Date)) AS Total
FROM Auction
INNER JOIN
BID ON Auction.AuctionID = BID.AuctionID
INNER JOIN
Item ON Auction.ItemID = Item.ItemID
WHERE (Auction.Status = 'UnSold')
GROUP BY DATENAME(month, BID.Date)
我想按日期对它们进行分组。
答案 0 :(得分:0)
我不是100%确定我完全理解你的要求。也许如果您发布了一些示例数据并模拟了结果集,您希望它更容易。
不过,我认为关键是您需要了解每次拍卖的“结果”(已售出/未售出)。这可以通过几种不同的方式完成,但这是一个相对简单的选项,可以帮助您入门
SELECT AuctionID
,ItemId
,CASE WHEN EXISTS(SELECT 1
FROM BID
WHERE BID.AuctionID=Auction.AuctionID)
THEN 'Won'
ELSE 'UnSold'
END Status
FROM Auction
编辑:
获得总数的一种方法是使用类似上面的东西作为CTE:
WITH AuctionResult AS (
SELECT CASE WHEN EXISTS(SELECT 1
FROM BID
WHERE BID.AuctionID=Auction.AuctionID)
THEN 'Won'
ELSE 'UnSold'
END [Status]
FROM Auction
) SELECT [Status]
,COUNT(*)
FROM AuctionResult
GROUP BY [Statush