SQL:旋转后合并行
我正在编写的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用聚合查询:
Use an aggregation query: