我想知道是否有办法找到已计算的派生列的总和到新列中。
Employee_KT_State
--------------------------------------------------------
Emp_Id Team KT_State Left_Org
----------------------------------------------------------
101 Orange In Progress 2016
102 Red Complete 2016
103 Orange Complete N
104 Green In Progress N
105 Orange Not Started N
106 Green Not Started 2015
107 Red In Progress N
108 Red Complete N
109 Green Complete N
-----------------------------------------------------------
SELECT
SUM(if (KT_State = 'In Progress' AND Team = 'Red', 1, 0)) AS 'Red In Progress Count',
SUM(if (KT_State = 'In Progress' AND Team = 'Green', 1, 0)) AS 'Green In Progress Count',
SUM(if (KT_State = 'In Progress' AND Team = 'Orange', 1, 0)) AS 'Orange In Progress Count'
SUM(if (KT_State = 'Complete' AND Team = 'Green', 1, 0)) AS 'Green Complete Count'
FROM
Employee_KT_State
我试图添加绿色进行中和完成计数。我可以直接使用从第2和第4列派生的计数,而不是使用具有不同if条件的另一个SUM吗?
something like -
SELECT
SUM(if (KT_State = 'In Progress' AND Team = 'Red', 1, 0)) AS 'Red In Progress Count',
SUM(if (KT_State = 'In Progress' AND Team = 'Green', 1, 0)) AS 'Green In Progress Count',
SUM(if (KT_State = 'In Progress' AND Team = 'Orange', 1, 0)) AS 'Orange In Progress Count'
SUM(if (KT_State = 'Complete' AND Team = 'Green', 1, 0)) AS 'Green Complete Count',
'Green In Progress Count' + 'Green Complete Count' AS ' Green In-Progress and Complete Count' --> Will this yield me results??
FROM
Employee_KT_State
感谢任何帮助。
答案 0 :(得分:2)
在MySQL中,您可以将代码简化为:
SELECT SUM(KT_State = 'In Progress' AND Team = 'Red') AS `Red In Progress Count`,
SUM(KT_State = 'In Progress' AND Team = 'Green') AS `Green In Progress Count`,
SUM(KT_State = 'In Progress' AND Team = 'Orange') AS `Orange In Progress Count`,
SUM(KT_State = 'Complete' AND Team = 'Green') AS `Green Complete Count`,
FROM Employee_KT_State;
要获得两个额外的列,您需要明确拥有SUM()
表达式。
请注意,我更改了列名以使用列别名的反引号。仅对字符串和日期常量使用单引号。
答案 1 :(得分:0)
使用子查询
SELECT t.*,
`Green In Progress Count` + `Green Complete Count`
As ` Green In-Progress and Complete Count`
FROM (
SELECT x As `Green In Progress Count`,
2* x As `Green Complete Count`
FROM Employee_KT_State
) t
| Green In Progress Count | Green Complete Count | Green In-Progress and Complete Count |
|-------------------------|----------------------|--------------------------------------|
| 1 | 2 | 3 |
| 2 | 4 | 6 |
| 3 | 6 | 9 |
简化演示:http://sqlfiddle.com/#!9/b7ddd8c/2
apollo-angular