如何在t-sql中的另一个聚合函数中进行聚合函数?

时间:2014-06-26 16:18:04

标签: sql sql-server tsql

我在t-sql中不是那么好..请帮忙...... 我得到了表Claims,列是:

Client,BusinessType, cliamRefno

我想要的结果如下:

SELECT Client, BusinessType, COUNT(cliamRefno ), SUM(COUNT(cliamRefno )), 
COUNT(cliamRefno )/SUM(COUNT(cliamRefno )) FROM Claims GROUP BY Client, BusinessType

可以请任何人帮忙吗?感谢

2 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @Claims TABLE (
    Client VARCHAR(50),
    BusinessType VARCHAR(50), 
    cliamRefno INT);
INSERT INTO @Claims VALUES('J Smith', 'Agricultural', 1);
INSERT INTO @Claims VALUES('D Brown', 'Agricultural', 2);
INSERT INTO @Claims VALUES('J Smith', 'Agricultural', 3);
INSERT INTO @Claims VALUES('Z Brown', 'Agricultural', 4);
WITH TotalClaims AS (
    SELECT
        COUNT(*) AS TotalClaims
    FROM
        @Claims)
SELECT 
    c.Client, 
    c.BusinessType, 
    COUNT(c.cliamRefno) AS RefNoCount, 
    tc.TotalClaims AS TotalRefNoCount, 
    COUNT(c.cliamRefno) * 1.0 / tc.TotalClaims AS SomeAggregate
FROM 
    @Claims c
    CROSS JOIN TotalClaims tc
GROUP BY 
    c.Client, 
    c.BusinessType,
    tc.TotalClaims;

答案 1 :(得分:0)

根据您的评论以及我从您的OP获得的内容,请根据您的需求进行尝试。您需要查询计数的子查询,然后在窗口函数中对它们求和以保留分组,但请查看您正在寻找的计数。

SELECT Client, BusinessType, Counts, SUM(Counts)OVER(), 
Counts/SUM(Counts)OVER()
FROM (
    SELECT Client, BusinessType, COUNT(cliamRefno) AS Counts
    FROM Claims
    GROUP BY Client, BusinessType
    ) T