SQL:旋转后合并行

发布于 2025-01-11 20:39:00 字数 1035 浏览 0 评论 0原文

我正在编写的 SQL 查询的一部分处理通用元数据表。因此,我正在调整所需的元素以适应我需要的格式。我用“case”来做,我不确定这是否是问题,但这个子查询的结果采用这种格式:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║ 1     ║ (NULL)║
║  1 ║(NULL) ║ 2     ║
║  1 ║(NULL) ║ (NULL)║ 
║  2 ║(NULL) ║ (NULL)║
║  2 ║ 2     ║ (NULL)║
║  3 ║(NULL) ║ (NULL)║
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

不是最漂亮的输出,但我想我可以用“GROUP BY”修复它ID”以简化输出。如下:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║(NULL) ║ (NULL)║ ?????
║  2 ║(NULL) ║   2   ║
║  3 ║(NULL) ║ (NULL)║ 
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

也许我对 GROUP BY 的理解根本上是错误的,但我没想到 ID 1 的结果。现在我正在寻找一种组合行的方法。它应该看起来像这样:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║   1   ║   2   ║ 
║  2 ║(NULL) ║   2   ║
║  3 ║(NULL) ║ (NULL)║ 
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

因此,只需将行“添加”在一起就足够了,因为对于一个 ID,单个数据列中永远不会有两个值。所以它永远是“数字+ NULL”。有没有一种方法可以轻松做到这一点?我觉得这应该不是什么大问题,但我无法想出解决方案。

part of an SQL query I'm writing handles a generic metadata table. Thus I'm pivoting the needed elements to fit into the format I need them to be. I'm doing it with "case" and I'm not sure if that's the or a problem, but the result of this subquery comes in this format:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║ 1     ║ (NULL)║
║  1 ║(NULL) ║ 2     ║
║  1 ║(NULL) ║ (NULL)║ 
║  2 ║(NULL) ║ (NULL)║
║  2 ║ 2     ║ (NULL)║
║  3 ║(NULL) ║ (NULL)║
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

Not the most beautiful output, but I thought I can fix it with "GROUP BY ID" to streamline the output. It's as following:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║(NULL) ║ (NULL)║ ?????
║  2 ║(NULL) ║   2   ║
║  3 ║(NULL) ║ (NULL)║ 
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

Maybe my understanding of GROUP BY is fundamentally wrong, but I did not expect the result for ID 1. Now I'm looking for a way to combine the rows. It should look something like this:

╔════╦═══════╦═══════╗
║ ID ║ DATA1 ║ DATA2 ║
╠════╬═══════╬═══════╣
║  1 ║   1   ║   2   ║ 
║  2 ║(NULL) ║   2   ║
║  3 ║(NULL) ║ (NULL)║ 
║  4 ║(NULL) ║ (NULL)║
╚════╩═══════╩═══════╝

So simply "adding" the rows together is sufficient, since for one ID there will never be two values in a single data column. So it'll always be "number + NULL". Is there a way to do this without much hassle? I feel like this shouldn't be to much of a problem, but I can't come up with a solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖树树初阳… 2025-01-18 20:39:00

使用聚合查询:

SELECT ID, MAX(DATA1) AS DATA1, MAX(DATA2) AS DATA2
FROM yourTable
GROUP BY ID
ORDER BY ID;

Use an aggregation query:

SELECT ID, MAX(DATA1) AS DATA1, MAX(DATA2) AS DATA2
FROM yourTable
GROUP BY ID
ORDER BY ID;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文