sql - Postgres sql基于整数在结果中显示特定字符串
问题描述
所以我有汽车的桌子和所说的汽车的颜色。颜色显示为整数,但我想在选择查询中映射它,以便显示相应的颜色。映射表不存在,我没有对数据库的写入权限,因此无法创建映射表。该查询仅适用于仅允许 SQL 查询的仪表板。
我有一张这样的桌子:
| **Color** | **Car** |
| 1 | BMW |
| 2 | Nissan |
| 1 | Tesla |
而这个查询
SELECT "Color", count(*)
FROM "Cars"
GROUP BY "Color"
这将给出这个结果:
| Color | Count |
| 1 | 2 |
| 2 | 1 |
但我想要的是这样的:
| Color | Count |
| white | 2 |
| green | 1 |
我怎样才能写这样的查询?
解决方案
Ok so "said table doesn´t exist and I don´t have write access". There is a very simple solution here: Go talk to your DBA and ask for it. One of the stupidest ideas in IT today is developers not talking to DBAs (almost as stupid as DBA not responding to developers). Contrary to popular belief you are on the same team.
However, in the event she/he doesn't respond (thus you unable to accomplish @Gordon goal of not repeating logic) but there is a work around - at least until the DBA comes to their sinces. You create a template CTE which can be pulled into queries as needed.
with color_names (id, name) as
( values (1,'White')
, (2,'Green')
)
Make sure this is stored in a location accessible to the entire team. This can the be pulled in whenever needed.
Then again, on second thought, you're a developer so develop: create a function that returns a table. You can then use this function almost exactly as if it were at table and it has a massive benefit - a single point of maintenance for all queries using it. Not quite the same as just updating a table, but massively better than having to update multiple queries.
Both are incorporated in fiddle.
推荐阅读
- c# - 将 Google 身份验证方法添加到现有 ASP.NET WebAPI 项目
- apache - Mod重写uri中第一个斜杠内的通配符问题
- javascript - 过滤没有键的 JavaScript 数组
- angularjs - Angular 和 Laravel 的第一步 - 重新编译失败
- wordpress - 从 wordpress 站点中的静态资源中删除查询字符串
- excel - 将单个工作表复制到多个工作簿
- imagemagick - LoadError:libgvc.so.5:无法打开共享对象文件:没有这样的文件或目录 - RMagick2.so
- opentracing - 跨度型客户端和跨度型服务器有什么区别?
- c - 这是否被认为是未定义的行为 x = ++x % 5;
- node.js - deno vs ts-node:有什么区别