简体   繁体   English

如何根据特定条件选择记录

[英]How to pick records based on specific condition

I have a table named as "ticket_lc" look like below 我有一个名为“ ticket_lc”的表,如下所示

在此处输入图片说明

From the above table i need to pick only the records which satisfy the condition 从上表中,我只需要选择满足条件的记录

condition: the ticket status should be in "assigned" and "closed" and "resolved" 条件:票证状态应为“已分配”,“已关闭”和“已解决”

so in the above table only 102 ticket is satisfying the condition, if the ticket contains other than these 3 then my query should not pick those tickets. 因此,在上表中,只有102张票证满足条件,如果票证包含这3张票证之外的其他票证,则我的查询不应选择这些票证。

can anybody help me on this..!!! 有人可以帮我吗.. !!!

Thanks 谢谢

You can do aggregation : 您可以进行聚合:

select ticket_id
from table t
group by ticket_id
having sum( case when status not in ('assigned', 'closed', 'resolved') then 1 else 0 end ) = 0 and
       count(*) = 3;

If you have a duplicate status for ticket then use distinct inside count() . 如果您的票证状态重复,请使用distinct内部count()

Below is for BigQuery Standard SQL 以下是BigQuery标准SQL

#standardSQL
SELECT ticket_id
FROM `project.dataset.ticket_lc`
GROUP BY ticket_id
HAVING COUNT(DISTINCT status) = 3
AND COUNTIF(LOWER(status) NOT IN ('assigned', 'closed', 'resolved')) = 0 

Yo can test, play with above using sample data from your question as in below example 您可以使用问题中的示例数据进行测试,玩游戏,如以下示例所示

#standardSQL
WITH `project.dataset.ticket_lc` AS (
  SELECT 101 ticket_id, 'Assigned' status UNION ALL
  SELECT 101, 'Pending' UNION ALL
  SELECT 101, 'Resolved' UNION ALL
  SELECT 101, 'Closed' UNION ALL
  SELECT 102, 'Assigned' UNION ALL
  SELECT 102, 'Resolved' UNION ALL
  SELECT 102, 'Closed' UNION ALL
  SELECT 103, 'Assigned' UNION ALL
  SELECT 103, 'Pending' UNION ALL
  SELECT 103, 'Pending' UNION ALL
  SELECT 103, 'Assigned' UNION ALL
  SELECT 103, 'Resolved' UNION ALL
  SELECT 103, 'Closed' 
)
SELECT ticket_id
FROM `project.dataset.ticket_lc`
GROUP BY ticket_id
HAVING COUNT(DISTINCT status) = 3
AND COUNTIF( LOWER(status) NOT IN ('assigned', 'closed', 'resolved')) = 0 

with result 结果

Row ticket_id    
1   102  

Kind of an interesting problem. 有点有趣的问题。 I came up with this checking if everything is covered and the amount is correct: 我想出了这个检查,是否涵盖了所有内容并且金额是否正确:

WITH t AS (SELECT * FROM UNNEST(
  [struct(101 as ticket_id, 'assigned' as status),(101,'closed'),
    (102,'assigned'),(102,'resolved'),(102,'closed'),
    (104,'assigned'),(104,'assigned'),(104,'closed'),
    (103,'assigned'),(103,'pending'),(103,'pending'),(103,'assigned'),(103,'resolved'),(103,'closed')]  
  )
)

SELECT ticket_id, array_agg(distinct status) as st 
FROM t
group by 1
having (SELECT count(1)=3 FROM unnest(st) a left join unnest(['assigned','resolved','closed']) b on a=b)

Includes adjusted sample data to cover more problem cases. 包括调整后的样本数据以涵盖更多问题案例。

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

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