本帖最后由 zuxianchun 于 2010-08-07 15:59:51 编辑

解决方案 »

  1.   

    --> 测试数据:#
    if object_id('tempdb.dbo.#') is not null drop table #
    create table #(ID varchar(8), color varchar(14), stock varchar(8))
    insert into #
    select '001', '红色,绿色,蓝色', '12,34,56' union all
    select '002', '绿色,黄色', '32,12' union all
    select '003', '咖啡色', '13' union all
    select '004', '绿色,黄色', '32,19'if object_id('tempdb.dbo.#Nums') is not null drop table #Nums
    select top 8 n = identity(int,1,1) into #Nums from syscolumns --> top 待拆分列的最大字符个数select b.n, a.ID, color = substring(a.color+',', b.n, charindex(',',a.color+',',b.n+1) - b.n) into #1 from # a, #Nums b where substring(','+a.color, b.n, 1) = ','
    update t set n = (select count(1) from #1 where ID = t.ID and n <= t.n) from #1 as t
    select b.n, a.ID, stock = substring(a.stock+',', b.n, charindex(',',a.stock+',',b.n+1) - b.n) into #2 from # a, #Nums b where substring(','+a.stock, b.n, 1) = ','
    update t set n = (select count(1) from #2 where ID = t.ID and n <= t.n) from #2 as t
    select
    sum(convert(int,b.stock))总产品,
    sum(case a.color when '绿色' then convert(int,b.stock) end)绿色
    from #1 as a inner join #2 as b on a.n = b.n and a.ID = b.ID/*
    总产品         绿色
    ----------- -----------
    210         98
    */drop table #, #Nums, #1, #2
      

  2.   


    不建议这样设计数据库。产品表 颜色表 库存表产品表 :(产品ID,产品名称,产品类别....)
    颜色表:(颜色ID,颜色名称)
    库存表(产品ID,颜色ID,库存数量)
    1,001,100  --001代表红色,002代表蓝色。
    1,002,200
    2,002,200
    2,001,300
    ....若按以上设计,将对于你的库存统计等操作都比较便利
    你的设计处理些统计较麻烦