加入两个sql表并进行分组

时间:2014-10-21 21:42:43

标签: sql group-by

我的数据库中有两个表:

汽车: IdCar PK, 公司, 类型, 颜色

租赁: Id-rent_date PK, IdCar FK, Car_return_date

我需要编写一个返回三列的查询: - 年 - 特定公司的汽车在当年租用的天数 - 公司 - 来自汽车表

现在我有:

  

SELECT DATEDIFF(dd,Id-rent_date,Car_return_date)AS Days,Company   来自租赁INNER JOIN汽车租赁Renting.IdCar = Cars.IdCar

我尝试在查询结束时按公司进行分组,但它返回错误:

专栏'租赁.Id-rent_date'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

4 个答案:

答案 0 :(得分:1)

如果添加group by子句,则选择列表中的所有项目必须是您已分组的列或汇总计算。在这里,例如,您想要计算每家公司的天数:

SELECT     SUM(DATEDIFF(dd, Id-rent_date, Car_return_date)) AS Days, 
           Company 
FROM       Renting 
INNER JOIN Cars ON Renting.IdCar = Cars.IdCar
GROUP BY   Company

答案 1 :(得分:1)

这并不容易,因为您必须考虑Id-rent_date与Car_return_date不同的年份。 如果你假设YEAR([Id-rent_date])= YEAR(Car_return_date)是

SELECT    YEAR([Id-rent_date]), SUM(DATEDIFF(dd, [Id-rent_date], Car_return_date)) AS Days, 
           Company 
FROM       Renting 
INNER JOIN Cars ON Renting.IdCar = Cars.IdCar
GROUP BY   Company, YEAR([Id-rent_date])

答案 2 :(得分:0)

您需要将列名id-rent_date更改为id_rent_date,因为 - 是保留字符然后:

SELECT  DATEDIFF(dd, Id_rent_date, Car_return_date) 
AS Days, 
DATEPART(yy, Car_return_date) 
AS year, Company 
FROM  Renting 
INNER JOIN Cars 
ON Renting.IdCar = Cars.IdCar
GROUP BY Company

答案 3 :(得分:0)

完整查询:

 declare @iter int
        declare @max int
        declare @test Table ([Id-rent_date] datetime, Car_return_date datetime, IdCar int)
        set @iter = 0
        select @max = max(year(Car_return_date) - year([Id-rent_date]))  FROM Renting

              WHILE(@iter < @max)
              BEGIN
          insert into @test 
                  SELECT 
            DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + @iter, 0)
           ,DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + 1 + @iter, -1)
           ,IdCar
          FROM Renting
          where year([Id-rent_date]) + @iter <> year(Car_return_date) and year([Id-rent_date]) <> year(Car_return_date)
          set @iter = @iter + 1
              END
SELECT    YEAR([Id-rent_date]), SUM(DATEDIFF(dd, [Id-rent_date], Car_return_date)) AS Days, 
           Company 
FROM 

                  (SELECT 
            [Id-rent_date]
           ,[Car_return_date]
           ,IdCar
          FROM Renting
          where year([Id-rent_date]) = year(Car_return_date)
          union all
              SELECT 
            [Id-rent_date]
           ,DATEADD(yy, DATEDIFF(yy,0,[Id-rent_date]) + 1, -1)
           ,IdCar
          FROM Renting
          where year([Id-rent_date]) <> year(Car_return_date)
          UNION ALL
          SELECT 
            DATEADD(yy, DATEDIFF(yy,0,[Car_return_date]), 0)
           ,[Car_return_date]
           ,IdCar
          FROM Renting
          where year([Id-rent_date]) <> year(Car_return_date)
              UNION ALL
        select * from @test) RentingSplit inner join Cars ON RentingSplit.IdCar = Cars.IdCar
GROUP BY   Company, YEAR([Id-rent_date])