1

我的 SQL 语句如下:

SELECT Count(DISTINCT A.LM_PERSON_ID) AS HEAD_COUNT 
,A.LM_STATUS
,To_Char(A.LM_STATUS_CHANGE_DT,'YYYY') AS YEAR
,B.LM_COURSE_NAME AS COURSE_NAME

FROM LM_ENRLOLMENT A
,LM_COURSE_TBL B

WHERE A.LM_STATUS='COMP'
AND A.LM_COURSE_ID=B.LM_CI_ID                  

GROUP BY A.LM_STATUS_CHANGE_DT,LM_STATUS,B.LM_COURSE_NAME

我想显示的示例输出是:

COURSE_NAME      2010      2011     2012
   A              4         5        1
   B              2         1        1
   C              6         0        3
   D              1         1        2

但我面临的主要问题LM_STATUS_CHANGE_DT是动态数据。有没有人可以告诉我如何做到这一点?

4

1 回答 1

2

您没有指定您使用的 RDBMS,但您应该能够在所有版本中使用以下内容:

SELECT 
  B.LM_COURSE_NAME AS COURSE_NAME,
  count(DISTINCT case when To_Char(A.LM_STATUS_CHANGE_DT,'YYYY') = '2010' then A.LM_PERSON_ID end) as Year2010,
  count(DISTINCT case when To_Char(A.LM_STATUS_CHANGE_DT,'YYYY') = '2011' then A.LM_PERSON_ID end) as Year2011,
  count(DISTINCT case when To_Char(A.LM_STATUS_CHANGE_DT,'YYYY') = '2012' then A.LM_PERSON_ID end) as Year2012
FROM LM_ENRLOLMENT A
INNER JOIN LM_COURSE_TBL B
  ON A.LM_COURSE_ID=B.LM_CI_ID
WHERE A.LM_STATUS='COMP'
GROUP BY B.LM_COURSE_NAME

如果您使用的是具有该PIVOT功能的 RDBMS (SQL Server 2005+/Oracle 11g+),那么您的代码将类似于以下内容:

SELECT *
FROM
(
  SELECT DISTINCT B.LM_COURSE_NAME,
    To_Char(A.LM_STATUS_CHANGE_DT,'YYYY') As Year,
    A.LM_PERSON_ID
  FROM LM_ENRLOLMENT A
  INNER JOIN LM_COURSE_TBL B
    ON A.LM_COURSE_ID=B.LM_CI_ID
  WHERE A.LM_STATUS='COMP'
) src
PIVOT
(
  count(LM_PERSON_ID)
  for Year in ('2010', '2011', '2012')
) piv
于 2013-01-11T01:26:04.417 回答