2009-10-05 58 views
0

我正在尝试编写一个应该像下面的Linq查询一样运行的SQL语句。主要是,我想根据一定的条件(Type ==“Check”)将两列(现金和支票)列出一列(值*数量)。因此,如果类型是“检查”,则将该值放入“检查”列中,否则将其放入“现金”列中。如果你可以在Linq中做到这一点,总是可以在SQL中做一些事情吗?

的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 

这可能吗?

回答

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 ... 
+1

如果这是一个MS SQL2005及以上的,你也可以使用PIVOT关键字http://msdn.microsoft.com/en-us/library/ms177410。 ASPX – 2009-10-05 18:20:58

相关问题