将多个查询转换为单行

时间:2010-09-24 20:40:09

标签: sql reporting

我有一个报告,我想基于单个SQL语句。问题是数据基于几个SQL语句。例如。

SELECT COUNT(*) as 'Cases Opened' 
FROM tblCases 
WHERE DateAssigned BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Cases Closed' 
FROM tblCases 
WHERE ClosedDate BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Tickets Issued' 
FROM tblTicket 
WHERE DateIssued BETWEEN @StartDate AND @EndDate

SELECT COUNT(*) as 'Warnings Issued' 
FROM tblWarning 
WHERE DateIssued BETWEEN @StartDate AND @EndDate

有没有办法将这四个单独的SQL语句转换为单个SQL语句,以便每个结果都列为一列?例如..

Cases Opened        Cases Closed       Tickets Issued        Warnings Issued
******************************************************************************
   256         |      165          |        56           |          165

编辑我使用的是SQL Server,表之间没有任何关系。

3 个答案:

答案 0 :(得分:7)

select 
 (
 SELECT COUNT(*)  
 FROM tblCases 
 WHERE DateAssigned BETWEEN @StartDate AND @EndDate
 ) as 'Cases Opened' ,
 (SELECT COUNT(*)  
 FROM tblCases 
 WHERE ClosedDate BETWEEN @StartDate AND @EndDate
 ) as 'Cases Closed' ,
 (SELECT COUNT(*)  
 FROM tblTicket 
 WHERE DateIssued BETWEEN @StartDate AND @EndDate
 ) as 'Tickets Issued' ,
 (SELECT COUNT(*) 
 FROM tblWarning 
 WHERE DateIssued BETWEEN @StartDate AND @EndDate
 )  as 'Warnings Issued'
from dual
在oracle中必须使用

,mysql支持它,但是没有必要,我不确定sqlserver,因为我没有在我面前。

答案 1 :(得分:1)

您可以联合并转动数据,如下所示:

SELECT SUM(CASE WHEN FieldName='Cases Opened' THEN Value ELSE 0 END) AS Cases_Opened,
       SUM(CASE WHEN FieldName='Cases Closed' THEN Value ELSE 0 END AS Cases_Closed,
       SUM(CASE WHEN FieldName='Warning Issued' THEN Value ELSE 0 END) AS Warnings_Issued,
       SUM(CASE WHEN FieldName='Tickets Issued' THEN Value ELSE 0 END) AS Tickets_Issued
FROM 
(
SELECT COUNT(*) as Value, 'Cases Opened' as FieldName
FROM tblCases 
WHERE DateAssigned BETWEEN @StartDate AND @EndDate

UNION

SELECT COUNT(*) as Value, 'Cases Closed' as FieldName
FROM tblCases 
WHERE ClosedDate BETWEEN @StartDate AND @EndDate

UNION

SELECT COUNT(*) as Value, 'Tickets Issued' as FieldName
FROM tblTicket 
WHERE DateIssued BETWEEN @StartDate AND @EndDate

UNION

SELECT COUNT(*) as Value, 'Warnings Issued' as FieldName
FROM tblWarning 
WHERE DateIssued BETWEEN @StartDate AND @EndDate
)

答案 2 :(得分:1)

如果您在SQLServer中运行

,请查看pivot语句