查询在postgresql中没有相应的工作

时间:2016-06-09 06:44:22

标签: sql postgresql

Select sum(num) as num, sum(numbr) as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t, 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1

给出结果:

num numbr
2   10

但正确的结果应该是

num numbr
1   5

4 个答案:

答案 0 :(得分:2)

您正在执行包含0和1的表格以及包含2和3的表格的叉积。请尝试删除总和:

Select num, numbr as numbr from 
(
(Select 0 as num)
union all
(Select 1 as num))t, 
((Select 2 as numbr)
union all
(Select 3 as numbr)
)t1

这会给你:

0;2
0;3
1;2
1;3

这将正确地总计为2和10。

答案 1 :(得分:1)

发生这种情况是因为你是CROSS JOINING,每条记录都连接到没有关系条件的每条记录,这意味着在这种情况下,你的联接就变成了这样:

NUM | NUMBR
 0      2
 0      3
 1      2  
 1      3

其中SUM(NUM) = 2且SUM(NUMBR) = 10。

加入时,您必须指定关系条件,除非这是您想要的。

注意:您正在使用隐式连接语法(逗号分隔),您应该避免使用显式语法,这将帮助您确保使用关系条件(通过ON子句):< / p>

Select sum(num) as num, sum(numbr) as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t
INNER JOIN 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1
ON(t.<Col> = t1.<Col1>)

答案 2 :(得分:1)

Select num, numbr as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t, 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1

为您提供表格的cartessian产品。

| Num | Number |
|-----|--------|
| 0   | 2      |
| 0   | 3      |
| 1   | 2      |
| 1   | 3      |

因此,这些的总和是2和10

答案 3 :(得分:1)

它正如你所写的那样正常工作。如果您希望得到预期的结果,请尝试以下方法:

<div class="active-task-body" data-ng-repeat="items in UserAssignTaskAllData">
<div class="col-md-12" id="data-{{items.TaskDetailId}}">
<div class="task-data-images" ng- init="get_All_ImagesData(items.TaskDetailAttachment,items.TaskDetailId)"> 
</div></div></div>