基于特定行条件的列中的值的透视和总和

时间:2018-05-09 14:06:47

标签: sql sql-server

我有一个这样的样本表:

DaysInOp  Zone_id   DailyAvg                RunNumber
    0       9       5996.79891226986        1
    0       15      0                       1
    0       3       12549.5152623033        1
    0       12      -8400.75508952542       1
    0       6       24766.7738319152        1
    0       7       11737.3698582701        1
    0       1       26395.0374347879        1
    0       18      0.0218623184855433      1
    0       10      1965.53524850589        1
    0       4       9499.54051554152        1
    0       13      6158.45142253444        1

DaysinOp可能来自0-300Zone ID=1-20以及DailyAvg= VariableRunNumber =1-5

我想输出如下:

Day #   Run 1 Weight (lbs)  Run 2 Weight (lbs)  Run 3 Weight (lbs)  Run 4 Weight (lbs)
0             15                      5            55                   1
1             17                     16           612                   34
2             19                     55          1100                  56
3            22                       100            1230              456
Etc.    …   …   …   …

其中每个运行重量是区域ID(1-10)的每日平均值的总和。

如果可能,请告诉我。

我正在尝试使用总和条件?任何提示将不胜感激。

2 个答案:

答案 0 :(得分:1)

SELECT
  DaysInOp,
  SUM(CASE WHEN Zone_id BETWEEN 1 AND 10
            AND RunNumber = 1            THEN DailyAvg END)   AS Run1Weight,
  SUM(CASE WHEN Zone_id BETWEEN 1 AND 10
            AND RunNumber = 2            THEN DailyAvg END)   AS Run2Weight,
  SUM(CASE WHEN Zone_id BETWEEN 1 AND 10
            AND RunNumber = 3            THEN DailyAvg END)   AS Run3Weight,
  SUM(CASE WHEN Zone_id BETWEEN 1 AND 10
            AND RunNumber = 4            THEN DailyAvg END)   AS Run4Weight,
  SUM(CASE WHEN Zone_id BETWEEN 1 AND 10
            AND RunNumber = 5            THEN DailyAvg END)   AS Run5Weight
FROM
  yourTable
GROUP BY
  DaysInOp

可以通过将Zone_id BETWEEN 1 AND 10移动到WHERE子句来简化。但是,如果某一天在这些区域中没有记录,则它不会出现在结果中。

SELECT
  DaysInOp,
  SUM(CASE WHEN RunNumber = 1 THEN DailyAvg END)   AS Run1Weight,
  SUM(CASE WHEN RunNumber = 2 THEN DailyAvg END)   AS Run2Weight,
  SUM(CASE WHEN RunNumber = 3 THEN DailyAvg END)   AS Run3Weight,
  SUM(CASE WHEN RunNumber = 4 THEN DailyAvg END)   AS Run4Weight,
  SUM(CASE WHEN RunNumber = 5 THEN DailyAvg END)   AS Run5Weight
FROM
  yourTable
WHERE
  Zone_id BETWEEN 1 AND 10
GROUP BY
  DaysInOp

答案 1 :(得分:0)

@MatBailie提供了手动数据透视,这是使用数据透视运算符的相同查询:

with t1 as (
  select DaysInOp
       , case when zone_id between 1 and 10 then dailyavg end rw
       , RunNumber
    from table1
)
select DaysInOp [Day #]
     , [1] [Run 1 Weight (lbs)]
     , [2] [Run 2 Weight (lbs)]
     , [3] [Run 3 Weight (lbs)]
     , [4] [Run 4 Weight (lbs)]
     , [5] [Run 5 Weight (lbs)]
  from t1
  pivot (sum(rw)
    for RunNumber in ([1],[2],[3],[4],[5])) pvt