合并2个SQL查询

时间:2009-10-08 12:34:47

标签: sql-server resultset

我有2个查询,我想在不使用union的情况下合并到1个结果集中。

查询1

select  datepart(yy,dateclosed)as 'Year',
    datepart(mm,dateclosed) as 'Month',
    count(*)as 'Total' 
from bug 
where projectid = 44 
and ifclosed = 1
and isnull(createdbyperson,1) <> '-1111111110'
and datepart(yy,dateclosed) > '2000'
group by datepart(yy,dateclosed), datepart(mm,dateclosed)
order by 1,2

查询2

select  datepart(yy,dateclosed)as 'Year',
    datepart(mm,dateclosed) as 'Month',
    count(*)as 'SameDay' 
from bug 
where   projectid = 44 
        and ifclosed = 1
        and isnull(createdbyperson,1) <> '-1111111110'
        and datepart(yy,dateclosed) > '2000' 
        and CONVERT(VARCHAR(10), dateclosed, 101) = CONVERT(VARCHAR(10), datecreated, 101) 
group by datepart(yy,dateclosed),datepart(mm,dateclosed)
order by 1,2

我喜欢将值返回为Year,Month,SameDay,Total。我该如何实现这一目标?联盟没有做我想做的事。我是否必须进行连接和表别名?子查询?

提前致谢。

4 个答案:

答案 0 :(得分:1)

好的......这个怎么样:

select a.Year, a.Month, b.SameDay, a.Total
from
(
select  datepart(yy,dateclosed)as 'Year',
    datepart(mm,dateclosed) as 'Month',
    count(*)as 'Total' 
from bug 
where projectid = 44 
and ifclosed = 1
and isnull(createdbyperson,1) <> '-1111111110'
and datepart(yy,dateclosed) > '2000'
group by datepart(yy,dateclosed), datepart(mm,dateclosed)
) a
inner join
(
select  datepart(yy,dateclosed)as 'Year',
    datepart(mm,dateclosed) as 'Month',
    count(*)as 'SameDay' 
from bug 
where   projectid = 44 
        and ifclosed = 1
        and isnull(createdbyperson,1) <> '-1111111110'
        and datepart(yy,dateclosed) > '2000' 
        and CONVERT(VARCHAR(10), dateclosed, 101) = CONVERT(VARCHAR(10), datecreated, 101) 
group by datepart(yy,dateclosed),datepart(mm,dateclosed)
) b
on a.Year = b.Year AND a.Month = b.Month
order by 1,2

答案 1 :(得分:1)

试试这个:

SELECT DATEPART(yy,dateclosed) AS 'Year',
    DATEPART(mm,dateclosed) AS 'Month',
    SUM(IF(CONVERT(VARCHAR(10), dateclosed, 101) = CONVERT(VARCHAR(10), datecreated, 101), 1, 0)) AS SameDay,
    COUNT(*) AS 'Total' 
FROM bug 
WHERE projectid = 44 
    AND ifclosed = 1
    AND ISNULL(createdbyperson,1) <> '-1111111110'
    AND DATEPART(yy,dateclosed) > '2000'
GROUP BY DATEPART(yy,dateclosed), DATEPART(mm,dateclosed)
ORDER BY 1,2

答案 2 :(得分:0)

如果不使用联合,您可以创建一个临时表,将两个查询的结果写入其中,然后查询临时表。

我怀疑你不应该这样做,而是要弄清楚为什么工会不适合你。

你有什么尝试?

发生了什么事?

答案 3 :(得分:0)

为什么要这样做?您是否知道您可以让查询返回多个结果集:

SELECT -- query 1

SELECT -- query 2

然后您的客户端可以独立读取2个结果集 - 它取决于您使用的语言,但在使用SqlDataReader的C#中使用NextResult

SqlDataReader reader = GetReader();
while (reader.Read())
{
    // Process result of query 1
}
reader.NextResult();
while (reader.Read())
{
    // Process result of query 2
}