如果其他列中有重复的值,则更改并合并该列上的多个值

时间:2019-07-15 07:51:11

标签: sql sybase-asa

对不起,我是SQL的新手。我正在使用Sybase Central

我需要帮助,我现在像这样在select语句(存储过程)的数据表上卡住了:

select case when product like 'A%' then 'Product A' when product like 'B%' 
then 'Product B' else 'Product C' end as 
'ProductGroup',product,invoice,customer from data_sales
group by product,invoice,customer

结果:

+--------------+---------+---------+---------+
| ProductGroup | Product | Invoice | Customer|
+--------------+---------+---------+---------+
| Product A    |   A1    | INV001  |   MR.A  |
| Product A    |   A1    | INV002  |   MR.B  |
| Product B    |   B1    | INV002  |   MR.B  |
| Product B    |   B1    | INV003  |   MR.C  |
+--------------+---------+---------+---------+

如果发票上重复的值,我想合并并更改为产品组列中的产品C 中的值客户

结果应该是这样的:

+--------------+--------+---------+
| ProductGroup | Invoice| Customer|
+--------------+--------+---------+
| Product A    | INV001 |   MR.A  |
| Product C    | INV002 |   MR.B  |
| Product B    | INV003 |   MR.C  |
+--------------+--------+---------+

我一直在使用 case group by 方法,但是它仍然显示重复的结果

任何帮助将不胜感激

谢谢

3 个答案:

答案 0 :(得分:0)

您可以使用having count(*)>1的{​​{1}}子句检查重复项

group by

答案 1 :(得分:0)

以下查询不会检查发票或客户是否有通过分组依据重复的内容。分组发票将对重复的发票进行分组,如果发现重复,则总计计数大于1,否则在客户的情况或条件下为0。这就是你想要的吗?

  Update Table 
  Set Product="Product C" where
   Invoice In
   (Select  Invoice
   from table group by
    Invoice having 
    count(*)>1) or 
     Customers In (Select  Customers
   from table group by
    Customers having 
    count(*)>1)

答案 2 :(得分:0)

如果您只想查询一个返回所请求信息的查询(因此不进行更新):

select distinct CASE WHEN (select count() 
                             from Tab t2 
                            where t2.Customer = t1.Customer or t2.Invoice = t1.Invoice) > 1 
                     THEN 'Product C' 
                     ELSE ProductGroup 
                END "ProductGroup", Invoice, Customer
from Tab t1