sql union 返回重复结果

标签 sql union

我有以下查询

select count(trade_sid), shortcode 
from  trade 
where 
    trade.trade_date <= sysdate and 
    trade.trade_date>= add_months(sysdate, -11) 
group by shortcode
UNION ALL
select count(trade_sid), shortcode 
from trade_archive 
where 
    trade_archive.trade_date <= sysdate and 
    trade_archive.trade_date>= add_months(sysdate, -11) 
group by shortcode
order by shortcode

这会导致像这样的重复输出
23 abc
24 abc 
56 def
87 def

这是因为使用了联合运算符,不知道如何更改此查询以便我得到
47 abc
143 def  

作为输出

我最终在 java 中执行此查询的用户没有足够的权限来创建临时表,还有其他方法可以解决这个问题吗?

最佳答案

像这样的东西:

select count(trade_sid), shortcode 
from
(
    select trade_sid, shortcode 
    from  trade 
    where 
        trade.trade_date <= sysdate and 
        trade.trade_date>= add_months(sysdate, -11) 
    UNION ALL
    select trade_sid, shortcode 
    from trade_archive 
    where 
        trade_archive.trade_date <= sysdate and 
        trade_archive.trade_date>= add_months(sysdate, -11) 
) tt
group by shortcode
order by shortcode

关于sql union 返回重复结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6273928/

相关文章:

mysql - 从 UNION 集合运算符中消除 NULL 值

Mysql - 根据月份日期合并两个表

python - 如何在不确定数量的参数上使用 LIKE 和 % with pymssql?

sql - 为什么这个 Oracle 查询不起作用?

java - 如何优化这个更新 SQL 查询

javascript - 如何找到渗透路径并突出显示?

sql - 合并SQL Server中行数不同的两个表

SQLite - 具有联合的多个随机结果集

javascript - Sequelize - 无法绑定(bind)多部分标识符 XXX

sql - 跨多个服务器复制数据 SQL