SQL Server使用count()和group by加入Select语句

时间:2011-08-19 18:11:25

标签: sql sql-server sql-server-2005

我在SQL Server中有两个表,tbl_disputestbl_disputetypestbl_disputes表包含外键列disputetype。表格tbl_disputetypes包含主键字段disputetypeiddisputetypedesc。以下查询为我提供了disputetype表中每个tbl_disputes的计数。

select disputetype, count(disputetype) as numberof
from tbl_disputes
group by disputetype

我需要使用哪种连接或子查询来显示 tbl_disputetypes.dbo.disputetypedesc代替tbl_disputes.dbo.disputetype?

编辑问题是因为disputetypedesc设置为TEXT。我将其更改为nvarchar,以下查询有效:

SELECT
    tbl_disputetypes.disputetypedesc,
    count(tbl_disputetypes.disputetypedesc)
FROM
    tbl_disputes Left OUTER JOIN
    tbl_disputetypes ON tbl_disputes.disputetype = tbl_disputetypes.disputetypeid
group by tbl_disputetypes.disputetypedesc

5 个答案:

答案 0 :(得分:3)

除非我遗漏了某些内容,否则您只能LEFT JOIN说明:

select disputetypedesc, count(disputetype) as numberof
from tbl_disputes d
LEFT JOIN tbl_disputetypes dt
    ON dt.disputetypeid = d.disputetype
group by disputetypedesc

答案 1 :(得分:2)

假设2005 +:

WITH x(t, numberof) AS 
(
  SELECT disputetype, COUNT(*) 
    FROM tbl_disputes 
    GROUP BY disputetype
)
SELECT dt.disputetypedesc, x.numberof
  FROM tbl_disputetypes AS dt
  INNER JOIN x ON dt.disputetype = x.t;

答案 2 :(得分:2)

一个简单的JOIN?

select
    DT.disputetypedesc, count(*) as numberof
from 
    tbl_disputes D
    JOIN
    tbl_disputetypes DT ON D.disputetype = DT.disputetype
group by
    DT.disputetypedesc

答案 3 :(得分:1)

基本思想是你需要一个子查询。这样的事情会起作用:

select disputetypedesc, disputetype, numberof
from (select disputetype, count(disputetype) numberof
      from tbl_disputes
      group by disputetype) t left outer join
     tbl_disputetypes on t.disputetype = tbl_disputetypes.disputetype

答案 4 :(得分:0)

我不确定我是否理解您的问题但您应该能够使用类似于下面的代码示例的查询选择所有列。

以下查询将通过disputetypeid列连接两个表。我改变了SQL语句的格式,但是你可以根据需要对它进行格式化。

    SELECT tbl_disputetypes.disputetypedesc
         , tbl_disputes.*
         , <any_column_from_either_table>
      FROM tbl_disputes
INNER JOIN tbl_disputetypes
        ON tbl_disputes.disputetypeid = tbl_disputetypes.disputetypeid