两个查询日期范围值,返回不同的行数

时间:2011-06-07 07:13:22

标签: sql-server-2008 date

两个查询返回不同的行数。

Query1:
----------
SELECT t1.a1, t1.a2, t2.b1,t2.b2 
from (SELECT a1,a2 from xyz WHERE (date BETWEEN '2011-01-01' AND '2011-01-30')
AND id = 70 GROUP BY a1 a2)t1,
(SELECT a1,a2 from xyz WHERE (date BETWEEN '2011-01-01' AND '2011-01-30')
AND id = 70 GROUP BY a1 a2)t2, t3

where t1.a1=t3.a1
and t2.a1=t3.a1


output 1:
---------------
a1 a2  b1  b2
---------------
1   2  7   4
1   3  4   2
1   6  5   1

上述查询有什么问题吗?

我有相同的结构化查询,它带给我一些行。

当我使用union进行相同的查询时,它会为我带来比以前的查询更多的行

query2:
---------------
SELECT t1.a1, t1.a2, '' as b1,'' as b2 
FROM(SELECT a1,a2 from xyz WHERE (date BETWEEN '2011-01-01' AND '2011-01-31')
AND id = 70 GROUP BY a1 a2)t1, t3
where t1.a1=t3.c1

UNION ALL

SELECT '' AS a1, '' AS a2, t2.b1,t2.b2 
FROM(SELECT a1,a2 from xyz WHERE (date BETWEEN '2011-02-01' AND '2011-02-30')
AND id = 70 GROUP BY a1 a2)t1, t3
where t2.b1=t3.c1

output 2:
---------------
a1 a2  b1  b2
---------------
1   2      4
1   3      2
1   6  5
4   8  3

如果我不得不考虑其他任何技术,请咨询。

注意:我需要在报表中拖出不同的日期范围数据,例如销售人员的月1和月2的销售数量,以便与月销售进行比较。 “Ouptup1”将解决我的问题。请建议。 注意:我在查询数据方面不是很了解。

感谢。 Shahidul-孟加拉国达卡。

1 个答案:

答案 0 :(得分:1)

第一个查询可以(并且应该)像这样写入(纠正我假设应该是两个不同的日期范围):

Select t1.a1
    , t1.a2
    , t2.b1
    ,t2.b2 
From    (
        Select a1,a2 
        From xyz 
        Where date Between '2011-01-01' And '2011-01-30'
            And id = 70 
        Group By a1,a2
        ) As t1
    Join t3
        On t3.a1 = t1.a1
    Join    (   
            Select a1,a2 
            From xyz 
            Where date Between '2011-02-01' And '2011-02-28'
                And id = 70 
            Group By a1, a2
            ) As t2
        On t2.a1 = t3.a1

您应该避免在使用逗号分隔From子句中的表的情况下编写查询。不推荐使用此语法,IMO更难以遵循查询。更好的语法是我演示的ANSI / ISO Join语法。

要在第一个查询中显示一行,表a1中必须存在t3值,且a1值必须存在一行,日期范围为1月并且必须存在2月份的行。我会假设您想要在1月或2月出现的数据。

鉴于我认为您的要求,以下内容可能会为您提供所需内容:

Select T1.a1, T1.a2
    , T2.a1 As b1, T2.a2 As b2
From    (
        Select a1, a2
        From xyz
            Join t3
                On t3.a1 = xyz.a1
        Where xyz.id = 70
            And xyz.date >= '2011-01-01' And xyz.date < '2011-02-01' 
        Group By a1, a2
        ) As T1
    Full Join   (
                Select a1, a2
                From xyz
                    Join t3
                        On t3.a1 = xyz.a1
                Where xyz.id = 70
                    And xyz.date >= '2011-02-01' And xyz.date < '2011-03-01' 
                Group By a1, a2
                ) As T2
        On T2.a1 = T1.a1

虽然上面的查询接近您的要求,但堆叠每个月数据而不是尝试并排显示它会更简单。为此,您可以使用Union All类似于您尝试的方式:

Select 'Jan' As Month, a1, a2
From xyz
    Join t3
        On t3.a1 = xyz.a1
Where xyz.id = 70
    And xyz.date >= '2011-01-01' And xyz.date < '2011-02-01' 
Group By a1, a2
Union All
Select 'Feb', a1, a2
From xyz
    Join t3
        On t3.a1 = xyz.a1
Where xyz.id = 70
    And xyz.date >= '2011-02-01' And xyz.date < '2011-03-01' 
Group By a1, a2