多个SQL SELECT语句的聚合

时间:2018-03-07 16:00:17

标签: sql sql-server

我有一张这样的表TABLE1

|--------------|--------------|--------------|
|      POS     |     TYPE     |    VOLUME    |
|--------------|--------------|--------------|
|       1      |      A       |     34       |
|       2      |      A       |     2        |
|       1      |      A       |     12       |
|       3      |      B       |     200      |
|       4      |      C       |     1        |
|--------------|--------------|--------------|

我希望得到这样的结果(TABLE2):

|--------------|--------------|--------------|--------------|--------------|
|      POS     |   Amount_A   |   Amount_B   |   Amount_C   |  Sum_Volume  |
|--------------|--------------|--------------|--------------|--------------|
|       1      |      2       |      0       |       0      |     46       |
|       2      |      1       |      0       |       0      |     2        |
|       3      |      0       |      1       |       0      |     200      |
|       4      |      0       |      0       |       1      |     1        |
|--------------|--------------|--------------|--------------|--------------|

到目前为止我的代码是:

SELECT
    (SELECT COUNT(TYPE)
    FROM TABLE1
    WHERE TYPE = 'A') AS [Amount_A]
    ,(SELECT COUNT(TYPE)
    FROM TABLE1
    WHERE TYPE = 'B') AS [Amount_B]
    ,(SELECT COUNT(TYPE)
    FROM TABLE1
    WHERE TYPE = 'C') AS [Amount_C]
    ,(SELECT SUM(VOLUME)
    FROM TABLE AS [Sum_Volume]
INTO [TABLE2]

现在有两个问题:

  1. 如何包含有关POS
  2. 的区别
  3. 有没有更好的方法来计算每个TYPE
  4. 我正在使用MSSQLServer。

2 个答案:

答案 0 :(得分:4)

您正在寻找的是使用GROUP BY以及您的聚合函数。因此,这导致:

USE Sandbox;
GO

CREATE TABLE Table1 (Pos tinyint, [Type] char(1), Volume smallint);
INSERT INTO Table1
VALUES (1,'A',34 ),
       (2,'A',2  ),
       (1,'A',12 ),
       (3,'B',200),
       (4,'C',1  );

GO

SELECT Pos,
       COUNT(CASE WHEN [Type] = 'A' THEN [Type] END) AS Amount_A,
       COUNT(CASE WHEN [Type] = 'B' THEN [Type] END) AS Amount_B,
       COUNT(CASE WHEN [Type] = 'C' THEN [Type] END) AS Amount_C,
       SUM(Volume) As Sum_Volume
FROM Table1 T1
GROUP BY Pos;

DROP TABLE Table1;
GO

如果您有[Type]的变量和未定义的值数,那么您很可能需要使用动态SQL。

答案 1 :(得分:0)

你的第一栏应该是POS,你就是GROUP BY POS。

这将为每个POS值提供一行,并相应地聚合(COUNT和SUM)。

您也可以使用CASE语句而不是子选择。例如,而不是:

 (SELECT COUNT(TYPE)
     FROM TABLE1
     WHERE TYPE = 'A') AS [Amount_A]

使用:

 COUNT(CASE WHEN TYPE = 'A' then 1 else NULL END) AS [Amount_A]