3

我正在使用 MS SQL 2008。我的表如下所示:

| Name  | Code | Amt  |
| ----- | ---- | ---- |
| April |  A   | 1.23 |
| Barry |  A   | 2.34 |
| Barry |  B   | 3.45 |
| Cliff |  A   | 4.56 |
| Cliff |  B   | 5.67 |
| Cliff |  C   | 6.78 |

我需要输出是这样的:

| Name  | Code_A | Code_B | Code_C |
| ----- | ------ | ------ | ------ |
| April |  1.23  |  NULL  |  NULL  |  
| Barry |  2.34  |  3.45  |  NULL  |
| Cliff |  4.56  |  5.67  |  6.78  |

NULL 可以为零。

通过自我加入,我可以获得 Cliff,但无法获得 Barry 和 April,因为我正在使用类似这样的东西,只有在所有三个条件都可用的情况下才会输出。

SELECT     a.Name, a.Amt Code_A, b.Amt Code_B, c.Amt Code_C
FROM       Table_1 as c INNER JOIN
                  Table_1 AS b ON c.Name = b.Name INNER JOIN
                  Table_1 AS a ON b.Name = a.Name 
WHERE     (a.Code = 'A') AND (b.Code = 'B') AND (c.Code = 'C')
4

2 回答 2

4

而不是JOINs,我认为aPIVOT在这里更合适:

SELECT 
    Name, 
    [A] AS Code_A, 
    [B] AS Code_B, 
    [C] AS Code_C
FROM (
    SELECT Name, Code, Amount
    FROM Table_1
) t
PIVOT (
    SUM(Amount)
    FOR Code IN ([A], [B], [C])
) AS pvt
于 2012-04-25T16:34:33.467 回答
2

一个完全与 sql 引擎无关的方法是:

select names.Name, 
   (select sum(a2.Amt) from amounts a2
    where a2.Name = names.Name
       and a2.Code = 'A') as AmtA,
   (select sum(a3.Amt) from amounts a3
    where a3.Name = names.Name
       and a3.Code = 'B') as AmtB,
   (select sum(a4.Amt) from amounts a4
    where a4.Name = names.Name
       and Code = 'C') as AmtC
from (select distinct Name from amounts) as names

在哪里选择唯一的名称集,然后汇总每个特定代码的数量。这更多是为了说明 SQL 的工作原理。

在实践中,我实际上不会在您的情况下使用它——PIVOT对于任何支持它的引擎来说,它的效率都会更高。如图所示: http ://sqlfiddle.com/#!3/7cb0a/5

于 2012-04-25T16:40:03.670 回答