使用包含值的n-n表进行交叉连接(pivot)

时间:2008-12-16 12:31:16

标签: sql linq pivot cross-join

我有3张桌子:

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中创建一个支点(herehere):

(假设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,...属性动态。

注意:导致n + 1查询的解决方案:

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)
        }
}

2 个答案:

答案 0 :(得分:2)

查看此问题的接受答案:

Dynamic SQL to generate column names?

答案 1 :(得分:0)

您是否有日历期(1-12)或会计期间(1-12或1-13,具体取决于年份)?

你只会将报告运行一年吗?

如果可能的话,我会将PeriodId分成两个字段,分别为Year&期。这样可以更轻松地选择特定年份。查询会更简单。