我有一个看起来像这样的表:
Associate Pay_Code Hours Site Date Week Year
Bill REG 8.0 US 3/3/2014 10 2014
Bill REG 8.0 US 3/4/2014 10 2014
Bill REG 8.0 US 3/5/2014 10 2014
Bill REG 8.0 US 3/6/2014 10 2014
Bill VTO 6.0 US 3/7/2014 10 2014
Bill PERS 2.0 US 3/7/2014 10 2014
Mary REG 8.0 Canada 3/3/2014 10 2014
Mary REG 8.0 Canada 3/4/2014 10 2014
Mary REG 8.0 Canada 3/5/2014 10 2014
Mary REG 8.0 Canada 3/6/2014 10 2014
Mary REG 6.0 Canada 3/7/2014 10 2014
Mary PERS 2.0 Canada 3/7/2014 10 2014
Fred REG 8.0 England 3/3/2014 10 2014
Fred REG 8.0 England 3/4/2014 10 2014
Fred REG 8.0 England 3/5/2014 10 2014
Fred REG 8.0 England 3/6/2014 10 2014
Fred REG 8.0 England 3/7/2014 10 2014
Wilma REG 8.0 Jamaica 3/3/2014 10 2014
Wilma REG 8.0 Jamaica 3/4/2014 10 2014
Wilma REG 8.0 Jamaica 3/5/2014 10 2014
Wilma REG 8.0 Jamaica 3/6/2014 10 2014
Wilma REG 8.0 Jamaica 3/7/2014 10 2014
Wilma OT 5.0 Jamaica 3/7/2014 10 2014
Jethro REG 8.0 Africa 3/3/2014 10 2014
Jethro REG 8.0 Africa 3/4/2014 10 2014
Jethro REG 8.0 Africa 3/5/2014 10 2014
Jethro REG 8.0 Africa 3/6/2014 10 2014
Jethro REG 8.0 Africa 3/7/2014 10 2014
Jethro OT 8.0 Africa 3/7/2014 10 2014
Frank REG 8.0 Iraq 3/3/2014 10 2014
Frank PERS 8.0 Iraq 3/4/2014 10 2014
Frank PERS 8.0 Iraq 3/5/2014 10 2014
Frank VACP 8.0 Iraq 3/6/2014 10 2014
Frank VACP 8.0 Iraq 3/7/2014 10 2014
此查询:
SELECT Pay_Code, Site, SUM(Hours), Week(Date,4), YEAR(Date)
FROM table
GROUP BY Pay_Code, Site, YEAR(Date), WEEK(Date,4)
给我:
Pay Code Site Sum of Hours Week Year
OT Africa 8.0 10 2014
Jamaica 5.0 10 2014
PERS Canada 2.0 10 2014
Iraq 16.0 10 2014
US 2.0 10 2014
REG Africa 40.0 10 2014
Canada 38.0 10 2014
England 40.0 10 2014
Iraq 8.0 10 2014
Jamaica 40.0 10 2014
US 32.0 10 2014
VACP Iraq 16.0 10 2014
VTO US 6.0 10 2014
我想要做的是对Pay_Code组进行分组,以便进一步汇总它们。看起来像这样:
Pay Code2 Pay Code Site Sum of Hours Week Year
OT OT Africa 8.0 10 2014
Jamaica 5.0 10 2014
Paid Shrink PERS Canada 2.0 10 2014
Iraq 16.0 10 2014
US 2.0 10 2014
VACP Iraq 16.0 10 2014
REG REG Africa 40.0 10 2014
Canada 38.0 10 2014
England 40.0 10 2014
Iraq 8.0 10 2014
Jamaica 40.0 10 2014
US 32.0 10 2014
Unpaid Shrink VTO US 6.0 10 2014
目标是按周按站点报告Pay_Code2字段,但表中不存在Pay_Code2字段。现在我查询大量数据并使用数据透视表对我的行进行分组。如果可能的话,我想在MySQL中这样做。
答案 0 :(得分:1)
听起来您正在尝试根据PayCode值创建新类别。你可以尝试这样的事情:
SELECT CASE
WHEN Pay_Code = 'OT' THEN 'OT'
WHEN Pay_Code IN ('VACP','PERS') THEN 'Paid Shrink'
WHEN Pay_Code = 'REG' THEN 'REG'
WHEN Pay_Code IN ('VTO','LOA','BER') THEN 'Unpaid Shrink'
ELSE 'Unknown'
END as PayCode_2
,YEAR(Date), WEEK(Date,4), SUM(Hours), Site, Pay_Code
FROM table
GROUP BY PayCode_2, Pay_Code, Site, YEAR(Date), WEEK(Date,4)