将一个SQL列划分为带有标题的子组

时间:2015-02-19 12:39:31

标签: sql sql-server select telerik radcombobox

我有两张桌子

STATUS

SNO | STATUS | DEPARTMENT_ID

1   In progress      1
2    Assigned        2
3     Quoted         2
4   Development      3

DEPARTMENTS

SNO | DEPARTMENT |

1     DESIGNING
2     MARKETING
3     PRODUCTION

现在我希望使用SQL存储过程

这样的结果
Some Custom Column Name | DEPARTMENT_ID

DESIGNING                      -
In Progress                    1
MARKETING                      -
Assigned                       2
Quoted                         2
PRODUCTION                     -
Development                    3

自定义列将用于填充Telerik RadComboBox,其中DESIGNING,MARKETING和PRODUCTION充当状态之间的分隔符。

3 个答案:

答案 0 :(得分:0)

Select Department, -1 from Department_Table
Union
Select StatusName, Department_ID from Status_Table

请详细说明您的问题,以便我们提供更好的答案。目前,您似乎只想返回两个表的连接数据。

答案 1 :(得分:0)

通常,这种类型的操作在应用程序级别更容易完成。您可以使用union allorder by在SQL中执行此操作,但是:

select status as CustomColumnName, department
from ((select s.status, d.department, 1 as ordering
       from status s join
            departments d
            on s.department_id = d.sno
      ) union all
      (select d.department, NULL, 0 as ordering
       from departments d
      )
     ) dd
order by CustomColumnName, ordering;

注意:这会将-视为NULL

答案 2 :(得分:0)

试试这个。其他样本数据还可以吗?

DECLARE @STATUS TABLE (
    SNO INT
    ,[STATUS] VARCHAR(50)
    ,DEPARTMENT_ID INT
    )

INSERT INTO @STATUS
VALUES (1,'In progress' ,1)
    ,(2,'Assigned',2)
    ,(3,'Quoted',2)
    ,(4,'Development',3)

DECLARE @DEPARTMENT TABLE (SNO INT,DEPARTMENT VARCHAR(50))

INSERT INTO @DEPARTMENT
VALUES (    1,'DESIGNING'),(2,'MARKETING')
    ,(3,'PRODUCTION')
    --select * from @STATUS
    --select * from @DEPARTMENT
    ;

WITH CTE
AS (
    SELECT DEPARTMENT [CustomeColumn]
        ,'-' DEPARTMENT_ID
        ,sno
    FROM @DEPARTMENT

    UNION ALL

    SELECT [STATUS]
        ,cast(DEPARTMENT_ID AS VARCHAR(10))
        ,(
            SELECT sno
            FROM @DEPARTMENT
            WHERE sno = a.DEPARTMENT_ID
            )
    FROM @STATUS A
    )
SELECT *
FROM CTE
ORDER BY sno