选择查询linq中的case语句的datediff

时间:2017-03-04 11:12:26

标签: sql sql-server linq

在linq查询中选择case语句。

这是关于sql的查询:

  select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
 Sum([Order].OrderSubtotal)
 else 
 case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
 Sum([Order].OrderSubtotal)/
  (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
 end 
 end as 'Account Value' from [order] where And Account.ID = @Act_ID 

我在这里尝试代码:

 var query = _orderRepository.Table;
        query = query.Where(o => o.AccountId == accountId);

在查询中我得到了我的价值。

查询语句后我该怎么写? 我如何使用linq写case语句???

1 个答案:

答案 0 :(得分:0)

@Manoj,可能是以下代码可以帮到你。此示例C#项目可以解决您遇到的问题。

using System;
using System.Collections.Generic;
using System.Linq;

namespace DateDiffIssue
{
    class Program
    {
        static void Main(string[] args)
        {

            // Preparing data
            var data = new Order[] {
                new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
                new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
                new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
            };

            // Selection
            var selected = (from item in data
                            let accountData = data.Where(w => w.AccountID == 1)
                            let minDate = accountData.Min(m => m.CreatedOnUtc).Date
                            let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
                            let isSameDate = minDate == maxDate
                            let basedOn30Days = (maxDate - minDate).TotalDays / 30
                            let isInside30Days = (int)basedOn30Days == 0
                            let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
                            select new
                            {
                                AccountValue = isSameDate ? accountDataSum :
                                                isInside30Days ? accountDataSum :
                                                accountDataSum / basedOn30Days
                            }).Distinct();

            // Print each order
            selected.ToList().ForEach(Console.WriteLine);

            // Wait for key
            Console.WriteLine("Please press key");
            Console.ReadKey();
        }
    }

    internal class Order
    {
        public int AccountID { get; set; }
        public DateTime CreatedOnUtc { get; set; }
        public int OrderSubtotal { get; set; }
    }
}