sql-server-2008 - Display row of another table as column of current table
问题描述
Consider there are two tables: Table1:
**Result Total**
Pass 102
Fail 3
Undetermined 1
Table 2:
**Pass% Fail% Undetermined%**
96.23 2.83 0.94
Result Needed:
**Result Total Percentage**
Pass 102 96.23
Fail 3 2.83
Undetermined 1 0.94
How to convert the table 2 rows as column in table 1 to obtain the result ?
解决方案
first, You can try to do unpivot
on Table2
, then JOIN
with Table1
.
Your sql-server
version is 2008, you can use unpivot
by UNION ALL
.
CREATE TABLE T1(
Result VARCHAR(50),
Total int
);
CREATE TABLE T2(
Pass FLOAT,
Fail FLOAT,
Undetermined FLOAT
);
insert into T2 VALUES (96.23,2.83,0.94)
INSERT INTO T1 VALUES ('Pass',102);
INSERT INTO T1 VALUES ('Fail',3);
INSERT INTO T1 VALUES ('Undetermined',1);
Query 1:
SELECT t1.*,s.val
FROM (
SELECT Pass val,'PASS' Name
FROM T2
UNION ALL
SELECT Fail val,'Fail' Name
FROM T2
UNION ALL
SELECT Undetermined val,'Undetermined' Name
FROM T2
) s inner join T1 t1 on t1.Result = s.Name
| Result | Total | val |
|--------------|-------|-------|
| Pass | 102 | 96.23 |
| Fail | 3 | 2.83 |
| Undetermined | 1 | 0.94 |
If you can use CROSS APPLY
with VALUE
you can try this.
Query:
SELECT t1.*,s.val
FROM (
SELECT v.* FROM T2
CROSS APPLY(VALUES
(Pass,'PASS'),
(Fail,'Fail'),
(Undetermined,'Undetermined')
) v(val,Name)
) s inner join T1 t1 on t1.Result = s.Name
| Result | Total | val |
|--------------|-------|-------|
| Pass | 102 | 96.23 |
| Fail | 3 | 2.83 |
| Undetermined | 1 | 0.94 |
推荐阅读
- node.js - 获取 MongoDB 聚合不匹配的字段
- javascript - useState 在第二次调用后设置更改值
- php - 与变体相关的自定义品牌分类
- python - Pytorch:批处理中每个图像的文件特定操作
- aws-amplify-cli - AWS Amplify -- 无法迭代回滚,因为以下步骤不包含 previousMetaKey:{"status":"WAITING_FOR_DEPLOYMENT"}
- java - 使用 Stream 将 List 中的字段合并到 Java 中的新 List
- java - 为什么 IntelliJ 丢失了我所有项目的路径?
- python - 在 GEE/Colab 上为“线”几何横截面上的波段值创建图表,以查看它们如何随空间变化?
- salesforce - Customer 360 - 客户身份解析是什么意思
- android - Flutter App 卡在 Android 启动器屏幕上