简体   繁体   English

带分组的 Tableau/SQL 计算字段

[英]Tableau/SQL Calculated Field With Grouping

I have a table with the following structure我有一个具有以下结构的表

id, event_name, event_date
| 1 | a | 1.1.2020 | 
| 2 | b | 3.2.2020 | 
| 3 | b | 3.2.2020 |
| 3 | b | 5.2.2020| 
| 1 | b | 31.12.2019 | 
| 2 | a | 5.1.2020 | 

My goal would be to perform a grouping on the id and then I'd have to check wheter the date of an event 'a' comes before an event 'b'.我的目标是对 id 进行分组,然后我必须检查事件“a”的日期是否在事件“b”之前。 If so I'd like to output 'ok' and 'error' elsewise.如果是这样,我想输出 'ok' 和 'error' 否则。

In this example this would result to在这个例子中,这将导致

id, check
| 1 | error| 
| 2 | ok |  
| 3 | ok |  

Would it be possible to perform the task with a calculated field in Tableau?是否可以使用 Tableau 中的计算字段来执行任务? SQL would be also be ok! SQL也可以!

Try this尝试这个

   Select id, case when diff<0 then 'ok' 
   else 'error' end as status from 
   (
    Select id,

    max(case when event_name ='a' then event_date end) - 
    max(case when event_name='b' then event_date end)
   As diff
    From table group by id order by id) 
  

You can use this query with UNION clause:您可以将此查询与 UNION 子句一起使用:

select id, 'Error' "check" from mydata md where event_name='a' and id in 
(select id from mydata where id=md.id and md.event_name<>event_name 
and md.event_date > event_date) 
union
select id, 'Ok' "check" from mydata md where event_name='a' and id in 
(select id from mydata where id=md.id and md.event_name<>event_name 
and md.event_date < event_date);

Output should be :输出应该是:

| ID | 'ERROR' |
|----|---------|
|  1 |   Error |
|  2 |      Ok |

ID=3 doesn't appear, because event_name both are 'b'. ID=3 没有出现,因为 event_name 都是 'b'。

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

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