【问题标题】:sql having statement with distinct count of a fieldsql 具有具有不同字段计数的语句
【发布时间】:2018-01-15 01:29:13
【问题描述】:

请我在这方面需要你的帮助 我如何将此 sql 解释为 linq:

SELECT  FK_ClassId, LectureDays
FROM tbl_TimeTables
WHERE (FK_ClassId = 11)
group by fk_classid, lecturedays
having count(distinct Period) < 7

任何帮助将不胜感激谢谢 蒂姆

【问题讨论】:

  • 看看这是否对您有帮助,风险自负:):SQL to LINQ Tool
  • 感谢 Brien 的回复,很遗憾我的 Linqer 试用期已过,我没有办法购买付费版,请有其他建议。

标签: sql linq count distinct having


【解决方案1】:

应该是这样的 (group by id, count period, apply where子句, project result)

var query = from timetable in context.TimeTables
            where timetable.ClassId == classId
            group timetable by new
            {
                timetable.ClassId,
                timetable.Period
            } into groupings
            let counter = groupings
                .Select(p => p.Period)
                .Distinct()
                .Count()
            where counter < 7
            select new
            {
                ClassId = groupings.Key.ClassId,
                Days = from grouping in groupings
                       select grouping.LectureDays
            };

【讨论】:

  • 嗨,丹,感谢您的回复,请问我在哪里检查 WHERE (FK_ClassId = 11)。谢谢
  • 理想情况下,您应该使用查询将其作为标准传递给您的函数,但这在很大程度上取决于您希望如何使用查询。与此同时,我已经更新了我的答案
  • 嗨,丹,感谢您的回复,根据我发布的 sql 查询,实际上我期望的结果通常应该给出 ClassId = 11 和 Days = 5,但它给了我一系列答案,但是按 11 的 classid 对它们进行分组,即当我使用 linqpad 时
  • 恐怕我不太明白。我的回答到底能解决你的问题吗?
  • 嗨,丹,感谢您的帮助,我很想向您展示我要解释的内容的图片,以便您完全理解。同时,有没有直接的方法来实现我的 sql 查询?
【解决方案2】:

感谢您为我指明了正确的方向,对不起,我有一段时间没有回复了,太忙了。 在查看了您的解决方案后,我有时间玩它,下面为我做了:

from t in Tbl_TimeTables 
where t.FK_ClassId == 11
        group t by new
        {
            t.FK_ClassId,
            t.LectureDays
        } into groupings
        let counter = groupings
            .Select(p => p.Period)
            .Distinct()
            .Count()
        where counter < 7
        select new
        {
            ClassId = groupings.Key.FK_ClassId,
            Days = (from grouping in groupings
                   select grouping.LectureDays).Distinct()
        }

我只需将组键更改为 Lecturedays 而不是 period,这会删除我得到的一系列结果,只得到一个结果。 非常感谢丹

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多