使用聚合或子查询进行分组

时间:2012-09-13 19:17:16

标签: sql-server tsql

我怎么能这样做(不是生产,知道它不漂亮):

SELECT mat1_01_06, count(mat1_01_06), MAX(mat_no),
MAX(
        (
          SELECT 
          document.mat_no
          FROM TimeMatters11.lntmu11.document 
          WHERE matter.sysid = document.mat_id and ccode = 'SUMS' 
        )
    )
FROM TimeMatters11.lntmu11.matter
WHERE con_no in 
('PR12-221' , '...', '...)
AND mat1_01_06 != ''
GROUP BY mat1_01_06
HAVING count(mat1_01_06) > 1
ORDER BY count(mat1_01_06) desc

输出

  

消息130,级别15,状态1,行7
无法对包含聚合或子查询的表达式执行聚合函数。

我希望mat_no的子文档编码为“SUMS”

编辑2

不带子查询的输出

Index                Cnt    mat_no(not useful)
112565/11            25     12-61692
16601/11             12     12-58850
34934/11             12     12-58854
34935/11             12     12-61983
704612/12            12     12-55487
712166/12            11     12-55613
707588/12            9      12-55604
91394/11             8      12-57115

所需

Index           Cnt     Mat_no that contains doc 'SUMS' 
112565/11   25      12-61692
16601/11    12      12-58850
34934/11    12      12-58854
34935/11    12      12-61983
704612/12   12      12-55487
712166/12   11      12-55613
707588/12   10      12-55604

mat_no是与索引的多对一关系,具有子doc'SUMS'的特定mat_no是主记录。我需要关注的那个。抱歉,我很困惑。

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?

SELECT mat1_01_06, count(mat1_01_06), MAX(mat_no),
       Mat_no =  (
          SELECT 
          MAX(document.mat_no)
          FROM TimeMatters11.lntmu11.document 
          WHERE matter.sysid = document.mat_id and ccode = 'SUMS' 
        )
FROM TimeMatters11.lntmu11.matter
WHERE con_no in 
('PR12-221' , '...', '...')
AND mat1_01_06 != ''
GROUP BY mat1_01_06
HAVING count(mat1_01_06) > 1
ORDER BY count(mat1_01_06) desc