我正在使用托管的SQL 2008数据库(因此无法创建表或修改值),并希望从同一列中分割两个数字以获得单个百分比答案。值将输入到同一列(TA_ANS_ANSWER
),但输入的值基于另一个字段,即问题(TA_ANS_QUESTION
)。
例如这个月;
第一个问题 - “电子学习用户列表中的总编号承包商” - 答案输入'430'。
第二个问题 - “电子学习总承包商导入报告” - 答案输入'357' 我需要为上述值获得83%的值。
我需要在填充答案时为每个月计算一个百分比值。 下面的查询给出了基本查询,该查询返回前一个MONTH(例如Nov)的名称,PPM ID和Answer(例如430)。我可以修改它来返回两行,每个问题回答1,但我只想要一行包含Month,PPM ID和Percentage计算。
道歉,如果答案是盯着我,但任何帮助都会受到高度赞赏。
SELECT CONVERT(varchar(3), TA_DUE_DATE-28, 100) AS MONTH,
TA_TASK_ID AS PPM,
F_TASK_ANS.TA_ANS_ANSWER AS ANSWER
FROM F_TASK_ANS
INNER JOIN F_TASKS
ON F_TASK_ANS.TA_ANS_FKEY_TA_SEQ = F_TASKS.TA_SEQ
WHERE TA_ANS_ANSWER <> ''
AND F_TASKS.TA_FKEY_CTR_SEQ = 126
AND F_TASK_ANS.TA_ANS_QUESTION LIKE '%Total No. Contractors on e-learning User List%'
AND (TA_HIST_STATUS IS NULL OR TA_HIST_STATUS = 'COMPLETE')
AND TA_TASK_ID LIKE '%6025'
AND TA_DUE_DATE >= GETDATE()-360
AND TA_DUE_DATE <= GETDATE()+7
ORDER BY PPM
答案 0 :(得分:0)
您正在寻找的是一个支点。这可以使用PIVOT关键字完成,也可以使用GROUP BY和MIN(CASE WHEN ... END)手动完成。有关更多示例,请查看标有“pivot”的其他答案。
SELECT CONVERT(varchar(3), TA_DUE_DATE-28, 100) AS MONTH,
TA_TASK_ID AS PPM,
MIN(CASE WHEN F_TASK_ANS.TA_ANS_QUESTION LIKE '%Total No. Contractors on e-learning inducted report%' THEN F_TASK_ANS.TA_ANS_ANSWER END) +0.0
/ MIN(CASE WHEN F_TASK_ANS.TA_ANS_QUESTION LIKE '%Total No. Contractors on e-learning User List%' THEN F_TASK_ANS.TA_ANS_ANSWER END)
AS PERCENTAGE
FROM F_TASK_ANS
INNER JOIN F_TASKS
ON F_TASK_ANS.TA_ANS_FKEY_TA_SEQ = F_TASKS.TA_SEQ
WHERE TA_ANS_ANSWER <> ''
AND F_TASKS.TA_FKEY_CTR_SEQ = 126
AND (F_TASK_ANS.TA_ANS_QUESTION LIKE '%Total No. Contractors on e-learning User List%' OR
(F_TASK_ANS.TA_ANS_QUESTION LIKE '%Total No. Contractors on e-learning inducted report%')
AND (TA_HIST_STATUS IS NULL OR TA_HIST_STATUS = 'COMPLETE')
AND TA_TASK_ID LIKE '%6025'
AND TA_DUE_DATE >= GETDATE()-360
AND TA_DUE_DATE <= GETDATE()+7
GROUP BY CONVERT(varchar(3), TA_DUE_DATE-28, 100),TA_TASK_ID
答案 1 :(得分:0)
一个可能的答案是使用公用表表达式(CTE)。像这样:
;with TotalOnELearningList (Month, TaskID, NumberOnList) as
(
select
convert(varchar(3), ta_due_date - 28, 100) as month,
ta_task_id,
f_task_ans.ta_ans_answer
from ...
),
TotalOnInductedReport (Month, TaskID, NumberInductedReport) as
(
...
),
select
case NumberInductedReport when 0 then 0 else NumberOnList / NumberInductedReport * 100 end as 'Percent',
...
from TotalOnELearningList
inner join TotalOnIndutedReport
on...