我目前正在努力解决以下问题。我在数据库中有一张表,其中包含公司列表和他们拥有的一些产品。我希望计算他们拥有的唯一产品的数量,并将其插入到公司名称所在的表格行中。
我尝试了以下内容:
val actor = system.actorOf(Props[SampleActor], "sampleActor")
actor ! "Pretty slick"
这是一张桌子。期望的输出是:
INSERT INTO table name
SET number of products =
(SELECT COUNT(DISTINCT productName) FROM table name
GROUP BY company name
答案 0 :(得分:2)
我想你想要更新:
Authentication
此查询将使用该公司的不同产品数更新表中的所有行。
答案 1 :(得分:0)
假设你的桌子是这样的
company_name | product_name | number_of_products
----------------------------------------------------
foo | wand | null
foo | wand | null
bar | plug | null
bar | stick | null
bar | broom | null
然后
;WITH CTE AS
(
select company_name, COUNT(DISTINCT product_name) as number_of_products
from table_name
group by company_name
)
update t SET
number_of_products = cte.number_of_products
from table_name t
inner join CTE
on t.company_name = cte.company_name
会给你
company_name | product_name | number_of_products
----------------------------------------------------
foo | wand | 1
foo | wand | 1
bar | plug | 3
bar | stick | 3
bar | broom | 3
如果您要从计数中排除产品列表,请将CTE更改为
select company_name, COUNT(DISTINCT product_name) as number_of_products
from table_name
where product_name not in ('stick')
group by company_name
虽然取决于您有多少排除项目,但您可能希望执行类似
的操作declare @exclusions table
(
product_name varchar(10) not null
)
insert into @exclusions (product_name) VALUES ('stick')
....
select company_name, COUNT(DISTINCT product_name) as number_of_products
from table_name
where product_name not in (select product_name from @exclusions)
group by company_name
会给你
company_name | product_name | number_of_products
----------------------------------------------------
foo | wand | 1
foo | wand | 1
bar | plug | 2
bar | stick | 2
bar | broom | 2