【问题标题】:Sql Sybase row count of distinct set of rows不同行集的 Sql Sybase 行数
【发布时间】:2011-08-13 07:13:01
【问题描述】:

我有一个表,其中包含每笔交易的 security_id 和边(买入或卖出)。我想计算不同的 security_id 和 side 组合的数量。

所以当我执行以下操作时,我会得到所有符号面的列表,但我不知道如何获得总数?

select 
  security_id, side
from 
  trade
group by security_id, side

我想要的结果是 1 行,它告诉我表中有多少不同的 security_id,边。

还有一种方法可以确定哪些 security_id(s) 对双方都有条目(买入和卖出)。

【问题讨论】:

    标签: sql sybase


    【解决方案1】:

    你试过这样做吗?

    select 
     security_id, side , count(*)
         from 
            trade
           group by security_id, side
    

    【讨论】:

    • 这将为我提供每个 security_id 的总数。我想要不同的security_id,side的总数。
    • hmm .. 我没有方便的数据库来测试它,但我确信 group by 本质上为您提供了 security_id 和 side 的独特组合。
    • 我现在明白这个问题了.. 你想用另一个 select count(*) from (select security_id, side ...group by ...) 包装你的整个选择
    【解决方案2】:
    Select Count(*)
    From    (
            Select security_id, side
            From trade
            Group security_id, side
            ) As Z
    

    关于第二个问题:

    Select security_id
    From trade
    Where side In('BUY','SELL')
    Group security_id
    Having Count( Distinct side ) = 2
    

    【讨论】:

    • 在第二个问题中,OP 仅询问 ID,而不询问其数量。不过,您的第二个查询确实包含解决方案(在子查询中)。
    • @Andriy M - 啊。你是对的。我已经更新了第二个查询。
    猜你喜欢
    • 2015-06-25
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多