在SQL中将一行数据分配给两行

时间:2016-10-28 18:55:29

标签: sql sql-server-2008

我有下表。是否有一种很好的方法可以重新组合它们,以便小组' a + b' 重复计算并添加到群组' a'和' b'

#include <iostream>

size_t const SIZE { 2 };

void Alloc2D(double ***x, size_t row, size_t col);
void Alloc2D(double ***x, size_t row, size_t col)
{ 
    *x = new double*[row];
    for(size_t i {}; i < row; i++)
    {
        (*x)[i] = new double[col];
    }
}

int main()
{
    double** matrix;

    // 2 x 2 matrix
    Alloc2D(&matrix, SIZE, SIZE);
    matrix[0][0] = 9;
    matrix[0][1] = 8;
    matrix[1][0] = 7;
    matrix[1][1] = 6;


    for(size_t i {}; i < SIZE; i++)
        delete matrix[i];
    delete[] matrix;
}

结果将是:

Group Amount
  a     100
  b     200
  c     300
 a+b    400

1 个答案:

答案 0 :(得分:2)

这很可怕,但你可以为匹配的组做一个子查询。

SELECT GroupId,
Amount + ISNULL(
  (SELECT SUM(Amount) FROM MyGroups t2
   WHERE t2.GroupId <> t1.GroupId
   AND t2.GroupId LIKE '%' + t1.GroupId + '%'), 0)
FROM MyGroups t1
WHERE t1.GroupId NOT LIKE '%+%'

http://sqlfiddle.com/#!3/50214/8