如何在此查询中对材料和公司进行分组

时间:2017-05-05 09:12:15

标签: sql

我有一张这样的桌子:

Material   Company    vendor 
A               100           Coca       
B               100           N/A       
C               200           Samsung 
D               200          Samsung  

现在我想按材料,公司和供应商进行分组。如果公司的材料有超过1个供应商,那么它将显示“N / A”,如此

WITH CTE_Material AS (
       SELECT
             Material
             ,Company
             ,Vendor
             ,Saleperson
       FROM (VALUES
             ('A', '100','Coca','Peter')
             , ('A', '100','Coca','Rex')
             , ('B', '100','Coca','Vena')
             ,('B', '100','Pepsi','Weter')
             ,('C', '200','Samsung','Indi')
             ,('D', '200','Samsung','Thomax')
             ) AS Material( Material,Company,Vendor,Saleperson)
)

select * from CTE_Material

你能帮我解决一下吗?

由于

{{1}}

1 个答案:

答案 0 :(得分:2)

尝试:

select  Material,Company, case when count(distinct Vendor) > 1 then 'N/A' else max(Vendor) end as vendor
from CTE_Material
group by  Material,Company