簡體   English   中英

面對條件時如何使用sql平衡數據?

[英]How to equiry data using sql when facing condition?

type cost
 A    10
 A    11
 A    12
 B    10
 B    10

我有這個小樣本表。 我想選擇相同類型成本不同的數據,因此預期結果應為:

type cost
 A    10
 A    11
 A    12

A的成本不同,因此我需要選擇這些“ A”。 那么“選擇”句子是什么?


感謝您的答復。 其實我的桌子有點像這樣

type cost people
 A    10   jack
 A    11   frank
 A    12   lucy
 B    10   amy
 B    10   tom

我需要選擇滿足以下要求之一的數據:

  1. 相同類型但成本不同
  2. 與“ amy”同類型

所以結果應該像這樣:

type cost people
 A    10   jack
 A    11   frank
 A    12   lucy
 B    10   amy
 B    10   tom

選擇全部類型A,因為成本不同選擇全部類型B,因為人們有“好朋友”我已經弄清楚了如何選擇艾米,就像這樣:

select type, cost, people
from table 
where type in
(select type from table where people = 'amy')

我不知道如何結合這些條件。 SQL小提琴

您可以使用EXISTS查找具有相同類型但其他成本的另一行:

select t1.type, t1.cost
from tablename t1
where exists (select * from tablename t2
              where t2.type = t1.type
                and t2.cost <> t1.cost)

或者,有一個子查詢返回具有不同成本的類型值,並與該結果聯接:

select t1.type, t1.cost
from tablename t1
join (select type
      from tablename
      group by type
      having max(cost) <> min(cost)) t2
    on t1.type = t2.type

另一種方法是:

select 
   t.type, t.cost
from t 
left join t t1 on t.type = t1.type 
   and (t.cost <> t1.cost or t1.people = 'amy')
where 
   not t1.cost is null
group by 
   t.type, t.cost;

[SQL Fiddle Demo]

或者:

select *
from t
where exists (
  select 1
  from t t1
  where t1.type = t.type
  group by t1.type
  having count(distinct t1.cost) > 1
  -- below code added your new criteria
  union all
  select 1
  from t t2
  where t2.people = 'amy'
);

[SQL Fiddle Demo]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM