sql - 如何将来自多个相似列的数据用作 SQL 中的行
问题描述
我有一个如下表:
项目名 | 1mth_presale_cost | 2mth_presale_cost | 1mth_postsale_cost | 2mth_postsale_cost |
---|---|---|---|---|
1000 | 10.1 | 12.1 | 12.5 | 15.1 |
1001 | 20.2 | 15.2 | 25.2 | 17.3 |
我希望结果如下表:
项目名 | 1mth_cost | 2mth_cost |
---|---|---|
1000 | 10.1 | 12.1 |
1000 | 12.5 | 15.1 |
1001 | 20.2 | 15.2 |
1001 | 25.2 | 17.3 |
我不想为此使用 UNION 。
解决方案
首先将每一行转换为两组,然后应用条件 CASE 语句以获得所需的结果。
-- SQL Server
SELECT t.ItemName
, CASE WHEN p.id = 1 THEN [1mth_presale_cost] ELSE [1mth_postsale_cost] END "1mth_cost"
, CASE WHEN p.id = 1 THEN [2mth_presale_cost] ELSE [2mth_postsale_cost] END "2mth_cost"
FROM test t
CROSS JOIN (SELECT 1 id UNION SELECT 2 id) p
ORDER BY t.ItemName, p.id
请从网址https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=3e1fdaf829c39554941c068b0c8a3e04检查
推荐阅读
- docker - 当我通过节点端口 i 访问应用程序时,未获取更改
- html - 如何使 HTML 和 CSS 下拉菜单正常工作?
- email - 使用 Smarty 检查字符串是否包含子字符串
- python - 读取一行或 idk 时的 EOF
- wpf - 异常未在 try-catch 中捕获
- angular - 缺少 int 类型的方法参数的 URI 模板变量“pagesize”
- python - 有没有办法在 sqlite 的 where 子句中包含多个变量?
- python - 如何从列表中过滤空字符串和回车?
- reactjs - 在 Firebase Analytics for Web 中跟踪默认事件
- python - 如何将 PATH 参数从脚本传递到批处理文件?