我需要创建一个Analyze数据表,将其放在c#中的listview中。这是我的问题:
SELECT CL.CLIENT_CODE, CL.CLIENT_NAME,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 1, COUNT(CL.CLIENT_CODE), '') AS MONTH1,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 2, COUNT(CL.CLIENT_CODE), '') AS MONTH2,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 3, COUNT(CL.CLIENT_CODE), '') AS MONTH3,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 4, COUNT(CL.CLIENT_CODE), '') AS MONTH4,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 5, COUNT(CL.CLIENT_CODE), '') AS MONTH5,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 6, COUNT(CL.CLIENT_CODE), '') AS MONTH6,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 7, COUNT(CL.CLIENT_CODE), '') AS MONTH7,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 8, COUNT(CL.CLIENT_CODE), '') AS MONTH8,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 9, COUNT(CL.CLIENT_CODE), '') AS MONTH9,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 10, COUNT(CL.CLIENT_CODE), '') AS MONTH10,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 11, COUNT(CL.CLIENT_CODE), '') AS MONTH11,
IIF (EXTRACT(MONTH FROM J.CJOB_ASSIGNED) = 12, COUNT(CL.CLIENT_CODE), '') AS MONTH12
FROM CLIENTS CL INNER JOIN CJOBS J ON (CL.CLIENT_ID = J.CLIENT_ID)
GROUP BY CL.CLIENT_CODE, CL.CLIENT_NAME, EXTRACT(MONTH FROM J.CJOB_ASSIGNED)
这个查询的结果是,按月分析了数据,但是对于分成许多不同数据行的每个客户端,它们并不是连续的:
结果如我所愿 )。
答案 0 :(得分:0)
每月获得单独行的原因是因为这就是您所要求的。您按月分组,因此每个月都有自己的行。
要获得您想要的结果,您需要将查询转换为首先获得每月和客户所需的计数,然后才能转移'那个月到每月的列数。
对于第一部分,您需要一个类似的查询:
select client_id, extract(month from cjob_assigned), count(*)
from cjobs
group by client_id, extract(month from cjob_assigned)
现在要将其转换为每个客户端一行和每月一列的数据透视表,您需要为每个客户端执行此查询12次。为了使这更容易,我们可以使用common table expression,因此我们不必每次都重复整个选择(作为简化:CTE可以被视为内联视图)。
最终查询变为:
with jcm (client_id, monthnr, jobcount) as (
select client_id, extract(month from cjob_assigned), count(*)
from cjobs
group by client_id, extract(month from cjob_assigned)
)
select client_code, client_name,
(select jobcount from jcm where jcm.client_id = clients.client_id and jcm.monthnr = 1) as month1,
(select jobcount from jcm where jcm.client_id = clients.client_id and jcm.monthnr = 2) as month2,
-- ... add months 3 - 11
(select jobcount from jcm where jcm.client_id = clients.client_id and jcm.monthnr = 12) as month12
from clients
顺便说一句:你可能也想考虑包括年份(虽然这确实让事情变得更复杂)。