![](/img/trans.png)
[英]mySQL: Given 2 column data, find 3rd column and then AVG() 3rd column based on 2nd column
[英]Find the 2nd row of data based on a column value, if not available then print NULL
我正在蜂巢中的某個項目上,下面的問題是其中的一部分。 請注意,我將針對已經完成的子查詢結果/表應用此查詢的解決方案。
因此,作為此過程的一部分,我試圖根據rnum的列值為每個id打印行。 如果rnum = 2,則打印兩個列值,即id,value。 如果ID不存在rnum = 2,則打印ID,“無值”。
在下面給出樣本輸入和預期輸出。
例如。
對於id 100,由於rnum只有1,因此將值打印為“無值”
對於id 200,僅打印rnum = 2的值,即xyz並忽略rnum = 1,3和4的值
輸入:
id value rnum
100 abc 1
200 def 1
200 xyz 2
200 rtz 3
200 tgv 4
預期產量:
id value
100 No Value
200 xyz
您可以使用聚合和case
邏輯:
select id,
(case when sum(case when mum = 2 then 1 else 0 end) > 0
then max(case when mum = 2 then value end)
else 'No Value'
end)
from t
group by id;
您可以如下所示進行操作:
select a.id, case when t.id is null then 'No value' else t.value end
from (select distinct id as id from t) a
left join t on t.rnum = 2 and a.id = t.id
這是您的查詢。
select t1.id, case when t2.rnum != 1 then t2.value else 'no value' end
from (
select count(1) as ct, id from test2
group by id) t1
left join test2 t2 on t2.id = t1.id and t2.rnum = 2
order by t1.id asc
已更改,允許任何id值:
with t2(id, cnt) as
(
select id, count(*) as cnt
from t1
group by id
)
select t1.id,
max(case
when t2.cnt = 1 and t1.rnum = 1 then 'No Value'
when t2.cnt > 1 and t1.rnum = 2 then value
end)
from t1
join t2 on t2.id = t1.id
group by t1.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.