【问题标题】:need to convert SQL CROSS JOIN into LINQ需要将 SQL CROSS JOIN 转换为 LINQ
【发布时间】:2014-09-27 10:05:07
【问题描述】:

我有两个表 table1 和 table2。每个表都包含一个带有 itemPrice 的列。我需要将两列加在一起。

下面的 SQL 查询返回正确的 SUM。

 SELECT SUM(item1+ item2) FROM 
(select SUM(t1.itemPrice) item1 from table1 t1 WHERE t1.userid=='jonh') tableA
CROSS JOIN
(select SUM(t2.itemPrice) item2 from table2 t2 WHERE t1.userid=='jonh') tableB

我不是偷懒,但是上面的查询有太多的 SUM 函数,我不知道从哪里开始编写 LINQ 查询。

谁能帮忙?

【问题讨论】:

    标签: join


    【解决方案1】:

    塞西,

    希望这会给你你想要的......

    from f in   (    
        from x in   (   from t1 in Table1 
                        where  t1.Userid.Equals("John") 
                        select new { Userid = t1.Userid }
                    ).Distinct() 
        select new {    item1 = (   from z in Table1 
                                    where z.Userid.Equals("John") 
                                    select z.ItemPrice ).Sum() ??0 ,
                        item2 = (   from z in Table2 
                                    where z.Userid.Equals("John") 
                                    select z.ItemPrice ).Sum() ??0 } 
                ) select new { total = f.item1 + f.item2 }
    

    如果一个表中没有“john”的记录,它会带回一个0并总结其他表。

    希望这会有所帮助。

    【讨论】:

    • 太棒了,效果很好!我永远不会让这个工作靠我自己。谢谢你。快速提问。一定有更短的方法来写这个,不是吗?它似乎很长。
    • @ceci,我不是 LINQ 专家,也许有更多经验的人可以提出更简洁的解决方案。
    • Ed,您在查询中添加了这个“??0”,如果它为空,我会假设它返回零。我尝试谷歌搜索,但找不到任何东西。你能解释一下它的用途吗?谢谢。
    • 您想要 TableA 和 TableB 的 ItemPrice 的总和,但是如果您在 TableA 中没有“john”的行,但在 TableB 中有他的行,那么您的结果将为空。这 ?? 0 表示如果 Null 返回 0。所以现在即使只有一个表包含 'John' 的行,您也会得到有效的结果。这是 Linq 处理 Null 时的常见问题。此 URL 将为您提供信息...google.com/…
    猜你喜欢
    • 2023-03-15
    • 2018-11-24
    • 2014-02-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多