简体   繁体   English

SQL select 列 group by 其中值的比率为 1

[英]SQL select column group by where the ratio of a value is 1

I am using PSQL.我正在使用 PSQL。

I have a table with a few columns, one column is event that can have 4 different values - X1, X2, Y1, Y2.我有一个有几列的表,一列是可以有 4 个不同值的event - X1、X2、Y1、Y2。 I have another column that is the name of the service and I want to group by using this column.我有另一列是服务的名称,我想使用此列进行分组。

My goal is to make a query that take an event and verify that for a specific service name I have count(X1) == count(X2) if not display a new column with "error"我的目标是进行一个带有事件的查询并验证对于特定服务名称,如果不显示带有“错误”的新列,我有 count(X1) == count(X2)

Is this even possible?这甚至可能吗? I am kinda new to SQL and not sure how to write this.我对 SQL 有点陌生,不知道怎么写。

So far I tried something like this到目前为止,我尝试过这样的事情

select 
    service_name, event, count(service_name) 
from 
    service_table st 
group by 
    (service_name, event); 

I am getting the count of each event for specific service_name but I would like to verify that count of event 1 == count of event 2 for each service_name.我正在获取特定 service_name 的每个事件的计数,但我想验证每个 service_name 的事件 1 的计数 == 事件 2 的计数。

I want to add that each service_name have a choice of 2 different event only.我想补充一点,每个 service_name 只能选择 2 个不同的事件。

You may not need a subquery/CTE for this, but it will work (and makes the logic easier to follow):您可能不需要子查询/CTE,但它会起作用(并使逻辑更容易遵循):

WITH event_counts_by_service AS (SELECT
service_name
, COUNT(CASE WHEN event='X1' THEN 1 END) AS count_x1
, COUNT(CASE WHEN event='X2' THEN 1 END) AS count_x2
FROM service_table
GROUP BY service_name)
SELECT service_name
, CASE WHEN count_x1=count_x2 THEN NULL ELSE 'Error' END AS are_counts_equal
FROM event_counts_by_service

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

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