编写sql查询以包装行数据

时间:2013-01-08 15:03:44

标签: sql-server-2008

我有一个要求只在使用SQL查询时显示数据。 表名:EMP_DEPT

    DEPARTMENT  |   EMPLOYEE    |   SALARY
    DEPT1       |   ABC         |   20000
    DEPT1       |   MNO         |   30000
    DEPT1       |   XYZ         |   25000
    DEPT2       |   DEF         |   42000
    DEPT2       |   GHI         |   35000
    DEPT3       |   JKL         |   36000

以及我期待的结果

    DEPARTMENT  |   EMPLOYEE    |   SALARY
    DEPT1       |   ABC         |   20000
                |   MNO         |   30000
                |   XYZ         |   25000
    DEPT2       |   DEF         |   42000
                |   GHI         |   35000
    DEPT3       |   JKL         |   36000

这样打印的选择查询是什么。使用MSSQL作为DB

提前致谢。

2 个答案:

答案 0 :(得分:3)

试试这个。您可以根据需要使用''NULL。也许您想按EMPLOYEE分区订购。

SELECT 
   CASE WHEN rn = 1 THEN DEPARTMENT ELSE '' END  as DEPARTMENT,
   EMPLOYEE,
   SALARY
FROM
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY DEPARTMENT ORDER BY (SELECT 1)) rn
   FROM EMP_DEPT
) A

答案 1 :(得分:1)

您可以使用ROW_NUMBER()来识别部门第一次出现,并使用CASE语句显示部门名称或空白。

SELECT
    CASE
        WHEN ROW_NUMBER() OVER(PARTITION BY DEPARTMENT ORDER BY EMPLOYEE) = 1
        THEN DEPARTMENT
        ELSE ''
    END AS DEPARTMENT,
    EMPLOYEE,
    SALARY
FROM EMP_DEPT
ORDER BY EMP_DEPT.DEPARTMENT, EMPLOYEE