我想以这种格式打印报告:(这些是样本值)
到目前为止,我能够做到这一点:
这是我的问题:
SELECT t.DisplayName,
ROUND((CAST(t.MarksObt AS FLOAT) / CAST(t.TotalMarks AS FLOAT) * 100), 0) AS Percentage,
t.EvaluationDate
FROM (SELECT u.DisplayName,
e.Id,
SUM(ea.QuestionMaxMarks) AS TotalMarks,
SUM(CASE WHEN ea.Achieve = 1 THEN ea.QuestionMaxMarks ELSE 0 END) AS MarksObt,
e.EvaluationDate
FROM Users u
JOIN Evaluation e
ON u.UserID = e.PhoneBankerId
JOIN EvaluationAnswer ea
ON e.Id = ea.EvaluationId
JOIN Question q
ON ea.QuestionId = q.Id
JOIN QuestionSection qs
ON q.SectionId = qs.Id
WHERE qs.[Type] = 1
AND e.Id > 31
AND ea.Achieve <> 3
GROUP BY e.Id, u.DisplayName, e.EvaluationDate) As t
非常感谢任何帮助。 感谢
答案 0 :(得分:1)
您需要使用PIVOT运算符。以下是基于Northwind数据库的示例,该数据库返回每月每个客户的订单总价值信息:
;WITH PivotData AS ( SELECT CustomerID, DATENAME(M,OrderDate) as Month, Freight FROM Orders)
SELECT CustomerID,
January,February,March,
April,May,June,
July,August,September,
October,November,December
FROM PivotData
PIVOT( SUM(Freight) FOR Month IN
(January,February,March,
April,May,June,
July,August,September,
October,November,December) ) AS P;
以下是我使用PIVOT运算符的查询的一般结构:
WITH PivotData AS
(
SELECT <grouping column>, <spreading column>, <aggregation column>
FROM <source table>
)
SELECT <select list>
FROM PivotData
PIVOT( <aggregate function >(<aggregation column>)
FOR <spreading column> IN (<distinct spreading values>) ) AS P;
在您的情况下,DisplayName是一个分组列,EvaluationDate的月份部分是一个传播列,而Percentage是一个聚合列。
答案 1 :(得分:1)
同样使用DECIMAL
而不是FLOAT
,浮点数据类型可能会给您带来意想不到的结果,因为它是近似数据类型,只应在使用近似值(如Pi值和质量)时使用地球等。
SELECT DisplayName
, CAST([JAN] AS VARCHAR(10))+ '%' AS [JAN]
, CAST([FEB] AS VARCHAR(10))+ '%' AS [FEB]
, CAST([MAR] AS VARCHAR(10))+ '%' AS [MAR]
, CAST([APR] AS VARCHAR(10))+ '%' AS [APR]
, CAST([MAY] AS VARCHAR(10))+ '%' AS [MAY]
, CAST([JUN] AS VARCHAR(10))+ '%' AS [JUN]
, CAST([JUL] AS VARCHAR(10))+ '%' AS [JUL]
, CAST([AUG] AS VARCHAR(10))+ '%' AS [AUG]
, CAST([SEP] AS VARCHAR(10))+ '%' AS [SEP]
, CAST([OCT] AS VARCHAR(10))+ '%' AS [OCT]
, CAST([NOV] AS VARCHAR(10))+ '%' AS [NOV]
, CAST([DEC] AS VARCHAR(10))+ '%' AS [DEC]
FROM
(
-- Your query here but get data in following format
SELECT DisplayName
,Percentage
,UPPER(LEFT(DATENAME(MONTH, EvaluationDate), 3)) AS EvaluationDate
FROM @TABLE
)t
PIVOT (AVG(Percentage)
FOR EvaluationDate
IN ([JAN],[FEB],[MAR],[APR],[MAY],[JUN],[JUL],[AUG],[SEP],[OCT],[NOV],[DEC])
)p