SQL Count query. Even numbers odd numbers
I have a product table,开发者_StackOverflow I need to know the number of records in the table. The Goal is to divide the return query into 2 separate query.
If (Count(*) % 2) = 0 return top(Count(*) / 2)
else return top((Count(*) / 2) + 1)
The main query is :
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
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
Note that there is a concurrency issue here - the number of rows might change between the first and second select statements, unless you apply a suitably restrictive locking hint/transaction isolation level.
Note also that an ORDER BY
is essential to give any meaning to "top half".
For information on the TOP
clause.
To get the bottom half do the same but subtract one if odd count and reverse the sort order a couple of times.
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
Probably not the most optimal solution, but this might work for you:
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
DECLARE @a FLOAT
SET @a = (SELECT CEILING(COUNT(*)/2.0) FROM users)
SELECT TOP (CAST(@a AS INT)) * FROM users
Try:
Select * From Table t
Where (Select Count(*) From Table
Where pkCol < t.PkCol) <=
(Select Count(*)+1 From Table)/2
the integer division should deal with what you are rtying to do with the modulus operator...
to address the lack of understanding by the comment below, if the table has an even number of records, say 20, then count(*) = 20
, Count(*) + 1 = 21
, and (Count(*)+1) / 2 = 10
, the query will return all records where the count of records with a pk less than it's pk is less than or equal to 10, i.e. half the records.
If there are an odd number of records, say 21, then count(*) = 21
, Count(*) + 1 = 22
, and (Count(*)+1) / 2 = 11
. the query will return all records where the count of records with a pk less than it's pk is less than or equal to 11, i.e. half the records plus one, the same as the use of the modulus operator would do.
精彩评论