尝试在Jasper报告中加入2个查询

时间:2012-07-03 14:34:23

标签: sql jasper-reports

我想找一张这样的桌子:

Manager     Expert          Adminis. Staff
Dept        A.P. | C.P.     A.P. | C.P.     A.P. | C.P.
Management      1   1       1   0              1    1   
Accounting      1   1       1   1              0    0
IT              1   1       2   1              0    0

A.P。 =可用位置编号 C.P. =当前位置编号

A.P。来自名为Positions的表:

[Positions](
    [id] [numeric](19, 0) IDENTITY(1,1) NOT NULL,   
    [NumOfAvailablePositions] [int] NULL,
    [PositionType] [varchar](255) NULL, 
    [DepartmentId] [numeric](19, 0) NULL
    )

和C.P.是Title表中Title_Names的计数:

[Title](
    [id] [numeric](19, 0) IDENTITY(1,1) NOT NULL,   
    [Title_Name] [varchar](50) NOT NULL,    
    [Department_Id] [numeric](19, 0) NULL,  
    [Position_Type] [varchar](255) NULL,
    )

总之,我试图获得这两个查询的结果:

SELECT   DepartmentId, PositionType, NumOfAvailablePositions  
FROM Positions 

SELECT Department_Id, Position_Type, Count (Position_Type) as CurrentPositions
FROM Title group by Department_Id, Position_Type

并将结果连接到一个表中(如上所述)。

我尝试使用以下脚本加入表:

SELECT Department_Id, PositionType, Count(Position_Type) as PositionCountTitle, Positions.DepartmentId, Positions.NumOfAvailablePositions  
FROM Title, Positions 
GROUP BY Position_Type, Department_Id, Positions.DepartmentId, Positions.NumOfAvailablePositions 
HAVING Title.Department_Id = Positions.DepartmentId

但它产生了错误的结果。您是否有任何建议来解决Jasper IReports中的这个问题?

2 个答案:

答案 0 :(得分:2)

尝试用

替换FROM Title, Positions
FROM Title INNER JOIN Positions ON Title.[Position_Type]=Positions.[Position_Type]

答案 1 :(得分:0)

可能有一种方法可以在不使用子查询的情况下执行此操作,但我发现这通常是让您了解查询的第一步。

SELECT title.Department_Id,
       (SELECT NumOfAvailablePositions FROM POSITIONS WHERE Department_Id = position.Department_Id AND PositionType = 'Expert') as expert_ap,
       (SELECT COUNT(*) FROM Title WHERE Department_Id = title.Department_Id AND PositionType = 'Expert') as expert_cp,
       (SELECT NumOfAvailablePositions FROM POSITIONS WHERE Department_Id = position.Department_Id AND PositionType = 'Adminis. Staff') as admin_ap,
       (SELECT COUNT(*) FROM Title WHERE Department_Id = title.Department_Id AND PositionType = 'Adminis. Staff') as admin_cp,
       (SELECT NumOfAvailablePositions FROM POSITIONS WHERE Department_Id = position.Department_Id AND PositionType IS NULL) as rest_ap,
       (SELECT COUNT(*) FROM Title WHERE Department_Id = title.Department_Id AND PositionType IS NULL) as rest_cp,
FROM Title title, Positions position
WHERE Title.Department_Id = Positions.DepartmentId

此查询存在固有问题,但如果Positions表具有Title表没有的部门,则它将永远不会在查询中返回。如果您的情况不是这样,那么这不是问题。