如何从LINQ实现SQL Pivot语句

时间:2017-10-06 20:22:30

标签: sql sql-server entity-framework linq entity-framework-core

我希望从LINQ获得以下SQL语句。我不确定是否可能?有人可以就此提出建议吗?

SELECT *
FROM (
    SELECT CONVERT(VARCHAR, (DATEADD(WEEK, DATEDIFF(WEEK, 0, S.SampleDrawn), 0)), 101) [Date], [Range] =
        CASE 
            WHEN ProbBacteremia >= 0 AND ProbBacteremia < 0.50 THEN 'Low'
            WHEN ProbBacteremia >= 0.50 AND ProbBacteremia < 0.75 THEN 'Med' 
            ELSE 'High'
        END
    FROM Result.Calculation C INNER JOIN Data.SampleSet S ON C.SampleSetID = S.ID  WHERE  S.SampleDrawn >= DATEADD(WEEK,-1,GETDATE())) o
    PIVOT
    (
        COUNT(o.[Range])
        FOR [Range] IN (
        [Low], [Med], [High])
    ) pt
    ORDER BY [Date]

以上查询的结果如下

Date        Low Med High
09/04/2017  370 174 175
09/11/2017  764 352 389
09/18/2017  759 384 360
09/25/2017  765 385 404
10/02/2017  115 48  56

请注意,上述日期已按周分组。 IE浏览器。 09 / 04,09 / 11,09 / 18等我做了很多研究,但我发现只按周数分组。

这是我想出的LINQ,它将返回以下结果集。

data = (from a in context.Calculations
                             where a.SampleSet.SampleDrawn >= dtStart && (isDeptFilter || a.SampleSet.Department == location)
                             group a by new { Text = RangeProvider(a.ProbBacteremia * 100, riskCats), Date = a.SampleSet.SampleDrawn.Date } into groupedData
                             orderby groupedData.Key.Date ascending
                             select new { Value = groupedData.Count(), Text = groupedData.Key.Text, Date = groupedData.Key.Date.ToShortDateString() }).ToList();

public static string RangeProvider(int value)
        {
            if (value > 0 && value <= 25)
            { return "Low"; }
            if (value > 25 && value <= 75)
            { return "Medium"; }
            if (value > 75 && value <= 90)
            { return "High"; }
            else
            { return "Very High"; }
        }

obver LINQ的结果数据集是

Date        Text Value
09/04/2017  Low  65
09/04/2017  Med  80
09/04/2017  High 40
09/05/2017  Low  30
10/05/2017  Med  50
10/05/2017  High 44

希望这能解释我想要实现的目标。请有人帮我这个吗?

2 个答案:

答案 0 :(得分:0)

作为一种解决方法,我使用了Entity Framework Core的“ FromSQL ”方法来执行我的存储过程,该过程负责处理所有GROUP BY。

答案 1 :(得分:0)

你可以使用它。

data = (from a in context.Calculations
             where a.SampleSet.SampleDrawn >= dtStart && (isDeptFilter || a.SampleSet.Department == location)
             group a by new { Text = RangeProvider(a.ProbBacteremia * 100, riskCats), Date = a.SampleSet.SampleDrawn.Date } into groupedData
             orderby groupedData.Key.Date ascending
             select new { 
                 Date = groupedData.Key.Date.ToShortDateString() ,
                 Low = ( groupedData.Key.Text =="Low" )?groupedData.Count() : 0,
                 Medium = ( groupedData.Key.Text =="Medium" )?groupedData.Count() : 0,
                 High = ( groupedData.Key.Text =="High" )?groupedData.Count() : 0,
                 VeryHigh = ( groupedData.Key.Text =="Very High" )?groupedData.Count() : 0
             }).ToList();