1

我正在尝试检查两个表的计数是否相同

我有一个查询:

SELECT Count(1) AS Items,
       [Basket Id],
       [Customer Id]
FROM   Order_Lookup
GROUP  BY [Basket Id],
          [Customer Id]

返回:

3   2   135674
5   4   115576
3   5   115576
2   3   118342
4   6   182368

而且我还有:

SELECT Count(1) AS Items,
                 a.[Basket Id],
                 a.[Customer Id]
          FROM   C1059204.Order_Lookup a
          WHERE  a.[Product Id] NOT IN (SELECT [Product Id]
                                        FROM   Orders
                                        WHERE  [Customer_Id] = a.[Customer Id]
                                               AND OrderDate = Dateadd(DAY, Datediff(DAY, 0, Getutcdate()), -2)
                                               AND OrderStatus IN ('POSTED' ))
          GROUP  BY a.[Basket Id],
                    a.[Customer Id] 

返回:

3   2   135674
3   4   115576
3   5   115576
2   3   118342
4   6   182368

如您所见,115576 Basket Id 4 的编号较小。

我需要像这样的查询

SELECT * FROM TABLE
WHERE (COUNT OF FIRST SUBQUERY) = (COUNT OF SECOND SUBQUERY)

我该怎么做,我已经尝试了很长时间,无法弄清楚。

谢谢

4

2 回答 2

1

您可以包装两个子查询并加入别名。

select *
from (
    SELECT Count(1) AS Items,
           [Basket Id],
           [Customer Id]
    FROM   Order_Lookup
    GROUP  BY [Basket Id],
              [Customer Id]
) as query1
join (
    SELECT Count(1) AS Items,
                     a.[Basket Id],
                     a.[Customer Id]
              FROM   C1059204.Order_Lookup a
              WHERE  a.[Product Id] NOT IN (SELECT [Product Id]
                                            FROM   Orders
                                            WHERE  [Customer_Id] = a.[Customer Id]
                                                   AND OrderDate = Dateadd(DAY, Datediff(DAY, 0, Getutcdate()), -2)
                                                   AND OrderStatus IN ('POSTED' ))
              GROUP  BY a.[Basket Id],
                        a.[Customer Id] 
) as query2 on query1.Items = query2.Items
于 2012-04-04T11:22:52.370 回答
0

像这样做:

SELECT count(*),
       subquery.[Basket Id],
       subquery.[Customer Id] 
FROM (
  -- Put your subselect in a case expression returning 1 or 0 to indicate
  -- whether it would evaluate to true or false for any given record
  SELECT CASE WHEN a.[Product Id] IN (
                SELECT [Product Id]
                  FROM Orders
                 WHERE [Customer_Id] = a.[Customer Id]
                   AND OrderDate = Dateadd(DAY, Datediff(DAY, 0, Getutcdate()), -2)
                   AND OrderStatus IN ('POSTED' ))
         THEN 1
         ELSE 0 END [isPosted],
       a.[Basket Id],
       a.[Customer Id]
   FROM   C1059204.Order_Lookup a
 ) subquery
 GROUP  BY subquery.[Basket Id],
           subquery.[Customer Id] 
 -- Those groups that contain at least one record which would figure in your 
 -- "second subquery" should be omitted altogether
 HAVING SUM([isPosted]) = 0
于 2012-04-04T11:19:47.860 回答