How to fix Number Of Row Per Page in SSRS Report? - reporting-services

I Have Fix 10 Rows Per Page , If 2records Comes From Query Then I Want To Show 8 Blank Rows. How To Fix It ?

This is a fairly generic example. It just counts the actual rows, calculates how many rows are required to round up to the nearest 10 and then UNIONs a query that generates blank rows.
SELECT *
FROM (
SELECT
RowN = ROW_NUMBER() OVER(ORDER BY myColumn), -- order by any column
*
FROM myTable
UNION ALL
SELECT
TOP (SELECT ExtraRows = (FLOOR((Count(*)+9)/10) * 10) - COUNT(*) FROM myTable) -- 10 here is rows per page
NewRowNumber = ROW_NUMBER() OVER (ORDER BY [object_id]) + (SELECT COUNT(*) FROM myTable)
,NULL, NULL, NULL -- one nulll value for each column in myTable
FROM sys.all_columns
) u
ORDER by u.RowN -- add any additional required sorting here
If your current query is not simple then dump the results of that into a temp table
SELECT *
INTO #t
FROM ...
myBigQuery
then change the references to myTable in the main query above to #t or whatever the temp table is called.
EDIT for using with SP
If using a Stored proc then you can dump the results of that into a temp table and do the same. For exmaple
CREATE TABLE #t (ColA int, ColB varchar(100)....)
INSERT INTO #t
EXEC myStoredProc
...
the main query from above
...
Just swap out all references to myTable with #t

Related

run a query if a value on the last row is correct

Id like to run a query only if a value in the last row is correct. In my exemple if the value in ColumnA is 1 on the last row then i want to run MyQuery. But if the value is not 1 stop there and do nothing.
i've try with case and count(*) and also with If exists. but i keep getting error
SELECT CASE WHEN ((SELECT COUNT(*) FROM
(Select a.* from table as a order by a.index desc limit 1) as b
where b.ColumnA = 1)) > 0 )
THEN (MyQuery)
END
i've also try with if exists but it doesn'work either
if exists Select b.* from (Select a.* from table as a order by a.index desc limit 1) where b.ColumnA = 1
begin
(MyQuery)
end
can you point me what wrong in those query or maybee there's a better way to achive this.
EDIT. This query will be run on a trigger after each insert in that table the goal is to avoid running MyQuery on row that dont required it. MyQuery is a bit slow and most row dont required it to run.
I think we can rephrase your logic here to make it work as you want:
WITH cte AS (
SELECT ColumnA, ROW_NUMBER() OVER (ORDER BY index DESC) rn
FROM yourTable
)
(your query here)
WHERE (SELECT ColumnA FROM cte WHERE rn = 1) = 1;
The WHERE clause above would return either true or false, and would apply to all records in the potential result set from your query. That is, if the ColumnA value from the "last" record were 1, then you would get back the entire result set, otherwise it would be empty set.
Assuming your version of MariaDB supports neither ROW_NUMBER nor CTEs, then use:
(your query here)
WHERE (SELECT ColumnA FROM yourTable ORDER BY index DESC LIMIT 1) = 1;
It depends on what your query is.
INSERT ...
SELECT ... WHERE ... -- this could lead to zero rows being inserted
DELETE ...
WHERE NOT EXISTS ( SELECT ... ) -- this could lead to zero rows being deleted
UPDATE t1 JOIN t2 ... -- the JOIN may cause no rows to be updated
Note:
(Select a.* from table as a order by a.index desc limit 1) as b
where b.ColumnA = 1)) > 0 )
can be simplified (and sped up) to
( ( SELECT ColumnA FROM table ORDER BY index DESC LIMIT 1 ) = 1 )
Note that that is a true/false "expression", so it can be used in various places.

Passing multiple values for a single parameter from SSRS to hive

Creating a concatenated string in SSRS with values enclosed in single quotes
Any answers to the above question?. I am struck with the same problem:
The query from SSRS side is:
select *
from xyz.test_table1
where f1 in (?)
Datasource for me in this case is a hive table. User selection on the parameter is a multivalued parameter which is what I expect to be substituted as:
where in ('value1','value2')
when query is executed. But when looked at the query execution on the hive side, it comes as:
where in ('value1,value2')
How could I solve this?
From the documentation here, it seems Hive Query Language supports Common Table Expressions.
Consequently, something similar to the following should work:
declare #str nvarchar(4000) = ?; -- String to split.
with n(n) as (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1)
-- Select the same number of rows as characters in #str as incremental row numbers.
-- Cross joins increase exponentially to a max possible 10,000 rows to cover largest #str length.
,t(t) as (select top (select len(isnull(#str,'')) a) row_number() over (order by (select null)) from n n1,n n2,n n3,n n4)
-- Return the position of every value that follows the specified delimiter.
,s(s) as (select 1 union all select t+1 from t where substring(isnull(#str,''),t,1) = ',')
-- Return the start and length of every value, to use in the SUBSTRING function.
-- ISNULL/NULLIF combo handles the last value where there is no delimiter at the end of the string.
,l(s,l) as (select s,isnull(nullif(charindex(',',isnull(#str,''),s),0)-s,4000) from s)
-- Return each individual value in the delimited string along with it's position.
,v as (select row_number() over(order by s) as rn
,substring(#str,s,l) as item
from l
)
select *
from v
join xyz.test_table1 as t
on v.v = t.f1
If you rather understandably don't want this rigamarole in all of your datasets, you would need to encapsulate this logic into whatever the Hive equivalent of a SQL Server table-valued parameter is, perhaps a UDTF?
In SQL Server, the function would be defined as follows:
create function [dbo].[fn_StringSplit4k]
(
#str nvarchar(4000) = ' ' -- String to split.
,#delimiter as nvarchar(1) = ',' -- Delimiting value to split on.
,#num as int = null -- Which value to return.
)
returns table
as
return
-- Start tally table with 10 rows.
with n(n) as (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1)
-- Select the same number of rows as characters in #str as incremental row numbers.
-- Cross joins increase exponentially to a max possible 10,000 rows to cover largest #str length.
,t(t) as (select top (select len(isnull(#str,'')) a) row_number() over (order by (select null)) from n n1,n n2,n n3,n n4)
-- Return the position of every value that follows the specified delimiter.
,s(s) as (select 1 union all select t+1 from t where substring(isnull(#str,''),t,1) = #delimiter)
-- Return the start and length of every value, to use in the SUBSTRING function.
-- ISNULL/NULLIF combo handles the last value where there is no delimiter at the end of the string.
,l(s,l) as (select s,isnull(nullif(charindex(#delimiter,isnull(#str,''),s),0)-s,4000) from s)
select rn
,item
from(select row_number() over(order by s) as rn
,substring(#str,s,l) as item
from l
) a
where rn = #num
or #num is null;
Figured it out! Posting the answer for other users.
Provide the query(under Query in SSRS) as an expression like below:
="select * from xyz.test_table1 where f1 in ('"&Join(Parameters!param.Value,"','")&"')"
The above string manipulation translates to:
select * from xyz.test_table1 where f1 in ('value1','value2')
Note: value1, value2 here are the values from user selected multivalue parameter

Get sequential rows that have same column values is SQL Server 2008

I need to know the sequential rows which have some same values
I need the rows which have prsstatus value of 0 and then next row is 1
Another method, change MyTable to whatever your table is and change the ORDER BY clause to whatever columns you want to sort by.
;WITH MyTableSort AS (
SELECT TblID, EmpID, PrsDay, PrsTime, PrsStatus, ROW_NUMBER() OVER (ORDER BY MyTable.TblID) [Row] FROM MyTable
)
SELECT * FROM MyTableSort AS MyTableSortA
WHERE (MyTableSortA.PrsStatus = 0 AND EXISTS (SELECT 1 FROM MyTableSort WHERE MyTableSort.[Row] = MyTableSortA.[row]+1 AND MyTableSort.PrsStatus = 1))
Assuming you mean "next" row in terms of dense values on TblID:
select YTN.*
from YourTableName as YTN inner join
YourTableName as NR on NR.TblID = YTN.TblId + 1 and
NR.PrsStatus = 1 and YTN.PrsStatus = 0

SQL Fastest way to Group records based on Thresholds

My records are in a temporary table having three columns :
Column1 : ID (Bigint)
Column2 : CreationDateTime (dateTime)
Column3 : Volume (Float)
The records are sorted based on CreationDateTime.
I need to pick the records from the table where Sum of Volume is equal to THRESHOLD1 and then the same for Threshold2.
One way is to add a new Column to the table which has the sum of Volume for the previous records. for example :
ID - CreationDateTime - Volume - SUM
1 - 20/07/2012 - 10 - 10
2 - 21/07/2012 - 12 - 22
3 - 22/07/2012 - 7 - 29
and then Select * from temp where Sum >= Threshold But the calculation of the sum is not the fastest way.
I was wondering if anyone can suggest a better way for doing the above.
I'm using SQL server 2008 and I can also use CLR if required.
try this solution:
you can find the running total just by self joining tables and group by
with cte as(
select T2.ID, T2.CreationDateTime,SUM(T1.Volume) [SUM]
from test_table T1 join test_table T2
on T1.id<=T2.id
group by T2.id, T2.CreationDateTime)
select * from cte where [SUM]>= Threshold
Here's an approach using a recursive CTE, which will likely be the fastest:
select #i=min(ID) from #temp
;with a as
(
select ID, Volume, Volume as RunningTotal
from #temp
where ID=#i
union all
select b.ID, b.Volume, b.Volume + a.RunningTotal as RunningTotal
from #temp b
inner join a
on b.ID=a.ID+1
)
select * from a
Some links related to running totals:
http://www.sqlusa.com/bestpractices/runningtotal/
http://www.databasejournal.com/features/mssql/article.php/3112381/SQL-Server-Calculating-Running-Totals-Subtotals-and-Grand-Total-Without-a-Cursor.htm
http://www.mssqltips.com/sqlservertip/1686/calculate-running-totals-using-sql-server-cross-joins/
http://social.msdn.microsoft.com/Forums/eu/transactsql/thread/1b4d87cb-ec77-4455-af48-bf7dae50ab87
Computed Column using a function:
create function dbo.fn_VolumeRunningTotal
{
#dt datetime
}
returns int
as
begin
declare #total int
select #total = sum(volume)
from dbo.MyVolumeTable
where CreationDateTime <= #dt
return #total
end
Computed Column formula:
dbo.fn_VolumeRunningTotal(CreationDateTime)
Select statements:
select * from dbo.MyVolumnTable where RunningTotal <= #Threshold1

Looking for missed IDs in SQL Server 2008

I have a table that contains two columns
ID | Name
----------------
1 | John
2 | Sam
3 | Peter
6 | Mike
It has missed IDs. In this case these are 4 and 5.
How do I find and insert them together with random names into this table?
Update: cursors and temp tables are not allowed. The random name should be 'Name_'+ some random number. Maybe it would be the specified value like 'Abby'. So it doesn't matter.
Using a recursive CTE you can determine the missing IDs as follows
DECLARE #Table TABLE(
ID INT,
Name VARCHAR(10)
)
INSERT INTO #Table VALUES (1, 'John'),(2, 'Sam'),(3,'Peter'),(6, 'Mike')
DECLARE #StartID INT,
#EndID INT
SELECT #StartID = MIN(ID),
#EndID = MAX(ID)
FROM #Table
;WITH IDS AS (
SELECT #StartID IDEntry
UNION ALL
SELECT IDEntry + 1
FROM IDS
WHERE IDEntry + 1 <= #EndID
)
SELECT IDS.IDEntry [ID]
FROM IDS LEFT JOIN
#Table t ON IDS.IDEntry = t.ID
WHERE t.ID IS NULL
OPTION (MAXRECURSION 0)
The option MAXRECURSION 0 will allow the code to avoid the recursion limit of SQL SERVER
From Query Hints and WITH common_table_expression (Transact-SQL)
MAXRECURSION number Specifies the maximum number of recursions
allowed for this query. number is a nonnegative integer between 0 and
32767. When 0 is specified, no limit is applied. If this option is not specified, the default limit for the server is 100.
When the specified or default number for MAXRECURSION limit is reached
during query execution, the query is ended and an error is returned.
Because of this error, all effects of the statement are rolled back.
If the statement is a SELECT statement, partial results or no results
may be returned. Any partial results returned may not include all rows
on recursion levels beyond the specified maximum recursion level.
Generating the RANDOM names will largly be affected by the requirements of such a name, and the column type of such a name. What exactly does this random name entail?
You can do this using a recursive Common Table Expression CTE. Here's an example how:
DECLARE #MaxId INT
SELECT #MaxId = MAX(ID) from MyTable
;WITH Numbers(Number) AS
(
SELECT 1
UNION ALL
SELECT Number + 1 FROM Numbers WHERE Number < #MaxId
)
SELECT n.Number, 'Random Name'
FROM Numbers n
LEFT OUTER JOIN MyTable t ON n.Number=t.ID
WHERE t.ID IS NULL
Here are a couple of articles about CTEs that will be helpful to Using Common Table Expressions and Recursive Queries Using Common Table Expressions
Start by selecting the highest number in the table (select top 1 id desc), or select max(id), then run a while loop to iterate from 1...max.
See this article about looping.
For each iteration, see if the row exists, and if not, insert into table, with that ID.
I think recursive CTE is a better solution, because it's going to be faster, but here is what worked for me:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TestTable]') AND type in (N'U'))
DROP TABLE [dbo].[TestTable]
GO
CREATE TABLE [dbo].[TestTable](
[Id] [int] NOT NULL,
[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
GO
INSERT INTO [dbo].[TestTable]([Id],[Name]) VALUES (1, 'John')
INSERT INTO [dbo].[TestTable]([Id],[Name]) VALUES (2, 'Sam')
INSERT INTO [dbo].[TestTable]([Id],[Name]) VALUES (3, 'Peter')
INSERT INTO [dbo].[TestTable]([Id],[Name]) VALUES (6, 'Mike')
GO
declare #mod int
select #mod = MAX(number)+1 from master..spt_values where [type] = 'P'
INSERT INTO [dbo].[TestTable]
SELECT y.Id,'Name_' + cast(newid() as varchar(45)) Name from
(
SELECT TOP (select MAX(Id) from [dbo].[TestTable]) x.Id from
(
SELECT
t1.number*#mod + t2.number Id
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
WHERE t1.[type] = 'P' and t2.[type] = 'P'
) x
WHERE x.Id > 0
ORDER BY x.Id
) y
LEFT JOIN [dbo].[TestTable] on [TestTable].Id = y.Id
where [TestTable].Id IS NULL
GO
select * from [dbo].[TestTable]
order by Id
GO
http://www.sqlfiddle.com/#!3/46c7b/18
It's actually very simple :
Create a table called #All_numbers which should contain all the natural number in the range that you are looking for.
#list is a table containing your data
select a.num as missing_number ,
'Random_Name' + convert(varchar, a.num)
from #All_numbers a left outer join #list l on a.num = l.Id
where l.id is null