我有UNION ALL查询,它给出了多行结果集的结果 我想总结只有具有某些条件的行的值为真 例如:
ELECT P_ID pid, P_COUNT pcount from
(
SELECT pid, ROUND(SUM(pcount*1)) pcount , OBJ_ID objId
FROM SEARCH_H
WHERE objId = '1' and pstart <= ADD_MONTHS(TO_DATE('05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM'), -3)
GROUP BY objId, pid
UNION ALL
SELECT pid, ROUND(SUM( pcount*2)) pcount , OBJ_ID objId
FROM SEARCH_H
WHERE objId ='1' and pstart > TO_DATE('05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM')
GROUP BY objId, pid
) results
ORDER BY pcount desc ;
现在表格是:
P_ID(VARCHAR2),
OBJ_ID(VARCHAR2),
P_COUNT(NUMBER),
pstart(TIMESTAMP)
数据
1,1,1,05/01/2018 12:00
1,2,1,05/01/2018 12:00
33,2,1,05/01/2018 12:00
1,1,1,05/01/2018 12:00
1,1,1,06/01/2018 12:00
1,2,1,06/01/2018 12:00
1,2,1,06/01/2018 12:00
33,1,1,06/01/2018 12:00
所以结果将是:
1,9
33,3
到目前为止,我的搜索结果如下: 我的问题是每个人分别选择其结果 所以现在我的结果是:
1,3
33,2
1,6
33,2
我真的被困在这里......
答案 0 :(得分:0)
我认为您需要在主查询中进行分组(再次),如:
SELECT P_ID pid, sum(pcount) from
(
SELECT pid, ROUND(SUM(pcount*1)) pcount , OBJ_ID objId
FROM SEARCH_H
WHERE objId = '13089' and pstart <= ADD_MONTHS(TO_DATE(
'05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM'), -3)
GROUP BY objId, pid
UNION ALL
SELECT pid, ROUND(SUM( pcount*2)) pcount , OBJ_ID objId
FROM SEARCH_H
WHERE objId ='13089' and pstart > TO_DATE(
'05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM')
GROUP BY objId, pid
) results
group by pid
ORDER BY pcount desc ;
答案 1 :(得分:0)
我认为您不需要UNION ALL(或任何类型的UNION),因为我认为您正在努力实现这一目标。
我有一些问题需要理解你的问题,但如果我说得对,也许这就是你要找的:
select p_id, obj_id, round(sum(p_count)) p_count
from (
select p_id, obj_id,
case
when pstart <= add_months(to_date('05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM'), -3) then p_count*1
when pstart > to_date('05/01/2018 12:00 AM', 'MM/DD/YYYY HH12:MI AM') then p_count*2
end p_count
from search_h
)
group by p_id, obj_id
order by p_count desc;