如何使用null进行SQL自连接

时间:2012-04-25 16:25:02

标签: sql tsql

我使用的是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')

2 个答案:

答案 0 :(得分:4)

而不是JOIN,我认为PIVOT更合适:

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

答案 1 :(得分: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