查询与计数记录的SQL相关

时间:2018-03-30 18:40:35

标签: sql asp.net-mvc database linq lambda

我有一个反馈表,我正在从客户那里获得反馈。他的表看起来像这样

ID  Service      Food      Behavior  Environment   OverallExprience  Flight    Date

1   Excellent   VeryGood    Good     Bad            Poor             EK0603  2018-03-29 
2   Excellent   Good      VeryGood   Excellent      Poor             EK0603  2018-03-29 

我想从员工那里搜索日期(从---到),并获得包含

的简要报告
  • 优秀的数量
  • 非常好的数量
  • 好的数量
  • 错误的数量
  • 穷人

所有给定的选项。 与给定数据一样,如果员工选择 2018-03-29 的日期范围为 2018-03-29

所以他可以看到像这样的记录

              Excellent        Very Good    Good     Bad     poor
Service         2                 0           0       0        0

Food            0                 1           1       0        0

Behavior        0                 1           1       0        0

Environment     1                 0           0       1        0

在这里需要帮助。如果答案是在LINQ查询

中将是明显的

1 个答案:

答案 0 :(得分:1)

因为你想将列转换为行,我想你需要一些UNION。 您可能需要为每个"类别"提供不同的查询,对于每个类别,您应该计算每个选项获得的票数。

请尝试此查询,它应该这样做:

SELECT MAX('Service') AS Category,
       COUNT(CASE WHEN t.Servive = 'Excellent' THEN 1 END) AS Excellent,
       COUNT(CASE WHEN t.Servive = 'VeryGood' THEN 1 END) AS Very_Good,
       COUNT(CASE WHEN t.Servive = 'Good' THEN 1 END) AS Good,
       COUNT(CASE WHEN t.Servive = 'Bad' THEN 1 END) AS Bad,
       COUNT(CASE WHEN t.Servive = 'Poor' THEN 1 END) AS Poor
  FROM table1 t
 WHERE t.Date BETWEEN '2018-03-29' AND '2018-03-29'
UNION
SELECT MAX('Food') AS Category,
       COUNT(CASE WHEN t.Food = 'Excellent' THEN 1 END) AS Excellent,
       COUNT(CASE WHEN t.Food = 'VeryGood' THEN 1 END) AS Very_Good,
       COUNT(CASE WHEN t.Food = 'Good' THEN 1 END) AS Good,
       COUNT(CASE WHEN t.Food = 'Bad' THEN 1 END) AS Bad,
       COUNT(CASE WHEN t.Food = 'Poor' THEN 1 END) AS Poor
  FROM table1 t
 WHERE t.Date BETWEEN '2018-03-29' AND '2018-03-29'
UNION
SELECT MAX('Behavior') AS Category,
       COUNT(CASE WHEN t.Behavior = 'Excellent' THEN 1 END) AS Excellent,
       COUNT(CASE WHEN t.Behavior = 'VeryGood' THEN 1 END) AS Very_Good,
       COUNT(CASE WHEN t.Behavior = 'Good' THEN 1 END) AS Good,
       COUNT(CASE WHEN t.Behavior = 'Bad' THEN 1 END) AS Bad,
       COUNT(CASE WHEN t.Behavior = 'Poor' THEN 1 END) AS Poor
  FROM table1 t
 WHERE t.Date BETWEEN '2018-03-29' AND '2018-03-29'
UNION
SELECT MAX('Environment') AS Category,
       COUNT(CASE WHEN t.Environment = 'Excellent' THEN 1 END) AS Excellent,
       COUNT(CASE WHEN t.Environment = 'VeryGood' THEN 1 END) AS Very_Good,
       COUNT(CASE WHEN t.Environment = 'Good' THEN 1 END) AS Good,
       COUNT(CASE WHEN t.Environment = 'Bad' THEN 1 END) AS Bad,
       COUNT(CASE WHEN t.Environment = 'Poor' THEN 1 END) AS Poor
  FROM table1 t
 WHERE t.Date BETWEEN '2018-03-29' AND '2018-03-29'