2015-01-13 190 views
0

這裏是我的查詢:ms sql查詢幫助。子查詢返回的多個值

SELECT   
     Bills.BillDate, 
     Client.ClientName, 
     (SELECT bills.NetAmount 
      FROM Bills 
      Where Bills.BillDate Between DATEADD(day, -30, GETDATE()) AND GETDATE()) as '30 days' 
FROM Client INNER JOIN 
     Vessel ON Client.ClientID = Vessel.ClientID INNER JOIN 
     Bills ON Vessel.VesselID = Bills.VesselID 
     GROUP BY Bills.BillDate, Client.ClientName 
+0

你的第三列'30 days'返回多個結果。 –

+0

警告:像這樣使用GETDATE()會阻止您使用任何索引。我建議在選擇和使用它之前在變量中計算日期。 –

+0

我想選擇[BillDate]在今天減去30天的[clientname]的所有[netamount]。謝謝 – Cored

回答

0

使用此:

SELECT 
    Bills.BillDate, 
    Client.ClientName, 
    (
     SELECT TOP 1 bills.NetAmount 
     FROM Bills 
     WHERE 
      Bills.BillDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE() 
    ) AS '30 days' 
FROM Client 
INNER JOIN Vessel 
    ON Client.ClientID = Vessel.ClientID 
INNER JOIN Bills 
    ON Vessel.VesselID = Bills.VesselID 
GROUP BY 
    Bills.BillDate, Client.ClientName 

TOP 1從內部查詢只得到結果。

0

調整,總結了bills.NetAmount爲最近30天:

SELECT   
     Bills.BillDate, 
     Client.ClientName, 
     SUM(bills.NetAmount) as '30 days' 
FROM Client INNER JOIN 
     Vessel ON Client.ClientID = Vessel.ClientID INNER JOIN 
     Bills ON Vessel.VesselID = Bills.VesselID 
WHERE Bills.BillDate BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE() 
GROUP BY Bills.BillDate, Client.ClientName