0

我有 2 个查询我想在不使用联合的情况下合并到 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

4 回答 4

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
于 2009-10-08T12:39:34.893 回答
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
于 2009-10-08T12:46:11.500 回答
0

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

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

你试过什么?

发生了什么?

于 2009-10-08T12:44:29.197 回答
0

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

SELECT -- query 1

SELECT -- query 2

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

SqlDataReader reader = GetReader();
while (reader.Read())
{
    // Process result of query 1
}
reader.NextResult();
while (reader.Read())
{
    // Process result of query 2
}
于 2009-10-08T14:40:24.063 回答