SQL Count查询。偶数数字奇数

时间:2011-08-30 19:12:54

标签: sql sql-server tsql sql-server-2008-r2 sql-server-2008r2-express

我有一个产品表,我需要知道表中的记录数。目标是将返回查询划分为2个单独的查询。

If (Count(*) % 2) = 0 return top(Count(*) / 2)
else return top((Count(*) / 2) + 1)

主要查询是:

select coalesce(Price, ProductPrice) as Price, Product.ProductName, Customer.CustomerName, Product.CatalogNum from Product 
        inner join Customer on CustomerID = @custId
        left outer join CustomerPrice on dbo.Customer.CustomerID = dbo.CustomerPrice.CustomerID 
        and dbo.Product.ProductID = dbo.CustomerPrice.ProductID
        Where Product.ProductActive = 1 Order by Product.CatalogNum

4 个答案:

答案 0 :(得分:1)

可能不是最佳解决方案,但这可能适合您:

DECLARE @Rows INT
SELECT @Rows = CASE WHEN COUNT(*) % 2 = 0 THEN COUNT(*)/ 2 ELSE COUNT(*) / 2 + 1 END FROM Table1
SET ROWCOUNT @Rows
SELECT * FROM Table1 
SET ROWCOUNT 0

答案 1 :(得分:1)

DECLARE @a FLOAT
SET @a = (SELECT CEILING(COUNT(*)/2.0) FROM users)

SELECT TOP (CAST(@a AS INT)) * FROM users

答案 2 :(得分:1)

DECLARE @Count int
SELECT @Count = COUNT(*) FROM SomeTable
SET @Count = CASE WHEN @Count % 2 = 0 THEN @Count / 2 ELSE @Count / 2 + 1 END
SELECT TOP(@Count) * FROM SomeTable ORDER BY SomeColumn

请注意,此处存在并发问题 - 除非您应用适当限制的锁定提示/事务隔离级别,否则第一个和第二个select语句之间的行数可能会发生变化。

另请注意,ORDER BY对于“上半部分”赋予任何意义至关重要。

For information on the TOP clause.

要获得下半部分,请执行相同操作,但如果奇数计数则减去一,并将排序顺序反转几次。

DECLARE @Count int
SELECT @Count = COUNT(*) FROM SomeTable
SET @Count = CASE WHEN @Count % 2 = 0 THEN @Count / 2 ELSE @Count / 2 - 1 END
SELECT * FROM (
    SELECT TOP(@Count) * FROM SomeTable ORDER BY SomeColumn DESC) AS Data
ORDER BY SomeColumn

答案 3 :(得分:0)

尝试:

 Select * From Table t
 Where (Select Count(*) From Table
        Where pkCol < t.PkCol) <=
       (Select Count(*)+1 From Table)/2

整数除法应该处理你正在使用模运算符...

通过以下评论解决缺乏理解的问题,如果该表具有偶数个记录,比如20,然后count(*) = 20Count(*) + 1 = 21(Count(*)+1) / 2 = 10,则查询将返回所有记录,其中pk小于或等于pk的记录数小于或等于10,即记录的一半。

如果有奇数个记录,比如说21,那么count(*) = 21Count(*) + 1 = 22(Count(*)+1) / 2 = 11。查询将返回所有记录,其中pk小于或等于pk的记录数小于或等于11,即记录的一半加一,与模数运算符的使用相同。