选择的ID数

时间:2015-04-27 15:31:57

标签: sql sql-server sql-server-2008

在下面的sql小提琴中,我如何更改视图以获得所需的输出?

http://sqlfiddle.com/#!6/a737a/1

查看

select
    sum(dollars) as totalDollars,
    sum(dollars)/count(id) as factor,
    count(id) as numberOfEvents, 
    id as eventID,
    event_date
from
    events
group by
    id,
    event_date

查询

select
*
from eventStats
where 
event_date between '1/1/2015' and '1/16/2015'

期望的输出

numberOfevents应该= 2(事件的实际数量,而不是每个事件的记录数,由查询中的where子句确定),以便在视图中正确地进行数学运算。

2 个答案:

答案 0 :(得分:1)

没有count条款,你可以distinct fk_id group by

select count(distinct fk_id) as number_of_IDs
from [myTable]
where [someCondition]

答案 1 :(得分:0)

distinct函数中使用count关键字:

select
    count(distinct fk_id) as number_of_IDs
    ,id
from
    myTable
where
    someCondition
group by
    id