简体   繁体   English

如何显示不同的日期数据(来自同一表)作为Oracle中的列

[英]How to show different dates data (from the same table) as columns in Oracle

I'm sorry if the title wasn't too clear, but the following explanation will be more accurate. 如果标题不太清楚,很抱歉,但是以下说明会更准确。

I have the following view: 我有以下观点:

DATE          USER         CONDITION
20140101      1            A
20140101      2            B
20140101      3            C
20140108      1            C
20140108      3            B
20140108      2            C

What I need to do is present how many users where in all conditions this week and 7 days before today. 我需要做的是显示本周和今天之前7天在所有情况下有多少用户。

Output should be like this: 输出应如下所示:

Condition          Today          Last_Week (Today-7)
A                  0              1
B                  1              1
C                  2              1

How can I do this in Oracle? 如何在Oracle中做到这一点? I will need to do this for 4 weeks so itll be Today-7,14-21. 我将需要做4周,所以今天是7月14日至21日。

I've tried this with group by but I get the "week2" as rows. 我已经用group by尝试过了,但是得到的是“ week2”。 Then I've tried something like Select conditions, (select count(users) from MyView where DATE='Today') FROM MyView (looking at something thats actually working) but it doesnt work for me. 然后,我尝试了类似“ Select conditions, (select count(users) from MyView where DATE='Today') FROM MyView (查看实际上有效的内容),但它对我不起作用。

Achieved this with a little modification of the accepted answer: 通过对接受的答案进行一些修改即可实现此目的:

select condition, 
   count(case when to_date(xdate) = to_date(sysdate) then 1 end) to_day,
   count(case when to_date(xdate) = to_date(sysdate-7) then 1 end) last_7_days
from my_table
group by condition
select condition, count(case when to_date(xdate) = to_date(sysdate) then 1 end) to_day,
       count(case when to_date(xdate) < to_date(sysdate) then 1 end) last_7_days
  from my_table
 where to_date(xdate) >= to_date(sysdate) - 7
 group by condition
select condition
,      sum
       ( case
         when date between trunc(sysdate) - 7 and trunc(sysdate) - 1
         then 1
         else 0
         end
       )
       last_week
,      sum
       ( case
         when date between trunc(sysdate) and trunc(sysdate + 1)
         then 1
         else 0
         end
       )
       this_week
from   table
group
by     condition

By using the conditional count (as a sum) and grouping on condition you can filter out all desired dates. 通过使用条件计数(总和)并按条件分组,可以过滤出所有所需日期。 Note that using trunc will cause to use the begin of the day. 请注意,使用trunc将导致使用一天的开始时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM