簡體   English   中英

LINQ復雜查詢

[英]LINQ Complex Query

我有一個復雜的SQL查詢,需要在LINQ中運行。 我想知道是否可以使用LINQ做到這一點,或者我還需要其他東西嗎? 請你幫助我好嗎? 謝謝。

SELECT DISTINCT_PLAY_COUNT,SUM(1) AS CLIENT_COUNT FROM
    (SELECT CLIENT_ID,SUM(1) AS DISTINCT_PLAY_COUNT FROM
        (SELECT CLIENT_ID,SONG_ID FROM PIEXHIBIT 
        WHERE PLAY_TS >= '10/08/2016 00:00:00' AND PLAY_TS <= '10/08/2016 23:59:59'
        GROUP BY CLIENT_ID,SONG_ID
    )
    GROUP BY CLIENT_ID
)
GROUP BY DISTINCT_PLAY_COUNT 

這是我的課程以及到目前為止我所取得的成就;

    public class Exhibit
    {
        public string PLAY_ID { get; set; }
        public Int32 SONG_ID { get; set; }
        public Int32 CLIENT_ID { get; set; }
        public DateTime PLAY_TS { get; set; }

    }

    var sql = from Exhibit row in Exhibit
                              where row.PLAY_TS >= DateTime.Parse("10/08/2016 00:00:00") && row.PLAY_TS <= DateTime.Parse("10/08/2016 23:59:59")
                              select new { row.CLIENT_ID, row.SONG_ID };
Exhibits
   .Where(t => t.PLAY_TS >= new DateTime(2016, 8, 10) && t.PLAY_TS < new DateTime(2016, 8, 11))
   .Select(t => new { t.CLIENT_ID, t.SONG_ID })
   .Distinct()
   .GroupBy(c => c.CLIENT_ID)
   .Select(c => c.Count())
   .GroupBy(g => g)
   .Select(g => new { DISTINCT_PLAY_COUNT = g.Key, CLIENT_COUNT = g.Count() })
   .ToList();

我認為這應該有效。

使用LINQ時,區分開總是有些棘手。 有可能的:

使用linq選擇“ distinct” (我偏愛重載equals方法,即使這可能不是正確的選擇。)

該鏈接提供了大量有關操作的建議。 “重復答案”線程也有一些不錯的建議。

我還建議您:

  1. PLAY_TS <='DD / MM / YYYY 23:59:59'

應該更改為

  1. PLAY_TS <'DD + 1 / MM / YYYY 00:00:00'

僅僅因為實際上有可能遇到一個毫秒級問題,而您在技術上尚未更改日期,因為毫秒級尚未達到999級。

我希望你明白我的意思。

我建議將其放在存儲過程中,而不要使用LINQ。 然后通過以下代碼執行存儲過程:

using (var conn = new SqlConnection(connString)) //Connection string in there
using (var command = new SqlCommand("ProcedureNameHere", conn) {
    CommandType = CommandType.StoredProcedure }) {
        conn.Open();
        command.ExecuteNonQuery();
}

這是我的建議。 GroupBy將自動為您提供我的代碼。

            var sqlDateTime = from Exhibit row in Exhibit.exhibits
                     where row.PLAY_TS >= DateTime.Parse("10/08/2016 00:00:00") && row.PLAY_TS <= DateTime.Parse("10/08/2016 23:59:59")
                     select new { cid = row.CLIENT_ID, songid = row.SONG_ID, date = row.PLAY_TS };

            var results = sqlDateTime.GroupBy(x => new { cid = x.cid, sid = x.songid })
                .Select(x => new { count = x.Count(), cid = x.Key.cid, sid = x.Key.sid }).ToList();  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM