简体   繁体   中英

SQL Query to insert into a particular column from output of select query

I have a query as shown below:

select department as departmentname,count(distinct(uid)) as userscnt 
from outlier_report where department is not null group by department ;

I want to insert this into outlier_output table which is already populated and has about 20 fields including departmentname and user_count (this field is empty). I want to put the userscnt field from the output of the select into the outlier_output table where the department=outlier_report.departmentment_name

I am assuming it would be something like this:

Insert into outlier_output(user_count Select department, count(distinct(uid) as userscnt from outlier_report where the department=outlier_report.departmentment_name)

How would the exact query be? Thanks in advance

Standard insert-select format is:

INSERT INTO `tableA` ([field_list])
SELECT [results corresponding to items in the field list in the same order as the field list]
[etc...]

http://dev.mysql.com/doc/refman/5.6/en/insert.html

This is how the query syntax works:

insert into outlier_output(departmentname, usercount) 
    select department as departmentname,count(distinct(uid)) as userscnt 
    from outlier_report 
    where department is not null group by department ;

I see Particular column and where the department = outlier_report.department_name .
So I think, You want to UPDATE instead of INSERT.

Please try this :

update outlier_output a
inner join (
    select department as departmentname,
    count(distinct(uid)) as userscnt 
    from outlier_report 
    where department is not null 
    group by department 
) b on a.department = b.departmentname
set a.user_count = b.userscnt 

And this is for INSERT

insert into outlier_output  (department,user_count)
select department as departmentname,
count(distinct(uid)) as userscnt 
from outlier_report 
where department is not null 
group by department 

You don't need INSERT as you have already populated them. You just need to update the user_count column in your table.

UPDATE outlier_output a set 
    a.user_count=(select count(distinct(b.uid)) 
                         from outlier_report b 
                  where b.department=a.departmentname );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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