我正在尝试检查两个表中的计数是否相同
我有一个问题:
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)
我怎么能这样做,我已经尝试了很长时间,但无法理解。
由于
答案 0 :(得分: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
答案 1 :(得分: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