【问题标题】:SQL Create Modified Record from ConditionSQL根据条件创建修改记录
【发布时间】:2021-11-10 06:52:00
【问题描述】:

我有下表:

id     activity     xuser     isDone
---------------------------------------
1      abc          tom       y
2      def          tom       n
3      hij          jeff      y
4      klm          jeff      n
5      nop          jeff      n

我希望得到以下结果:

nCol     tom      jeff
----------------------------
done     1        1
undone   1        2

如何在 SQL 语法中做到这一点?那我怎样才能把它转换成 linq 语法呢?
谢谢。

【问题讨论】:

  • 返回列(xuser、donecount、undocount)要灵活得多。
  • @jarlh,同意...如果像上面提到的那样交换列,你能告诉我语法吗?
  • xuser 不是静态列表时,您必须在SQL 中使用PIVOT,并且在LINQ 中没有等效项。

标签: sql linq .net-core


【解决方案1】:

如果你最终做了类似@jarlhsuggests in his answer 的事情,你可以通过或多或少这样的查询在 LINQ 中获得类似的 SQL 结果:

var xUserCounts = 
    from x in tableName
    group x by x.xuser into groupped
    select new 
    {
        User = groupped.Key,
        DoneCount = groupped.Select(y => y.IsDone).Sum(y => y == "y" ? 1 : 0),
        UndoneCount = groupped.Select(y => y.IsDone).Sum(y => y == "n" ? 1 : 0),
    };

【讨论】:

    【解决方案2】:

    返回列(xuser、donecount、undocount)更加灵活。

    做一个GROUP BY,用case表达式条件聚合

    select xuser,
           sum(case when isDone = 'y' then 1 else 0 end) as donecount,
           sum(case when isDone = 'n' then 1 else 0 end) as undonecount
    from tablename
    group by xuser
    

    (必须由其他人进行 linq 编码。)

    【讨论】:

    • 如果你愿意,我可以在你的答案中添加一个示例 LINQ 查询
    • @CamiloTerevinto,是的,请。也可以使用 linq 语法。
    • @CamiloTerevinto,把它写成一个单独的答案,我会赞成的!
    • @jarlh 和 Camilo Terevinto ....你们俩都很棒!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2018-06-20
    • 2018-11-29
    相关资源
    最近更新 更多