来自子查询的多个'group by'

时间:2014-07-19 17:26:49

标签: sql sql-server tsql

以下查询来自视图。使用案例是因为巡逻编号来自基于名称值的不同字段。

子查询

select timetag1, name,   
case when name = 'Location1' then afield17
     when name = 'Location2' then afield16 
     when name = 'Location3' then afield22 end as PatrolNo
FROM         someView
where timetag1 > (getdate-2) and timetag1 < GETDATE()
group by PatrolNo, Name

上述查询为我提供了过去两天三个地点和巡逻号码的以下结果。结果:

timetag1                        name                    PatrolNo


2014-07-19 17:53:22.000         Location1               A

2014-07-19 17:54:12.000         Location1               B

2014-07-19 17:55:08.000         Location2               B

2014-07-19 17:55:38.000         Location3               C

2014-07-19 17:56:13.000         Location2               A

2014-07-19 18:59:01.000         Location1               C

2014-07-19 19:59:45.000         Location2               B

2014-07-18 13:00:28.000         Location1               B

2014-07-18 13:02:47.000         Location3               A

2014-07-18 13:03:45.000         Location1               B

2014-07-18 14:04:46.000         Location2               C

2014-07-18 15:05:37.000         Location2               B

2014-07-18 18:06:25.000         Location1               A

2014-07-18 18:08:02.000         Location3               C

现在我想使用上面的查询作为子查询(因为它已经来自视图我不希望有嵌套视图) 所以我可以得到给定日期某个地点(名字)的巡逻号码

它按日期分组,然后按位置分组,与巡逻编号一起计算。

例如,如果你从19岁的第19天开始,从下面拿第一行,则1有一个值为A的巡逻号

预期

name        timetag1        PatrolNo     Count

Location1   2014-07-19          A            1

Location1   2014-07-19          B            1

Location1   2014-07-19          C            1

Location2   2014-07-19          A            1

Location2   2014-07-19          B            2

Location3   2014-07-19          C            1

Location1   2014-07-18          A            1

Location1   2014-07-18          B            2

Location2   2014-07-18          C            1

Location2   2014-07-18          B            1

Location3   2014-07-18          A            1

Location3   2014-07-18          C            1

尝试失败:

select temp.timetag1, temp.PatrolNo, COUNT(*) from

(select timetag1, name,   
case when name = 'Location1' then afield17
     when name = 'Location2' then afield16 
     when name = 'Location3' then afield22 end as PatrolNo
FROM         someView
where timetag1 > (getdate-2) and timetag1 < GETDATE()) as temp

group by timetag1, name, PatrolNo

1 个答案:

答案 0 :(得分:1)

你非常接近:

select cast(temp.timetag1 as date), temp.PatrolNo, COUNT(*)
from (select timetag1, name,   
             (case when name = 'Location1' then afield17
                   when name = 'Location2' then afield16 
                   when name = 'Location3' then afield22
              end) as PatrolNo
      FROM  someView
      where timetag1 > (getdate() - 2) and timetag1 < GETDATE()
    ) temp
group by cast(temp.timetag1 as date), PatrolNo;

主要更改是从name()子句中删除group by。另外,我假设第一次提到getdate()是函数调用,所以我添加了parens。