根据不同条件错误多次调用同一列:子查询返回超过 1 个值

问题描述 投票:0回答:1

项目:

GUID   Name
1    P1
2    P2
3    P3

项目任务:

Name   ProjectID Time
PCO1   1         3600
PCA1   1         7200
PCO2   2         1000
PCA2   2         1500
PCO3   3         2000
PCA3   3         1250

结果列:

Projects.Name, Projecttasks.Name (condition 1 = %PCA%) ,Projecttasks.Time (CON1), Projecttasks.Name (condition 2 = %PCO%), Projecttasks.Time (CON2)

P1 PCA1 7200 PCO1 3600
P2 PCA2 1500 PCO2 1000
P3 PCA3 1250 PCO3 2000

我试过了

SELECT 
    projects.name,
    (SELECT Projecttasks.Name FROM ProjectTasks WHERE ProjectTasks.Name like '60 MATERIAL PCO%') AS PCO,
    (SELECT Projecttasks.Name FROM ProjectTasks WHERE ProjectTasks.Name like '60 MATERIAL PCA%') AS PCA
FROM
    projects
    Inner Join Projecttasks on Projects.GUID = ProjectTasks.ProjectID

但有错误

Msg 512, Level 16, State 1, Line 10 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

sql subquery multiple-conditions
1个回答
0
投票

只要每个 GUID 只有 1 个 PCO/PCA,一个简单的 pivot 应该能帮到你,如果你有更多,你需要检查聚合函数,看看你是否得到正确的名称和时间

SELECT
    p.Name,
    MAX(CASE WHEN pt.Name like '60 MATERIAL PCO%' THEN pt.Name END PCO_name,
    MAX(CASE WHEN pt.Name like '60 MATERIAL PCO%' THEN pt.Time END PCO_Time,
    MAX(CASE WHEN pt.Name like '60 MATERIAL PCA%' THEN pt.Name END PCA_name,
    MAX(CASE WHEN pt.Name like '60 MATERIAL PCA%' THEN pt.Time END PCA_Time
FROM Projects p INNER JOIN Projecttasks pt ON p.GUID    = pt.ProjectID 
GROUP BY p.GUID,p.Name
© www.soinside.com 2019 - 2024. All rights reserved.