为SQL创建用户定义的聚合

时间:2019-07-12 00:06:41

标签: c# sql user-defined-aggregate

以下是我的想法示例。当您使用聚合函数查询tbl时,您应该是这个结果

Tally聚合功能

Table: tbl  

Tag length              
abc 8               
cde 8               
fgh 10      

SQL:

SELECT aggTally(Tag, Length) FROM tbl   

结果:

2/8   
1/10            

我是C#的新手,那么如何创建它并使用dll?

2 个答案:

答案 0 :(得分:0)

我看不到如上所述如何使用Tag,但是下面的代码返回了

2/8 1/10

->

    private static void TotalsByLength()
    {
        List<Tuple<string, int>> tagdata = new List<Tuple<string, int>>
        {
            new Tuple<string, int>("abs", 8),
            new Tuple<string, int>("cde", 8),
            new Tuple<string, int>("fgh", 10)
        };

        var tagcounts = from p in tagdata
            group p.Item2 by p.Item2 into g
            orderby g.Count() descending
            select new { g.Key, TotalOccurrence = g.Count() };

        foreach (var s in tagcounts)
        {
            Console.WriteLine("{0}/{1}", s.TotalOccurrence, s.Key );
        }
    }

答案 1 :(得分:0)

T-SQL方法:

CREATE TABLE dbo.TestTable (tag CHAR(3), taglen INT)
GO

INSERT INTO dbo.TestTable VALUES ('abs',8), ('cde', 8), ('fgh',10)
GO

;WITH TagTotal AS (SELECT taglen, COUNT(*) AS totallengthbytag
FROM dbo.TestTable
GROUP BY taglen)
SELECT a.totallengthbytag, a.taglen
FROM TagTotal a