计算两列

时间:2015-09-15 12:09:45

标签: sql tsql calculated-columns

我有一个名为#table的表和三列。 SinGroup(没关系,可以是任何东西),Column1和Column2。

    CREATE TABLE #table(
     sinGroup  NVARCHAR(10)
     ,column1 INT
     ,column2 int 
     );

我有一些数据:

    INSERT INTO #table(sinGroup,column1,column2) VALUES
      ('y1',100,0),
      ('y2',0,60),
      ('y3',40,20),
      ('z1',150,0),
      ('z2',0,50),
      ('z3',0,50)

我想知道如何获得这个结果集(c1 - c2和Y和Z分组以及第1列下显示的结果):

       SinGroup    C1       C2

         y1        100      0
         y2          0     60
         y3         40     20

          Y         60      0

         z1        150      0
         z2          0     50
         z3          0     50

          Z         50      0

也是这样的结果(每行c1-c2和grop,结果显示在第1列下)

       SinGroup     C1      C2
          y1       100      0
          y1       100      0

          y2         0     60
          y2       -60      0

          y3        40     20
          y3        20      0

          z1       150      0
          z1       150      0

          z2         0     50
          z2       -50      0

          z3         0     50
          z3        -50     0

sqlFiddle

编辑: 我尝试过类似的东西,但我不想要4列,结果必须低于c1。

       select sinGroup, column1, column2, sum(column1) - sum(column2) as c
       from #table
       group by sinGroup,column1,column2

1 个答案:

答案 0 :(得分:1)

如果可能,请在前端级别格式化这些数据。 SQL不是为这类任务设计的语言。

查询1 SQL Fiddle

WITH summary AS (
  SELECT LEFT(sinGroup,1) AS sinGroup, SUM(C1) - SUM(c2) AS total 
  FROM t1
  GROUP BY LEFT(sinGroup,1)
)
SELECT sinGroup,c1,c2
FROM 
(  SELECT sinGroup,c1,c2, 0 as display_order
  FROM t1
  UNION ALL
  SELECT sinGroup
    ,CASE WHEN total > 0 THEN total ELSE 0 END AS C1
    ,CASE WHEN total < 0 THEN total ELSE 0 END AS C2
    ,1 AS display_order
  FROM summary
 ) t
 ORDER BY LEFT(sinGroup,1),display_order,sinGroup 

查询2 SQL Fiddle

SELECT sinGroup,c1,c2
FROM 
(  SELECT sinGroup,c1,c2, 0 as display_order
  FROM t1
  UNION ALL
  SELECT sinGroup, SUM(C1) - SUM(C2) AS c1, 0 AS C2, 1  as display_order
  FROM t1
  GROUP BY sinGroup
 ) t
 ORDER BY sinGroup,display_order