先生,下面是我的SQL查询,后面是两个查询结果& 所需输出。
正如您在结果图片上看到的那样,我从执行以下查询获得此输出。
必需输出的第二张图片。我需要以该格式显示输出。由于第一部门的名称应该在顶部和以下项目详细信息对应于该部门。应该为每个部门重复相同的周期。
我该如何实现这个目标?
SQL代码:
DECLARE @ColName varchar(20)=null,
@Query varchar(MAX)=null,
@DepartmentName varchar(50)=null,
@deptt_code varchar(4)=null,
@DistrictId varchar(4)='0001',
@Deptt_Id char(4)=null,
@stYear varchar(4)=null,
@cYear varchar(4)=null,
@yr varchar(9)='2017-2018',
@tno int
BEGIN
set @stYear = SUBSTRING(@yr,0,5);
set @cYear = SUBSTRING(@yr,6,4);
--CREATE DYNAMIC TABLE WITH COLs
DECLARE @DepartmentTable table
(
department_name varchar(50),
department_code varchar(4)
);
DECLARE @ProjectTable table
(
project_name varchar(130),
project_code varchar(15),
department_code varchar(4),
department_name varchar(50),
district_code varchar(4),
district_name varchar(30),
tehsil_code varchar(6),
tehsil_name varchar(30),
service_code varchar(3),
[service_name] varchar(30),
sector_code varchar(3),
sector_name varchar(30),
project_start_year varchar(8),
project_compl_year varchar(8),
financial_year varchar(9)
);
--Insert into Department Table
INSERT INTO @DepartmentTable (department_code, department_name)
select deptt_code,deptt_name+'('+ RTRIM(LTRIM(deptt_short))+')' as dept_name from m_Department
where deptt_code in (select distinct department_code from t_Project_Details where district_id=@DistrictId
and financial_year=@yr);
--Insert into Project Table With Corresponding Department Name & Code
insert into @ProjectTable (
department_code,
project_code,
project_name,
department_name,
district_code,
district_name,
tehsil_code,
tehsil_name,
service_code,
[service_name],
sector_code,
sector_name,
project_start_year,
project_compl_year,
financial_year
)
SELECT pd.department_code,
pd.project_Code,
pd.project_name,
d.deptt_name,
pd.district_id,
di.district_name,
pd.tehsil_id,
t.tehsil_name,
pd.service_code,
s.[service_name],
pd.sector_code,
se.sector_name,
CONVERT(varchar,YEAR(pd.project_initiation_fin_from_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_from_yr,100) as project_start_year,
CONVERT(varchar,YEAR(pd.project_initiation_fin_to_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_to_yr,100) as project_compl_year,
pd.financial_year
FROM t_Project_Details pd
INNER JOIN m_Department d
ON d.deptt_code=pd.department_code
INNER JOIN m_Service s
ON s.service_code = pd.service_code
INNER JOIN m_Sector se
ON se.sector_code=pd.sector_code
INNER JOIN m_District di
ON di.district_code=pd.district_id
INNER JOIN m_Tehsil t
ON t.tehsil_code = pd.tehsil_id
WHERE
district_id=@DistrictId and
financial_year=@yr;
--select all from Department Table;
select * from @ProjectTable;
END
查询结果图片: https://drive.google.com/open?id=0Bxn7UXgmstmRaS1qX21kbjlwZzg
必需的输出图片: https://drive.google.com/open?id=0Bxn7UXgmstmRekJkUWhBcmNCbk0
答案 0 :(得分:0)
您的所需输出是表示层问题; SQL可以返回结果,但不能使一行包含一个内容,后面的行包含不同格式的许多不同内容。
SQL结果集将在所有行中包含相同数量的列,每个行具有相同的数据类型。
使用像SSRS这样的东西来实现你的欲望输出。