SQL设置列到行计数

时间:2014-06-11 18:52:33

标签: sql sql-server

我正在使用SQL Server数据库,并且有两个包含以下列的表:

Driver: DriverID, NumCars

Cars: CarID, DriverID

NumCars为空,但我需要它是Cars中包含该特定DriverID的行数。我该怎么做?

7 个答案:

答案 0 :(得分:1)

尝试:

SELECT count(carID) as CountOfCars from Cars where DriverID = [DriverID]

将根据输入的DriverID给您计数 或

SELECT DriverId, count(carID) as CountOfCars from Cars group by DriverID 

将为您提供carID的所有计数并按DriverID对其进行分组

如果您需要根据Driver表中的数据计算:

SELECT count(carID) as CountOfCars from Cars inner join on Driver.DriverID = Cars.DriverID group by Cars.DriverID 

答案 1 :(得分:1)

UPDATE D
  SET D.NumCars = C.NumCars
FROM Driver D INNER JOIN (SELECT DriverID, COUNT(*) AS NumCars
                          FROM Cars
                          GROUP BY DriverID) C
ON D.DriverID = C.DriverID 

答案 2 :(得分:0)

您可以使用以下Cars查询获取属于驱动程序的Driver计数以及所有SELECT数据:

SELECT *
    ,(
        SELECT COUNT(*)
        FROM Cars c
        WHERE c.DriverID = d.DriverID
        )
FROM Driver d

您可以使用以下声明UPDATE NumCars列:

UPDATE Driver
SET NumCars = (
    SELECT COUNT(*)
    FROM Cars
    WHERE Driver.DriverID = Cars.DriverID
    )

答案 3 :(得分:0)

这会将NumCars表格中Driver列的所有条目设置为与该驱动程序关联的汽车数量:

UPDATE Driver SET NumCars = (SELECT COUNT(*) FROM Cars WHERE Driver.DriverID = Cars.DriverID);

答案 4 :(得分:0)

我会做一个子查询,然后将其加入到你想要更新的表中。

UPDATE  d
SET     NumCars = [NumCars]
FROM    Driver AS d
        INNER JOIN (SELECT  d.DriverID, COUNT(c.CarID) AS NumCars
                FROM    Drivers AS d
                        INNER JOIN Cars AS c ON c.DriverID = d.DriverID
                GROUP BY d.DriverID 
                ) AS Sub ON sub.DriverID = a.DriverID

答案 5 :(得分:0)

如果您希望列的更新是动态的,请在第二个表和该触发器内创建一个插入/更新后触发器,您可以使用上面提到的任何一个更新第一个表的列方法

答案 6 :(得分:0)

尝试此查询。它有效。

update Driver
set Driver.Numcars = src.cnt
from
(
select c.DriverId, count(c.CarId) as cnt
from Cars as c
inner join Driver as d
on c.DriverId = d.DriverId
group by c.DriverId
) as src
where Driver.DriverId = src.DriverId