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
這可能嗎?
如果這是一個MS SQL2005及以上的,你也可以使用PIVOT關鍵字http://msdn.microsoft.com/en-us/library/ms177410。 ASPX – 2009-10-05 18:20:58