在group by子句中排除select语句列

时间:2016-09-19 19:29:32

标签: sql oracle

我有以下查询生成报告

select 
  cust.firstname as "FIRST NAME",
  cust.lastname as "LAST NAME",
  dept.name as "DEPARTMENT",
  subdept.name as "SUB DEPARTMENT",
  count(*) "cust type"
from cust
join dept on dept.deptid = cust.deptid
join subdept on subdept.deptid = cust.subdeptid
join custactivity on custactivity.custid = cust.custid
where custactivity.swipetime > (trunc(sysdate - 1))
group by cust.firstname,cust.lastname,dept.name,subdept.name
having count(*) > 5
order by "DEPARTMENT" ;

现在,我想要列#34; custactivity.swipetime"只在select语句中而不是group by子句,因为它是一个时间字段,如果我在group by子句中包含它,我会得到不正确的结果。怎么可能?

我在ORACLE Select and group by excluding one field中尝试了解决方案 但它没有成功。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

每位客户可以有许多保管活动。因此,您必须告诉DBMS选择哪种刷卡时间。例如最新的:

, max(custactivity.swipetime) as "last swipe time"

在下面的评论中,您说您想要每个cust.firstname,cust.lastname,dept.name,subdept.name, custactivity.swipetime的结果行。因此必须将swipetime添加到group by子句中。

以下是将swipetime添加到group by子句中的查询。您需要原始组的分析函数SUM。由于您不能在having子句中使用分析函数,因此需要一个周围的查询。

select *
from
(
  select 
    cust.firstname as "FIRST NAME",
    cust.lastname as "LAST NAME",
    dept.name as "DEPARTMENT",
    subdept.name as "SUB DEPARTMENT",
    custactivity.swipetime as "SWIPE TIME",
    sum(count(*)) over (partition by 
                        cust.firstname, 
                        cust.lastname, 
                        dept.name, 
                        subdept.name) as "cust type"
  from cust
  join dept on dept.deptid = cust.deptid
  join subdept on subdept.deptid = cust.subdeptid
  join custactivity on custactivity.custid = cust.custid
  where custactivity.swipetime > (trunc(sysdate - 1))
  group by 
    cust.firstname, 
    cust.lastname, 
    dept.name, 
    subdept.name, 
    custactivity.swipetime
)
where "cust type" > 5
order by "DEPARTMENT";