ms sql查询帮助。子查询返回的值超过1

时间:2015-01-13 08:12:47

标签: sql sql-server

这是我的问题:

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

2 个答案:

答案 0 :(得分: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 只会从内部查询获得 1 结果。

答案 1 :(得分:0)

调整为过去30天的账单.NetAmount:

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