我有3個表:交叉連接(樞軸)與含N-N的表值
TABLE MyColumn (
ColumnId INT NOT NULL,
Label VARCHAR(80) NOT NULL,
PRIMARY KEY (ColumnId)
)
TABLE MyPeriod (
PeriodId CHAR(6) NOT NULL, -- format yyyyMM
Label VARCHAR(80) NOT NULL,
PRIMARY KEY (PeriodId)
)
TABLE MyValue (
ColumnId INT NOT NULL,
PeriodId CHAR(6) NOT NULL,
Amount DECIMAL(8, 4) NOT NULL,
PRIMARY KEY (ColumnId, PeriodId),
FOREIGN KEY (ColumnId) REFERENCES MyColumn(ColumnId),
FOREIGN KEY (PeriodId) REFERENCES MyPeriod(PeriodId)
)
提供了一種真正的值時僅創建myvalue的的行。
我希望我的以表格方式的結果,如:
Column | Month 1 | Month 2 | Month 4 | Month 5 |
Potatoes | 25.00 | 5.00 | 1.60 | NULL |
Apples | 2.00 | 1.50 | NULL | NULL |
我已經成功地創建了一個交叉聯接:
SELECT
MyColumn.Label AS [Column],
MyPeriod.Label AS [Period],
ISNULL(MyValue.Amount, 0) AS [Value]
FROM
MyColumn CROSS JOIN
MyPeriod LEFT OUTER JOIN
MyValue ON (MyValue.ColumnId = MyColumn.ColumnId AND MyValue.PeriodId = MyPeriod.PeriodId)
或者,在LINQ:
from p in MyPeriods
from c in MyColumns
join v in MyValues on new { c.ColumnId, p.PeriodId } equals new { v.ColumnId, v.PeriodId } into values
from nv in values.DefaultIfEmpty()
select new {
Column = c.Label,
Period = p.Label,
Value = nv.Amount
}
並看到如何在linq中創建數據透視表(here或here):
(假設MyDatas是與以前的查詢結果的視圖):
from c in MyDatas
group c by c.Column into line
select new
{
Column = line.Key,
Month1 = line.Where(l => l.Period == "Month 1").Sum(l => l.Value),
Month2 = line.Where(l => l.Period == "Month 2").Sum(l => l.Value),
Month3 = line.Where(l => l.Period == "Month 3").Sum(l => l.Value),
Month4 = line.Where(l => l.Period == "Month 4").Sum(l => l.Value)
}
但我想找到一種方法來創建一個結果,如果可能的話,MONTH1,...特性的動態。
注:
from c in MyDatas
group c by c.Column into line
select new
{
Column = line.Key,
Months =
from l in line
group l by l.Period into period
select new
{
Period = period.Key,
Amount = period.Sum(l => l.Value)
}
}
我可以工作,是 – tbolon 2010-04-30 08:34:46