简体   繁体   English

SQL query INSERT SELECT COUNT 从一个表逐行到另一个表

[英]SQL query INSERT SELECT COUNT from one table to another row by row

I have trouble finding the correct SQL Query.我无法找到正确的 SQL 查询。 As you can see in the picture, I have two Tables ('Table_1' with column 'VEHICULES') and ('Table_2' with column 'IMMATRICULATION' and 'NOMBRE').正如您在图片中看到的,我有两个表(“Table_1”和“VEHICULES”列)和(“Table_2”和“IMMATRICULATION”和“NOMBRE”列)。 In the Table_2 I want to insert in the column ('Nombre') the counted values from the Table_1 of VEHICULE (CarA, CarB and CarC) in the same row of these values as in the picture.在 Table_2 中,我想在列('Nombre')中插入来自 Table_1 的 VEHICULE(CarA,CarB 和 CarC)的计数值,这些值与图片中的这些值在同一行中。

I tried the below query but it is added a value instead of placing it in the same row of CarA, CarB....我尝试了下面的查询,但它被添加了一个值,而不是将它放在 CarA、CarB 的同一行中......

INSERT INTO Table_2 (NOMBRE)
    VALUES ((SELECT COUNT(*) FROM Table_1 WHERE VEHICULES = 'CarA'),
            (SELECT COUNT(*) FROM Table_1 WHERE VEHICULES = 'CarB'),
            (SELECT COUNT(*) FROM Table_1 WHERE VEHICULES = 'CarC')
           );

带有表格和所需结果的图片

First generate the select query that returns the values you want inserted into the new table, then add INSERT INTO in the beginning.首先生成 select 查询,返回要插入到新表中的值,然后在开头添加 INSERT INTO。 The group by clause is also what you're missing. group by 子句也是您所缺少的。

Here is an example这是一个例子

INSERT INTO Table_2 (Name, Cnt)
select VEHICULES, count(*)
from Table_1
group by VEHICULES

You seem to want update , not insert :你似乎想要update ,而不是insert

update table_2 t2 join
       (select vehicules, count(*) as cnt
        from table_1
        group by vehicules
       ) t1
       on t2.immatriculation = t1.vehicules
    set nombre = t1.cnt;

You need update obviously, rather than insert , and if you're using MSSQL Server ( which's suggested by the error text you got ), then use such a statement:您显然需要update ,而不是insert ,如果您使用的是MSSQL Server这是您收到的错误文本所建议的),则使用这样的语句:

WITH t AS
(
 SELECT vehicules, COUNT(*) AS cnt
   FROM table_1
  GROUP BY vehicules 
)
UPDATE table_2
   SET nombre = cnt
  FROM t
 WHERE immatriculation = vehicules

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM