首页 > 解决方案 > 从 Azure 表存储中选择 MAX(值)

问题描述

如何从表存储中提取 MAX(值)?例如,什么等价于

select MAX(Timestamp) FROM DailyUsers

(但 DailyUsers 是 Azure 表存储而不是 SQL 表)

标签: azure-table-storage

解决方案


If you're using c# code, you can follow the steps below:

1.Create a .net framework console project, and install the WindowsAzure.Storage nuget package, version 9.3.3.

2.Define an entity class for your table storage. The code like below, and it's just a sample, you can modify it to meet your need:

using Microsoft.WindowsAzure.Storage.Table;

namespace ConsoleApp6
{
    public class CustomerEntity : TableEntity
    {
        public CustomerEntity()
        {
        }

        public CustomerEntity(string lastName, string firstName)
        {
            PartitionKey = lastName;
            RowKey = firstName;
        }

        public string FirstProperty { get; set; }
        public string SecondProperty { get; set; }
    }
}

3.Then in the program.cs, write the code below. And to get the max date record, you can use this line of code: OrderByDescending(r=>r.Timestamp).FirstOrDefault().

Sample code in program.cs:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Linq;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            string connstr = "DefaultEndpointsProtocol=https;xxxxxx;EndpointSuffix=core.windows.net";
            var storageAccount = CloudStorageAccount.Parse(connstr);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("your_table_name");

            TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>();

            //if you want to get the max date value from a specified PartitionKey, you can uncomment the following code.
            //string myfilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "r1");
            //query.FilterString = myfilter;

            var items = table.ExecuteQuery(query).OrderByDescending(r=>r.Timestamp).FirstOrDefault();

            Console.WriteLine(items.PartitionKey+","+items.RowKey+","+items.Timestamp);

            Console.ReadLine();
        }
    }
}

Please feel free to let me know if you have more concerns.


推荐阅读