0

我不太清楚应该如何描述标题问题,但这是我的问题。我有一个名为和hello的两列的表。timestate

Time | State

这是我拥有的数据示例

1 DC
1 VA
1 VA
2 DC
2 MD
3 MD
3 MD
3 VA
3 DC

我想获得所有可能的时间和“VA”的计数(如果当时没有出现“VA”,则为 0)输出看起来像这样

Time Number
1 2
2 0
3 1

我试着做

SELECT DISTINCT time,
    COUNT(state) as Number
        FROM hello
        WHERE state = 'VA'
        GROUP BY time

但它似乎不起作用。

4

3 回答 3

2

这是一个条件聚合:

select time, sum(case when state = 'VA' then 1 else 0 end) as NumVA
from hello
group by time

我想补充一点,distinct当您拥有group by. 这两个是多余的。 Distinct在 SQL 语言中甚至不需要关键字;从语义上讲,它只是按所有列分组的简写。

于 2013-02-06T00:03:54.310 回答
2
SELECT  TIME,
        SUM(CASE WHEN State = 'VA' THEN 1 ELSE 0 END)
FROm    tableName
GROUP   BY Time
于 2013-02-06T00:04:05.273 回答
0

一个经验法则是先获得计数,然后将它们放入临时温度以供以后使用。见下文:

    Create table temp(Num int, [state] varchar(2))
    Insert into temp(Num,[state])
    Select 1,'DC'
        UNION ALL
    Select 1,'VA'
        UNION ALL
    Select 1,'VA'
        UNION ALL
    Select 2,'DC'
        UNION ALL
    Select 2,'MD'
        UNION ALL
    Select 3,'MD'
        UNION All
    Select 3,'MD'
        UNION ALL
    Select 3,'VA'
        UNION ALL
    Select 3,'DC'


     Select t.Num [Time],t.[State]
     , CASE WHEN t.[state] = 'VA' THEN Count(t.[State]) ELSE 0 END [Number]
     INTO #temp2
    From temp t
    Group by t.Num, t.[state]
    --drop table #temp2
    Select
    t2.[time]
    ,SUM(t2.[Number])
    From #temp2 t2
    group by t2.[time]
于 2013-02-06T02:17:00.923 回答