按非标准化列分组

Group by non normalised Columns

使用 SQL Server 2000 - 我有一个旧数据库,它没有规范化。

它有一堆像

这样的列
memId
c1
c2
c3
c4
c5

这些列在此处包含一个数字示例

123
10
20
0
40
0

123
0
20
0
40
5

我想要的是像这样提取按memId和列名分组的数据

会变成

memId  col   total
123    c1    10
123    c2    40
123    c4    80
123    c5    5

其中数字是组的总和

我想我可以每次拉动并将它们合并在一起,但想知道是否有更简单的方法。

听起来您想 unpivot 您的结果。您的数据库的一个选项是 union all:

select memId, 'c1' as col, sum(c1) from yourtable group by memId, col
union all
select memId, 'c2' as col, sum(c2) from yourtable group by memId, col
union all
select memId, 'c3' as col, sum(c3) from yourtable group by memId, col
union all
select memId, 'c4' as col, sum(c4) from yourtable group by memId, col
union all
select memId, 'c5' as col, sum(c5) from yourtable group by memId, col

看来我误会你的意思了,哎呀。您正在将信息迁移到另一个 table?

But first, a note about my use of the term normalization

First Normal Form
 - Eliminate repeating groups in individual tables.
 - Create a separate table for each set of related data.
 - Identify each set of related data with a primary key.

So clearly I was wrong about the normalization. Ouch. Good thing I'm still young, eh? :/

我花了一些时间重新评估这个(一个致命的错误,不是吗?)以及 SQL Server 2000 的局限性。我在 redware - SQL SERVER Handbook.

上找到了有用的 SQL Server 2000 手册汇编

当谈到 table 表达式时...唯一出现的是 subqueriesviews,尽管没有真正的排名函数可用(谢天谢地,您可以创建 Functions).

虽然您可以通过某种草书添加一个值,为什么呢?

  • 您仍将解析 table 至少 N x #Columns 以取消透视。不需要复杂的枢轴(无论如何都不存在)。
  • 无需使用任何昂贵的草书,SELECT 'C1' 简单易行。
  • 您想连接 table,所以最简单的方法仍然是 UNION ALL
  • 您可以在连接后 运行 GROUP BY 一次。简洁大方。

解决方案:

SELECT memID
     , Col
     , SUM(C1) AS Count 
FROM (
      SELECT 'C1' AS [Col], memID, C1 FROM  #Test2
      UNION ALL SELECT 'C2' AS [Col], memID, C2 FROM #Test2
      UNION ALL SELECT 'C3' AS [Col], memID, C3 FROM #Test2
      UNION ALL SELECT 'C4' AS [Col], memID, C4 FROM #Test2
      UNION ALL SELECT 'C5' AS [Col], memID, C5 FROM #Test2 ) AS A
GROUP BY memID, Col
ORDER BY memID ASC, Col ASC

来源Table:

CREATE TABLE #Test2 (memID INT, C1 INT, C2 INT, C3 INT, C4 INT, C5 INT)
INSERT INTO #Test2 (memId, C1, C2, C3, C4, C5)
VALUES (123, 10, 20, 0, 40, 0)
     , (123, 0, 20, 0, 40, 5)
     , (122, 5, 20, 10, 15, 0)
     , (122, 5, 0, 0, 0, 60)
     , (155, 10, 0, 0, 10, 10)
     , (155, 0, 0, 0, 50, 50)

结果:

memID   Col Count
122     C1  10
122     C2  20
122     C3  10
122     C4  15
122     C5  60
123     C1  10
123     C2  40
123     C3  0
123     C4  80
123     C5  5
155     C1  10
155     C2  0
155     C3  0
155     C4  60
155     C5  60

所以我认为你最初的想法是正确的。 干杯。