2014-02-27 110 views
0

大家好我已經在我的SQL SERVER中創建了2個表格,第一個表格叫做拍賣,第二個出價,每個拍賣都有一個狀態,它們可以是有效的,過期的或未售出的,當拍賣時沒有任何出價,但沒有任何出價,但過期時拍賣應該有一個或出價,問題是,我想選擇每個有出價的拍賣,並將其命名爲成功,並且所有拍賣的狀態未售出爲不成功Select Statement for 2 Tables

這裏是我的代碼

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

我不是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 
+0

你並不遙遠,但如果我想有總韓元和總的未售出怎麼會請> – user3287068

+0

就項目的數量銷往VS項目沒有賣?你所要做的就是重新查詢結果集的狀態分組。有多種方式。 –