簡體   English   中英

SQL從另一列插入不同值

[英]SQL Insert Count of Distinct Values from another column

我目前正在嘗試以下查詢。 我在數據庫中的一個表格中列出了公司列表以及他們擁有的許多產品。 我希望統計他們擁有的獨特產品的數量,並將其插入公司名稱所在表格的行中。

我嘗試了以下方法:

INSERT INTO table name
SET number of products =
(SELECT COUNT(DISTINCT productName) FROM table name
GROUP BY company name

這是一張桌子。 所需的輸出是:

CompanyName | Product | NumberOfProducts
Company A.    A.        3
Company A.    B.        3
Company A.    C.        3

我認為您想要更新:

UPDATE t
    SET numberofproducts = (SELECT COUNT(DISTINCT productname)
                            FROM tablename t2
                            WHERE t2.companyname = t.companyname
                           )
    FROM tablename t;

此查詢將使用該公司的不同產品數更新表中的所有行。

假設你的桌子是這樣的

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

測試: http//rextester.com/XWMYK90685

如果您要從計數中排除產品列表,則將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

測試排除情況: http//rextester.com/AYPGFQ42106

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM