简体   繁体   中英

Xamarin SQLite.net group columns by data and sum numbers

I am learning Xamarin,I am using this [sqlite plugin][1. I would like to aggregate table value by dates(MyCreateDate) and sum the number of words (Word1 ) in thoses date (moth,yeah).

For example if I have:

3 words in November 2001, nothing  in December 2001, 6 words in january 2002,2 words in febuary 2002, nothing  in March 2002.

I would like to have a return like :

Moth      Year   NumberWords
11        2001      3 
12        2001      0
1         2002      6
2         2002      2
3         2002      0

Here is my model Model.cs:

[PrimaryKey, AutoIncrement]
public int ID { get; set; }

[JsonProperty(PropertyName = "id")]
public string MyId { get; set; }

[JsonProperty(PropertyName = "myCreated")]
public DateTime MyCreateDate { get; set; } = DateTime.UtcNow; // with this value of date

[JsonProperty(PropertyName = "myUpdate")]
public DateTime MyUpdateDate { get; set; } = DateTime.UtcNow;

[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }

[JsonProperty(PropertyName = "wordissaved")]
public bool WordIsSaved { get; set; } = false;

[JsonProperty(PropertyName = "word1")]
public string Word1 { get; set; }

[JsonProperty(PropertyName = "word2")]
public string Word2 { get; set; }

Here is Database MyWordsDatabase.cs, I have manage to get words and select randoms words:

class MyWordsDatabase
    {
        private SQLiteAsyncConnection conn;

        //CREATE  
        public MyWordsDatabase()
        {
            conn = DependencyService.Get<ISQLite>().GetConnection();
            conn.CreateTableAsync<MyWords>();
        }

        //READ  
        public  Task <List<MyWords>> GetWords()
        {
            var wordList = conn.Table<MyWords>();
            return wordList.OrderByDescending(w => w.ID).ToListAsync();

        }

        // Select ramdon words and put them in a list 
         public   Task<List<MyWords>> GetRandomListWords(int number)
        {
            var words =  conn.QueryAsync<MyWords>("select DISTINCT  * from MyWords ORDER BY RANDOM() LIMIT " + number + "");

            return  words;
        }

     }

Thanks for your help

you can use LINQ to group

var query = (from w in wordList
         group w by new {w.MyCreateDate.Year, w.MyCreateDate.Month}
         into grp
                select new
                {
                    grp.Key.MyCreateDate.Year,
                    grp.Key.MyCreateDate.Month,
                    Quantity = grp.Count()
                }).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM