我正在尝试编写一个应该像下面的Linq查询一样运行的SQL语句。主要是,我想根据一定条件(Type ==“Check”)将一列(现金和支票)中的两列(价值*数量)相加。因此,如果Type为“Check”,则将值放入Check列,否则将其放入Cash列。
的LINQ:
from ac in m_DataContext.acquisitions
join ai in m_DataContext.acquireditems on ac.Identifier equals ai.AcquisitionIdentifier
group ai by ac.SessionIdentifier into g
select new
{
SessionIdentifier = g.Key,
Cash = g.Where(ai => ai.Type != "Check").Sum(ai => (double?)ai.Value * (int?)ai.Quantity) ?? 0,
Check = g.Where(ai => ai.Type == "Check").Sum(ai => (double?)ai.Value * (int?)ai.Quantity) ?? 0,
CheckQuantity = g.Where(ai => ai.Type == "Check").Sum(ai => (int?)ai.Quantity) ?? 0
};
SQL:
SELECT a.SessionIdentifier, a.Checks as CheckQuantity, ???? as Cash, ???? as Check
FROM Acquisitions ac
INNER JOIN AcquiredItems ai ON ai.AcquisitionIdentifier = ac.Identifier
GROUP BY a.SessionIdentifier
这可能吗?
答案 0 :(得分:2)
你可以这样做:
select sum(case when type = 'cash' then Value * Quantity else 0 end) as Cash,
sum(case when type = 'check' then Value * Quantity else 0 end) as Check
from ...