【问题标题】:How to join two tables and count records SQL如何连接两个表并统计记录SQL
【发布时间】:2022-01-12 21:27:29
【问题描述】:

表 1 是 maintable_KQPPJ :包含 GroupID、Year、Name、VendorID。此表包含多个具有相同 GroupID 的记录 表 2 是 cb_vendorinformation:包含 GroupID 和 CompanyName

我想加入 GroupID 上的两个表。输出应该只有 GroupID、CompanyName 和 Count。 Count 是 maintable_KQPPJ 中 GroupID 的不同计数。

我有以下代码,但它并没有真正给我正在寻找的输出。

SELECT  maintable_KQPPJ.GROUPID, cb_vendorinformation.CompanyName, count(distinct maintable_KQPPJ.GROUPID)
FROM maintable_KQPPJ
 JOIN cb_vendorinformation ON maintable_KQPPJ.GROUPID=cb_vendorinformation.GROUPID

maintable_KQPPJ:

GroupID  Year VendorID Name
26       2019 9999     John
26       2020 2345     Jane 
6        2018 3244     Jack
36       2021 3245     Jill 

cb_vendor 信息:

GroupID CompanyName 
26      Walmart    
6       Target     
36      Kroger      

输出应该是这样的

GroupID CompanyName Count
26      Walmart     2
6       Target      1
36      Kroger      1

【问题讨论】:

    标签: sql join


    【解决方案1】:

    你需要 group by 和 count(*)

    SELECT  maintable_KQPPJ.GROUPID
     , cb_vendorinformation.CompanyName
     , count(*)
    FROM maintable_KQPPJ
    JOIN cb_vendorinformation ON maintable_KQPPJ.GROUPID=cb_vendorinformation.GROUPID
    GROUP BY maintable_KQPPJ.GROUPID
     , cb_vendorinformation.CompanyName
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多