SQL Server - 按不同列的值分组

时间:2016-11-10 20:31:46

标签: sql sql-server group-by

我有一组这样的数据:

   ID   Person1   Value1   Person2   Value2   Person3   Value3   Period
  ---------------------------------------------------------------------
   1       A        1         D        1                          June
   2       B        2                                             July
   3       C        3                                             June
   4       B        1         C        3         A        2       August
   5       C        2         A        2                          June

列ID只是一个行标识符,并不代表任何内容。我想按人物和期间对它们进行分组,然后是每个人的值的总和。预期结果如下:

Person   Period   Value
-----------------------
   A      June      3
   A      August    2
   B      July      2
   B      August    1
   C      June      5
   C      August    3
   D      June      1

可行吗?任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

  

基于问题编辑和评论:

SELECT Person, Period, SUM(Val) as total
FROM (
  SELECT Person1 as Person, Period, Value1 as Val
  FROM tablename
  UNION ALL
  SELECT Person2 as Person, Period, Value2 as Val
  FROM tablename
  UNION ALL
  SELECT Person3 as Person, Period, Value3 as Val
  FROM tablename
) sub
GROUP BY Person, Period
  

原始答案

将问题简化为要解决的步骤。

首次标准化

SELECT Person1 as Person, Value1 as Val
FROM tablename
UNION ALL
SELECT Person2 as Person, Value2 as Val
FROM tablename
UNION ALL
SELECT Person3 as Person, Value3 as Val
FROM tablename

然后按正常

添加em
SELECT Person, SUM(Val) as total
FROM (
  SELECT Person1 as Person, Value1 as Val
  FROM tablename
  UNION ALL
  SELECT Person2 as Person, Value2 as Val
  FROM tablename
  UNION ALL
  SELECT Person3 as Person, Value3 as Val
  FROM tablename
) sub
GROUP BY Person

答案 1 :(得分:0)

我喜欢将apply用于此目的:

select v.person, v.period, sum(v.value)
from t apply
     (values (Person1, Value1, Period),
             (Person2, Value2, Period),
             (Person3, Value3, Period)
     ) v(Person, Value, Period)
group by v.person, v.period;

答案 2 :(得分:0)

;WITH CTE (Person , Val) AS (SELECT Person1 as Person, Value1 as Val FROM          tablename UNION ALL SELECT Person2 as Person, Value2 as Val FROM tablename UNION ALL SELECT Person3 as Person, Value3 as Val FROM tablename ) SELECT Person, SUM(Val) FROM CTE GROUP BY Person