Try .NET /elinq/
Powered by Try .NET

SQL Server SELECT DISTINCT

A) DISTINCT one column example

var query = DbContext.Set<Cities>()
                .Query((Customers customer, Cities city) =>
                {
                    var result = SELECT(DISTINCT<Cities>(customer.City.@as(city.City)));
                    FROM(customer);

                    return result;
                })
                .OrderBy(city => city.City);

foreach (var city in query.Take(3))
    Console.WriteLine(city.City);

B) DISTINCT multiple columns example

var query = DbContext.Set<CityState>()
                .Query((Customers customer, CityState city) =>
                {
                    var result = SELECT(DISTINCT<CityState>(customer.City.@as(city.City), customer.State.@as(city.State)));
                    FROM(customer);

                    return result;
                });

foreach (var cityState in query.Take(3))
    Console.WriteLine((cityState.City, cityState.State));

C) DISTINCT with null values example

var query = DbContext.Set<Phones>()
                .Query((Customers customer, Phones phones) =>
                {
                    var result = SELECT(DISTINCT<Phones>(customer.Phone.@as(phones.Phone)));
                    FROM(customer);

                    return result;
                })
                .OrderBy(t => t.Phone);

foreach (var phone in query.Take(3))
    Console.WriteLine(phone?.Phone ?? "NULL");
var query = DbContext.Set<CityStateZip>()
                .Query((Customers customer, CityStateZip alias) =>
                {
                    var result = SELECT<CityStateZip>(customer.City.@as(alias.City),
                        customer.State.@as(alias.State),
                        customer.ZipCode.@as(alias.ZipCode));
                    FROM(customer);
                    GROUP(BY(customer.City), BY(customer.State), BY(customer.ZipCode));

                    return result;
                })
                .OrderBy(t => t.City)
                .ThenBy(t => t.State)
                .ThenBy(t => t.ZipCode);

foreach (var cityStateZip in query.Take(3))
    Console.WriteLine((cityStateZip.City, cityStateZip.State, cityStateZip.ZipCode));
var query = DbContext.Set<CityStateZip>()
                .Query((Customers customer, CityStateZip alias) =>
                {
                    var result = SELECT(DISTINCT<CityStateZip>(customer.City.@as(alias.City),
                        customer.State.@as(alias.State),
                        customer.ZipCode.@as(alias.ZipCode)));
                    FROM(customer);

                    return result;
                });

foreach (var cityStateZip in query.Take(3))
    Console.WriteLine((cityStateZip.City, cityStateZip.State, cityStateZip.ZipCode));

< BACK | HOME