Creating User defined aggregation for SQL

133 Views Asked by At

Here’s a sample of what I have in mind. When you query tbl with the aggregation function you should be this Result

Tally Agregation function

Table: tbl  

Tag length              
abc 8               
cde 8               
fgh 10      

SQL:

SELECT aggTally(Tag, Length) FROM tbl   

Result:

2/8   
1/10            

I am very new to C#, so How do I create this, and have the dll for use?

2

There are 2 best solutions below

0
kcooper On

I don't see how Tag is used as mentioned above but the below code returns

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 );
        }
    }
0
kcooper On

T-SQL approach:

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