如何计算列成员数据库表的算术表达式?

时间:2013-12-24 09:00:12

标签: sql database select sql-server-2012 aggregate

我有来自此查询的结果

SELECT
    myTable.Branch AS Branch,
    myTable.Quarter AS Quarter,
    SUM(myTable.Sales) AS Sales
FROM
    myTable
GROUP BY
    myTable.Branch,
    myTable.Quarter

Branch  Quarter Sales
B1      Q1      17
B1      Q2      7
B1      Q3      1
B1      Q4      8
B1      Q5      12
B2      Q1      8
B2      Q2      5
B2      Q3      2
B2      Q4      14
B2      Q5      17

现在我想得到计算成员让我们说Q1-Q3然后结果看起来像

Branch  Quarter     Sales
B1      Q1          17
B1      Q2          7
B1      Q3          1
B1      Q4          8
B1      Q5          12
B1      Q1-Q3       16
B2      Q1          8
B2      Q2          5
B2      Q3          2
B2      Q4          14
B2      Q5          17
B2      Q1-Q3       6

表达式可以是任何有效的算术表达式,如(Q1+Q2-Q3)*2

3 个答案:

答案 0 :(得分:1)

您可以创建一个表,其中Q1,Q2,Q3,Q4为每个分支的列:

http://sqlfiddle.com/#!6/eca51/14/0

SELECT
    Branch,
    SUM(CASE WHEN quarter='Q1' THEN sales END) AS Q1,
    SUM(CASE WHEN quarter='Q2' THEN sales END) AS Q2,
    SUM(CASE WHEN quarter='Q3' THEN sales END) AS Q3,
    SUM(CASE WHEN quarter='Q4' THEN sales END) AS Q4
FROM
    sales
GROUP BY Branch

这给出了:

| BRANCH | Q1 | Q2 | Q3 | Q4 |
|--------|----|----|----|----|
|     B1 | 17 |  7 |  1 |  8 |
|     B2 |  8 |  5 |  2 | 13 |

您可以将其用作子查询并执行您喜欢的任何算术。

SELECT Branch, Q1+2*Q2 AS Weighted,SQRT(Q1*Q2) GeometricMean
  FROM (
  SELECT
      Branch,
      SUM(CASE WHEN quarter='Q1' THEN sales END) AS Q1,
      SUM(CASE WHEN quarter='Q2' THEN sales END) AS Q2,
      SUM(CASE WHEN quarter='Q3' THEN sales END) AS Q3,
      SUM(CASE WHEN quarter='Q4' THEN sales END) AS Q4
  FROM
      sales
 GROUP BY Branch) AS BQ

这给出了:

| BRANCH | WEIGHTED |   GEOMETRICMEAN |
|--------|----------|-----------------|
|     B1 |       31 | 10.908712114636 |
|     B2 |       18 |  6.324555320337 |

这依赖于已知和修复的季度数量 - 我猜测有4个,但你​​似乎有5个。

答案 1 :(得分:0)

试试这个:

SELECT m.Branch, m.Quarter, m.Sales
FROM (SELECT m.Branch, m.Quarter, SUM(m.Sales) AS Sales
      FROM myTable m
      GROUP BY m.Branch, m.Quarter
      UNION 
      SELECT m.Branch, 'Q1+Q3' AS `Quarter`, SUM(m.Sales) AS Sales
      FROM myTable m 
      WHERE m.Quarter IN ('Q1', 'Q3')
      GROUP BY m.Branch
     ) AS m 
ORDER BY m.Branch, m.Quarter;

答案 2 :(得分:0)

试试这个, 首先通过CTE输出您的第一个查询

;使用cte(Branch,Quarter,Sales) 如 (选择     myTable.Branch AS Branch,     myTable.Quarter AS Quarter,     SUM(myTable.Sales)AS Sales 从     为myTable 通过...分组     myTable.Branch,     myTable.Quarter)

选择Branch,Quarter,Sales 来自CTE

联盟

选择Branch,'Q1-Q3'AS Quarter,'Q1 Sales -Q3 Sales'AS Sales 来自CTE