簡體   English   中英

SQL 根據不同的列不同

[英]SQL Distinct based on different colum

我對基於其他列的列上的不同值有問題。 案例研究是:

表:列表

well | wbore | op|
------------------
wella|wbore_a|op_a|
wella|wbore_a|op_b|
wella|wbore_a|op_b|
wella|wbore_b|op_c|
wella|wbore_b|op_c|
wellb|wbore_g|op_t|
wellb|wbore_g|op_t|
wellb|wbore_h|op_k|

所以,我希望 output 出現在不同的字段/列中,例如:

 well | total_wbore | total_op
    ----------------------------
  wella |      2      |   3
    ---------------------------
  wellb |      2      |   2

真正的研究案例來自不同的表,但為了簡化,我假設這個案例發生在 1 個表中。

我試過的 sql 查詢:

SELECT well.well_name, wellbore.wellbore_name, operation.operation_name, COUNT(*) 
FROM well
INNER JOIN wellbore ON wellbore.well_uid = well.well_uid
INNER JOIN operation ON wellbore.well_uid = operation.well_uid 
GROUP BY  well.well_name,wellbore.wellbore_name
HAVING COUNT(*) > 1

但是這個查詢是計算不符合要求的重復行。 任何人都可以幫忙嗎?

你需要使用count distinct

SELECT 
  count(distinct wellbore.wellbore_name) as total_wbore
  count(distinct operation.operation_name) as total_op
FROM well
  INNER JOIN wellbore ON wellbore.well_uid = well.well_uid
  INNER JOIN operation ON wellbore.well_uid = operation.well_uid

最終查詢:

SELECT 
  well.well_name,
  COUNT(DISTINCT wellbore.wellbore_name) AS total_wbore,
  COUNT(DISTINCT operation.operation_name) AS total_op
FROM well
  INNER JOIN wellbore ON wellbore.well_uid = well.well_uid
  INNER JOIN operation ON wellbore.well_uid = operation.well_uid
  GROUP BY well.well_name

暫無
暫無

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

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