3

我通常在子查询中使用 COUNT 来获取所需的数字,但在这种情况下,我需要一些帮助,因为查询包含太多参数。

SELECT a.[QueueID]
  ,a.[CouponID]
  ,a.[ListingID]
  ,a.[User_ID]
  ,b.[CouponID]
  ,b.[ListingID]
  ,b.[CouponActive] 
  ,b.[CouponExpire] 
  ,b.[IsDeleted]
  ,c.[ListingID]
  ,c.[TypeID]
  ,c.[LevelID]
  ,@passedUserID as User_ID

FROM CouponQueue a
JOIN Coupon b
    on a.CouponID = b.CouponID
JOIN Listing c
    on b.ListingID = c.ListingID

WHERE (a.[User_ID] = @passedUserID)
AND (b.[CouponActive] = 1)
AND (b.[IsDeleted] = 0)
AND (b.[CouponExpire] > DATEADD(dd, -1, GETDATE()) OR b.[CouponExpire] IS NULL)

因此,假设此查询返回 7 行的结果。我所需要的只是我的 VIEW 的这个号码。所以我想将最终结果限制为单行,以便最终得到:

[TotalCount] <-- Field name
[7] <-- Result

但不是 7 行数据。我只需要上面查询的计数。仍在努力学习。我看了其他几个例子,但我没有找到一个符合所有条件的例子......这让我很困惑。请帮忙!

非常感谢!

4

3 回答 3

3

这对你有用吗?

select count(*) as TotalCOunt from (
SELECT a.[QueueID] /* 
  ,a.[CouponID]
  ,a.[ListingID]
  ,a.[User_ID]
  ,b.[CouponID]
  ,b.[ListingID]
  ,b.[CouponActive] 
  ,b.[CouponExpire] 
  ,b.[IsDeleted]
  ,c.[ListingID]
  ,c.[TypeID]
  ,c.[LevelID]
  ,@passedUserID as User_ID */

FROM CouponQueue a
JOIN Coupon b
    on a.CouponID = b.CouponID
JOIN Listing c
    on b.ListingID = c.ListingID

WHERE (a.[User_ID] = @passedUserID)
AND (b.[CouponActive] = 1)
AND (b.[IsDeleted] = 0)
AND (b.[CouponExpire] > DATEADD(dd, -1, GETDATE()) OR b.[CouponExpire] IS NULL)
) t

您可以删除计数的列。它们实际上不是必需的。

于 2013-01-18T03:14:59.813 回答
0

应该可以只添加 COUNT(*):

SELECT COUNT(*) as TotalCount    
FROM CouponQueue a
JOIN Coupon b
    on a.CouponID = b.CouponID
JOIN Listing c
    on b.ListingID = c.ListingID
WHERE (a.[User_ID] = @passedUserID)
AND (b.[CouponActive] = 1)
AND (b.[IsDeleted] = 0)
AND (b.[CouponExpire] > DATEADD(dd, -1, GETDATE()) OR b.[CouponExpire] IS NULL)

祝你好运。

于 2013-01-18T03:16:50.623 回答
0

您可以将以下示例放在 SQL Developer 上运行以进行计数:

SELECT count(*) as totalCount (*-open a parentheses - your original query -close the parentheses*)
于 2020-11-17T19:00:03.707 回答