Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Friday, March 30, 2012

How to get Top 3 records in the group level?

Hi all,

I have a query which is grouped by a field called R_ID, which gives me a list of records for each R_ID. So here is the thing, I want to get only top 3 records for each R_ID. I tried using 'select top 3....', but the result is not what I wanted. It doesn't consider the grouping. Is there any way to achieve this task?

Please let me know if some body has any idea.

Thx.

The answer depends on whether or not you have SQL Server 2005 or SQL Server 2000. If you are using SQL Server 2005 you can use the ROW_NUMBER function. What is also needed is to know what field you are ordering your groups by (to get the top 3).


Dave

|||Doing this in a report wouldn′t be the best way as you would get all the data from the server and then only would display a part of it. better filter the data on the server and send only back the appropiate results, then you would have no problem on the client / reporting service. Anway, if you want to do this, you might have a look at the RowNumber() property in Reporting Services. You could set the Visibility of the row to Visible=True if the RowNumber("GroupName") equals or is less than 3 =IIF(Rownumber("GroupName") <= 3;True;False)

Doing this on the server depends on which server version you are using. SQL Server 2005 probably would enable you to use ROW_NUMBER() on the server side. SQL Server 2k does not implement this new function, so you would have to use something else instead.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||

How about this:

-- sample table / data
CREATE TABLE t1 (R_ID nvarchar(3), text_data NVARCHAR(50));

INSERT INTO t1 VALUES ('A', 'Text for A1');
INSERT INTO t1 VALUES ('A', 'Text for A2');
INSERT INTO t1 VALUES ('A', 'Text for A3');
INSERT INTO t1 VALUES ('A', 'Text for A4');
INSERT INTO t1 VALUES ('B', 'Text for B1');
INSERT INTO t1 VALUES ('B', 'Text for B2');
INSERT INTO t1 VALUES ('B', 'Text for B3');
INSERT INTO t1 VALUES ('B', 'Text for B4');
INSERT INTO t1 VALUES ('C', 'Text for C1');
INSERT INTO t1 VALUES ('C', 'Text for C2');
INSERT INTO t1 VALUES ('C', 'Text for C3');
INSERT INTO t1 VALUES ('C', 'Text for C4');

-- Retrieve TOP(3) Entries for Each R_ID
SELECT R_ID, text_data
FROM t1 AS a
WHERE text_data IN
(SELECT TOP(3) text_data
FROM t1 AS b
WHERE a.R_ID = b.R_ID
ORDER BY text_data)

|||

Amde:

I set up a mock-up to compare Lucky's query with a query based on ROW_NUMBER. I created the T1 table with 32767 distinct R_ID entries and 30 distinct TEXT_DATA entries for each R_ID -- nearly 1,000,000 rows. When I ran Lucky's query with the table without any indexes it took about 102 seconds with 6.6 million logical IOs. I then added an index based on R_ID only and repeated the run. Again, it took about 102 seconds with 6.6 million logical IOs. I then looked at the SHOWPLAN and verified that the plan was still using a TABLE scan and was not using the index. This is expected because use of the index would require a prohibitive amount of bookmark lookups. I lastly dropped that index and added a cover index based on both R_ID and TEXT_DATA and repeated the run. This time it took 17 seconds with 3.1 million logical IOs.

Next, I repeated this using a query based on ROW_NUMBER. I first ran the query without any indexes. It took 7263 ms with 7709 logical IOs. I added an index based on R_ID only and it again took about 7600 ms with 7709 logical IOs. I then dropped that index and added an index based on both R_ID and TEXT_DATA. This query then took 2406 ms with 7706 logical IOs. This is the script I used for testing:

set nocount on
use tempdb
drop table t1
go

-- sample table / data
CREATE TABLE t1 (R_ID nvarchar(5), text_data NVARCHAR(50));
--exec sp_help t1

insert into t1
select convert (nvarchar (5), i.iter),
'Text for ' + convert (nvarchar(5), i.iter)
+ '-' + convert (nchar(2), j.iter)
from mugambo.dbo.small_iterator (nolock) i
inner join mugambo.dbo.small_iterator (nolock) j
on j.iter <= 30
--select * from t1

--drop index t1.t1_ndx
--create index t1_ndx on t1(r_id)
create index t1_ndx on t1(r_id, text_data)
update statistics t1
go

declare @.begDt datetime set @.begDt = getdate()

/*
--insert into @.receiver
-- Retrieve TOP(3) Entries for Each R_ID
SELECT R_ID, text_data
FROM t1 AS a
WHERE text_data IN
(SELECT TOP(3) text_data
FROM t1 AS b
WHERE a.R_ID = b.R_ID
ORDER BY text_data)
*/

set statistics io on

select r_id,
text_data
from ( select r_id,
row_number () over
(partition by R_ID order by text_data)
as seq,
text_data
from t1
) x
where seq <= 3

set statistics io off

print ' '
select datediff (ms, @.begDt, getdate()) as [Elapsed Time]


-- Output:

-- r_id text_data
-- -- --
-- 1 Text for 1-1
-- 1 Text for 1-10
-- ...
-- 9999 Text for 9999-11

-- Table 't1'. Scan count 1, logical reads 7706, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
-- Elapsed Time
--
-- 2220

|||

Hi,

keeping same table as Lucky_p has dipicted , just try this

select *from

(SELECT i.r_id, i.text_data,

DENSE_RANK() OVER (PARTITION BY i.r_id order by text_data) as RANK

FROM t1 i) A where rank<=3

Madhu

|||

That's all nice and i agree my solution is not fast when the table is large.

Do you have a fast solution for SQL 2000 too? All your solutions are for SQL 2005.

|||

Lucky:

I cannot come up with a method for SQL Server 2000 that is any faster than your version. Hopefully, one of the senior members can shed some light; I struck out.


Dave

|||

I found an alternative that might be of some use:

declare @.top3 table
( r_id nvarchar (5) not null,
seq integer not null,
text_data nvarchar (50) not null,

primary key (r_id, seq)
)

insert into @.top3
select r_id,
1,
min(text_data)
from t1
group by r_id

insert into @.top3
select r_id,
2,
( select min (b.text_data) from t1 b
where a.r_id = b.r_id
and b.text_data > a.text_data
)
from @.top3 a

insert into @.top3
select r_id,
3,
( select min (b.text_data) from t1 b
where a.r_id = b.r_id
and b.text_data > a.text_data
)
from @.top3 a
where seq = 2


set statistics io off

print ' '
select datediff (ms, @.begDt, getdate()) as [Elapsed Time]


-- Output:

-- Table '#33ADF722'. Scan count 0, logical reads 66286, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 1, logical reads 7640, physical reads 0, read-ahead reads 0.
-- Table '#33ADF722'. Scan count 1, logical reads 97120, physical reads 0, read-ahead reads 0.
-- Table 'Worktable'. Scan count 1, logical reads 33468, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 32767, logical reads 98558, physical reads 0, read-ahead reads 0.
-- Table '#33ADF722'. Scan count 1, logical reads 100528, physical reads 0, read-ahead reads 0.
-- Table 'Worktable'. Scan count 1, logical reads 33468, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 32767, logical reads 98552, physical reads 0, read-ahead reads 0.
-- Elapsed Time
--
-- 2766

|||

I have an additional solution for SQL 2000 which uses a Partition calculation. But I'm not sure if its faster than the other 2000 compatible approach.

-- Create a Temporary Table using an additional column
-- Row-Number Partitioned by R_ID
SELECT R_ID , text_data,
(SELECT COUNT(*) FROM T1 AS b
WHERE b.R_ID = a.R_ID
AND (b.text_data < a.text_data
OR (b.text_data = a.text_data))) AS rownum
INTO #T1
FROM T1 AS a
ORDER BY R_ID, text_data;

-- Get the results from Temporary Table
SELECT R_ID, text_data FROM #T1
WHERE rownum <= 3

|||

Lucky P wrote:

I have an additional solution for SQL 2000 which uses a Partition calculation. But I'm not sure if its faster than the other 2000 compatible approach.

-- Create a Temporary Table using an additional column
-- Row-Number Partitioned by R_ID
SELECT R_ID , text_data,
(SELECT COUNT(*) FROM T1 AS b
WHERE b.R_ID = a.R_ID
AND (b.text_data < a.text_data
OR (b.text_data = a.text_data))) AS rownum
INTO #T1
FROM T1 AS a
ORDER BY R_ID, text_data;

-- Get the results from Temporary Table
SELECT R_ID, text_data FROM #T1
WHERE rownum <= 3

again with little modification u can fine tune this script.. eliminate Temp table

Select *from

(SELECT top 100 R_ID , text_data,

(SELECT COUNT(*) FROM T1 AS b

WHERE b.R_ID = a.R_ID

AND (b.text_data < a.text_data

OR (b.text_data = a.text_data))) AS rownum

FROM T1 AS a

ORDER BY R_ID, text_data) A

where rownum<4

Madhu

|||

I tested these other queries too with my "million-row" mockup and here is what I think:

If running SQL Server 2005 use either Madhu's or my first query|||

Your getting a partial result because of these line:

(SELECT top 100 R_ID , text_data,

If You change it to

(SELECT top 100 PERCENT R_ID , text_data,

You should get all the rows....

|||

Thanks for catching that lucky; I tested this one too and your original query is still much faster.


Dave

|||

ms sql server

data:


idno Email Category
1 a@.a.com c
2 b@.b.com c
3 b@.b.com c
4 b@.b.com c

only unique email address record are requierd.
1 a@.a.com c
2 b@.b.com c

what could be the query for such requirements.

How to get Top 3 records in the group level?

Hi all,

I have a query which is grouped by a field called R_ID, which gives me a list of records for each R_ID. So here is the thing, I want to get only top 3 records for each R_ID. I tried using 'select top 3....', but the result is not what I wanted. It doesn't consider the grouping. Is there any way to achieve this task?

Please let me know if some body has any idea.

Thx.

The answer depends on whether or not you have SQL Server 2005 or SQL Server 2000. If you are using SQL Server 2005 you can use the ROW_NUMBER function. What is also needed is to know what field you are ordering your groups by (to get the top 3).


Dave

|||Doing this in a report wouldn′t be the best way as you would get all the data from the server and then only would display a part of it. better filter the data on the server and send only back the appropiate results, then you would have no problem on the client / reporting service. Anway, if you want to do this, you might have a look at the RowNumber() property in Reporting Services. You could set the Visibility of the row to Visible=True if the RowNumber("GroupName") equals or is less than 3 =IIF(Rownumber("GroupName") <= 3;True;False)

Doing this on the server depends on which server version you are using. SQL Server 2005 probably would enable you to use ROW_NUMBER() on the server side. SQL Server 2k does not implement this new function, so you would have to use something else instead.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de
|||

How about this:

-- sample table / data
CREATE TABLE t1 (R_ID nvarchar(3), text_data NVARCHAR(50));

INSERT INTO t1 VALUES ('A', 'Text for A1');
INSERT INTO t1 VALUES ('A', 'Text for A2');
INSERT INTO t1 VALUES ('A', 'Text for A3');
INSERT INTO t1 VALUES ('A', 'Text for A4');
INSERT INTO t1 VALUES ('B', 'Text for B1');
INSERT INTO t1 VALUES ('B', 'Text for B2');
INSERT INTO t1 VALUES ('B', 'Text for B3');
INSERT INTO t1 VALUES ('B', 'Text for B4');
INSERT INTO t1 VALUES ('C', 'Text for C1');
INSERT INTO t1 VALUES ('C', 'Text for C2');
INSERT INTO t1 VALUES ('C', 'Text for C3');
INSERT INTO t1 VALUES ('C', 'Text for C4');

-- Retrieve TOP(3) Entries for Each R_ID
SELECT R_ID, text_data
FROM t1 AS a
WHERE text_data IN
(SELECT TOP(3) text_data
FROM t1 AS b
WHERE a.R_ID = b.R_ID
ORDER BY text_data)

|||

Amde:

I set up a mock-up to compare Lucky's query with a query based on ROW_NUMBER. I created the T1 table with 32767 distinct R_ID entries and 30 distinct TEXT_DATA entries for each R_ID -- nearly 1,000,000 rows. When I ran Lucky's query with the table without any indexes it took about 102 seconds with 6.6 million logical IOs. I then added an index based on R_ID only and repeated the run. Again, it took about 102 seconds with 6.6 million logical IOs. I then looked at the SHOWPLAN and verified that the plan was still using a TABLE scan and was not using the index. This is expected because use of the index would require a prohibitive amount of bookmark lookups. I lastly dropped that index and added a cover index based on both R_ID and TEXT_DATA and repeated the run. This time it took 17 seconds with 3.1 million logical IOs.

Next, I repeated this using a query based on ROW_NUMBER. I first ran the query without any indexes. It took 7263 ms with 7709 logical IOs. I added an index based on R_ID only and it again took about 7600 ms with 7709 logical IOs. I then dropped that index and added an index based on both R_ID and TEXT_DATA. This query then took 2406 ms with 7706 logical IOs. This is the script I used for testing:

set nocount on
use tempdb
drop table t1
go

-- sample table / data
CREATE TABLE t1 (R_ID nvarchar(5), text_data NVARCHAR(50));
--exec sp_help t1

insert into t1
select convert (nvarchar (5), i.iter),
'Text for ' + convert (nvarchar(5), i.iter)
+ '-' + convert (nchar(2), j.iter)
from mugambo.dbo.small_iterator (nolock) i
inner join mugambo.dbo.small_iterator (nolock) j
on j.iter <= 30
--select * from t1

--drop index t1.t1_ndx
--create index t1_ndx on t1(r_id)
create index t1_ndx on t1(r_id, text_data)
update statistics t1
go

declare @.begDt datetime set @.begDt = getdate()

/*
--insert into @.receiver
-- Retrieve TOP(3) Entries for Each R_ID
SELECT R_ID, text_data
FROM t1 AS a
WHERE text_data IN
(SELECT TOP(3) text_data
FROM t1 AS b
WHERE a.R_ID = b.R_ID
ORDER BY text_data)
*/

set statistics io on

select r_id,
text_data
from ( select r_id,
row_number () over
(partition by R_ID order by text_data)
as seq,
text_data
from t1
) x
where seq <= 3

set statistics io off

print ' '
select datediff (ms, @.begDt, getdate()) as [Elapsed Time]


-- Output:

-- r_id text_data
-- -- --
-- 1 Text for 1-1
-- 1 Text for 1-10
-- ...
-- 9999 Text for 9999-11

-- Table 't1'. Scan count 1, logical reads 7706, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
-- Elapsed Time
--
-- 2220

|||

Hi,

keeping same table as Lucky_p has dipicted , just try this

select *from

(SELECT i.r_id, i.text_data,

DENSE_RANK() OVER (PARTITION BY i.r_id order by text_data) as RANK

FROM t1 i) A where rank<=3

Madhu

|||

That's all nice and i agree my solution is not fast when the table is large.

Do you have a fast solution for SQL 2000 too? All your solutions are for SQL 2005.

|||

Lucky:

I cannot come up with a method for SQL Server 2000 that is any faster than your version. Hopefully, one of the senior members can shed some light; I struck out.


Dave

|||

I found an alternative that might be of some use:

declare @.top3 table
( r_id nvarchar (5) not null,
seq integer not null,
text_data nvarchar (50) not null,

primary key (r_id, seq)
)

insert into @.top3
select r_id,
1,
min(text_data)
from t1
group by r_id

insert into @.top3
select r_id,
2,
( select min (b.text_data) from t1 b
where a.r_id = b.r_id
and b.text_data > a.text_data
)
from @.top3 a

insert into @.top3
select r_id,
3,
( select min (b.text_data) from t1 b
where a.r_id = b.r_id
and b.text_data > a.text_data
)
from @.top3 a
where seq = 2


set statistics io off

print ' '
select datediff (ms, @.begDt, getdate()) as [Elapsed Time]


-- Output:

-- Table '#33ADF722'. Scan count 0, logical reads 66286, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 1, logical reads 7640, physical reads 0, read-ahead reads 0.
-- Table '#33ADF722'. Scan count 1, logical reads 97120, physical reads 0, read-ahead reads 0.
-- Table 'Worktable'. Scan count 1, logical reads 33468, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 32767, logical reads 98558, physical reads 0, read-ahead reads 0.
-- Table '#33ADF722'. Scan count 1, logical reads 100528, physical reads 0, read-ahead reads 0.
-- Table 'Worktable'. Scan count 1, logical reads 33468, physical reads 0, read-ahead reads 0.
-- Table 't1'. Scan count 32767, logical reads 98552, physical reads 0, read-ahead reads 0.
-- Elapsed Time
--
-- 2766

|||

I have an additional solution for SQL 2000 which uses a Partition calculation. But I'm not sure if its faster than the other 2000 compatible approach.

-- Create a Temporary Table using an additional column
-- Row-Number Partitioned by R_ID
SELECT R_ID , text_data,
(SELECT COUNT(*) FROM T1 AS b
WHERE b.R_ID = a.R_ID
AND (b.text_data < a.text_data
OR (b.text_data = a.text_data))) AS rownum
INTO #T1
FROM T1 AS a
ORDER BY R_ID, text_data;

-- Get the results from Temporary Table
SELECT R_ID, text_data FROM #T1
WHERE rownum <= 3

|||

Lucky P wrote:

I have an additional solution for SQL 2000 which uses a Partition calculation. But I'm not sure if its faster than the other 2000 compatible approach.

-- Create a Temporary Table using an additional column
-- Row-Number Partitioned by R_ID
SELECT R_ID , text_data,
(SELECT COUNT(*) FROM T1 AS b
WHERE b.R_ID = a.R_ID
AND (b.text_data < a.text_data
OR (b.text_data = a.text_data))) AS rownum
INTO #T1
FROM T1 AS a
ORDER BY R_ID, text_data;

-- Get the results from Temporary Table
SELECT R_ID, text_data FROM #T1
WHERE rownum <= 3

again with little modification u can fine tune this script.. eliminate Temp table

Select *from

(SELECT top 100 R_ID , text_data,

(SELECT COUNT(*) FROM T1 AS b

WHERE b.R_ID = a.R_ID

AND (b.text_data < a.text_data

OR (b.text_data = a.text_data))) AS rownum

FROM T1 AS a

ORDER BY R_ID, text_data) A

where rownum<4

Madhu

|||

I tested these other queries too with my "million-row" mockup and here is what I think:

If running SQL Server 2005 use either Madhu's or my first query|||

Your getting a partial result because of these line:

(SELECT top 100 R_ID , text_data,

If You change it to

(SELECT top 100 PERCENT R_ID , text_data,

You should get all the rows....

|||

Thanks for catching that lucky; I tested this one too and your original query is still much faster.


Dave

|||

ms sql server

data:


idno Email Category
1 a@.a.com c
2 b@.b.com c
3 b@.b.com c
4 b@.b.com c

only unique email address record are requierd.
1 a@.a.com c
2 b@.b.com c

what could be the query for such requirements.

How to get this relation(Need Sql Query)?

Hi friends

I have one Table called tblCategory.

I have three Column CatID, CatName, ParentID

I have many records in this Table

CatID CatName ParentID

1 Cat1 0

2 Cat2 1

3 Cat3 1

4 Cat4 2

5 Cat5 2

6 Cat6 0

7 Cat7 6

8 Cat8 6

9 Cat9 7

10 Cat10 7

11 Cat11 8

Here I have Main Category which has ParentID 0 [ Cat1 and Cat6 ]

I Have Sub categories of Cat1 Which has ParentID 1(CatID 1 of Cat1) [ Cat2 and Cat 3 ]

Cat 2 has also sub category with ParentID 2 (CatID 2 of Cat2) [ Cat4 and Cat5]

I want result looks like as

Cat1 Cat6 ->>>>>ParentID 0
- Cat2 -Cat7 ->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)
- - Cat4 - -Cat9 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7)
- - Cat5 - -Cat10 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7)
- Cat3 -Cat8 -->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)
--No record --Cat11

Can anybody give me solution?

Thanks

See if this article on working out JOIN syntax will help:http://www.mikesdotnetting.com/Article.aspx?ArticleID=72

|||

There are two tables but in my case I have only one table.

|||

impathan:

There are two tables but in my case I have only one table.

So you have. Sorry, I saw the word Relation in the title of your post and thought you were after somerthing else.

Is what you are after something like the threaded view of a discussion board or similar? If so, one solution might be a recursive function. If not, could you explain the logic beind the diagram you have supplied? I can't, for example see the basis on which Cat3 and Cat8 on the penultimate line are related.

|||

impathan:

There are two tables but in my case I have only one table.

You can query a table twice in the same statement and join it to itself. :) You just need to give each usage of the table a different table alias.

How to get the value of a SQL query before binding it to DataGrid?

I am using C#.Net, Visual web Developer, SQL server 2000.

I have a SQL query which I am binding it to a DataGrid.

SQL : "SELECT ord_number, ord_ID, ord_split, ord_Name, ETD_Date, OSP_FSD FROM ORDERS"

In My DataGrid I have a dynamic databound column.

I am able to bind one column to this databound column using following code.

BoundColumn ETDDate = new BoundColumn();
ETDDate.HeaderText = "ETD Date";
ETDDate.DataField = "OSP_FSD";
mygrid2.Columns.AddAt(ETDDate);

but now I want to bind this databound column based on the following criteria to two different database columns.

if(ord_split = 1)
{
ETDDate.DataField = "OSP_FSD";
}
else
{
ETDDate.DataField = "ETD_Date";
}

How to get value of ord_split before binding SQL to teh DataGrid? i.e I just want to take value of ord_split and not all the values of SQL.

Please Help!

HI~

ord_split if different in each row but if you change ETDDate.DataField it will affect all rows.

I am afraid you just want to display OSP_FSD for the rows " ord_split =1 " or ETD_Date if not.

If so you can change the text inGridView'sRowDataBound Event.

how to get the top value?

hi,

this my prediction query.

select Flattened (select $time as Date, [Perf] as Perf from PredictTimeSeries([Perf],100) where $Time <'1/1/2007' ) as A from [Stud_Model] WHERE [StudID]=8

Its giving me result where the date is less than 1/1/2007.i need only one result, where the date should be nearer to 1/1/2007. I am not able to use Top 1 inside like

select Flattened (select top 1 $time as Date, [Perf] as Perf from PredictTimeSeries([Perf],100) where $Time <'1/1/2007' ) as A from [Stud_Model] WHERE [StudID]=8

can anyone help.

Thanks,

Karthik

I haven't tried a query like that, but you can't use Top in that context. You may be able to use the TopCount function, I believe the syntax is

TopCount(<table expression>, <count>, <column-ref>) // the last two may be reversed.

TopCount is itself a table expression.

|||

hi jamie,

Its working cool.

Thanks a lot.

Wednesday, March 28, 2012

How to get the Top 10 Categories in Chart

Hi,

I would like to know how to get the Top 10 Categories from Reporting Services chart without using the scripting in T-SQL to query from db.

Is there a function like Ranking and then we filter the Ranking to be less than or equal 10 ?

Please kindly direct me in step by step to the way on how to achieve this as I am quite new in Reporting Services Smile

Thank you

best regards,

Tanipar

An example of top N in a report can be seen in the execution log samples provided by MS. (These reports allow you to view stats on who is using which report in reporting services)

Set a filter (right click - properties - filters) on your table/grouping/whatever
to be something like

expression
=Sum(Fields!Executions.Value)

operator
top N

value
=10|||

Hi,

Thank you

But after I follow your instruction I got the following error message, any idea what happen :

An error occured during local report processing

An error has occured during report processing

The processing of SortExpression for the list 'List1' cannot be performed. The comparison failed. Please check the data type returned by the SortExpression

I have ensure the one that the field that I sum is the numbers.

Please let me know if you have any idea on this.

Thanks

best regards,

Tanipar

|||

Hi,

After moving the TopN condition into the grouping, now I encounter another error :

An error has occured during report processing.

Failed to evaluate the FilterValue.

Can anyone help me ?

Many Thanks!

best regards,

Tanipar

|||I have this work already. Many thanks for your help !!!

how to get the status of a sql job

Hi Gurus,
can any one help me to get the job status of a sql job.
My requirement is as under
ordinary user (not SA) will query pass job name as argument to stored procedure and sp has to give me the job status.
Thanks in advanceYou can use SP_HELP_JOB and a user who is not a member of the sysadmin fixed role can use sp_help_job to view only the jobs he/she owns.

Execute permissions default to the public role in the msdb database.

How to get The Standard Query Languages general standard?

:) I wanna find a general standard in some database like ms sql,oracle,sybase..This standard is a rfc or another document which declared the base role how to work with sql..
Can u give me any thread??The only SQL standards that I recognize are the ISO SQL Standard (http://www.iso.org/iso/en/CatalogueDetailPage.CatalogueDetail?CSNUMBER=34132 &ICS1=35&ICS2=60&ICS3=&scopelist=) and the ANSI (http://webstore.ansi.org/ansidocstore/product.asp?sku=INCITS%2FISO%2FIEC+9075%2D2%2D2003 ) standard.

-PatP|||I'm not too sure how much use buying one of the standards would be, as meritoriuos they are. Virtually no server meets the (most recent) standards in their entireity, AND most servers have there own extensions and variations on the standard. So either, you use the reduced common set applicable to all db's, or get a specialist book on the db you are working with.

Personally I found the O'Reilly "SQL in a nutshell" a good basic reference But not a primer (it covers MySQL, Oracle, SQL Server (and one other I can't remember)). Its a bit sparse on examples (but that would be the same with a standards manual), but it provides sufficent pointers to jog the memory, or show the way forward. But there are others with masses of text, information and examples. The "in a nutshell" series are probably not the "best" for beginners, don't take offence I've made no assessment of your competance.|||cleverpig, i would definitely buy a book, it is much easier

if you really want to see the standard, you may read a draft of sql-92 here --
http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

note that most databases implement most of sql-92

don't spend too much time in there, though, because if you learn something in sql-92 there's no guarantee that it'll work in your particular database|||I'm certainly game with the idea of buying a book. As a general rule, they are significantly easier to read than the standards are!

Just as a note, the standards are what both the database engine writers and the book writers use for a reference. The standard is where they start. If you are looking for a clear, technically correct statement of what is required for a given level of SQL implementation, the standard document is where I would start.

The standard documents might not be suitable for everyone, but why start third-hand (with the interpretation provided by the book's writer)?

-PatP|||depends what cleverpig is trying to achieve. If CleverPig is going to write a SQL database then go to the standards to check what you are doing is correct, if CleverPig is writing some application software accessing a specific SQL engine then go buy a book relevent to that SQL implementation, or buy a book which identifies where varius flavours of SQL implementations vary from the standard and make sure Cleverpig writes code compliant to the lowest common denominator (if you wan ttomake your code protable).

The standard identifies what the server "should" do, but the servers often:- don't do it,
or dont do it the way the standard says they should,
or has implemented some other features not thought of at the time the standard was thrashed out, or has retained some features from previous versions which are not compatible with the current standard
even if they are compliant with most of the standard, they are still not standard compliant. On dodgy ground here but I'm not aware of any SQL implementation which is truly compliant to the satndards.|||:D Thank for your replies..They are very good suggestion about how to get and learn sql standard..
I think the sql standard is a common role,but the some sql implement has his owner's role base on thie sql standard!..
:eek: So we can use it fixable just as you said..

How to get the second biggest number using sql query?

Hi,

Now I have a task to get the second biggest number using sql query. I know that we can get the biggest number using SQL very easily: select Max(NumColumn) from aTable.

For example, I have the following records:

NumColumn

1

2

3

4

10

11

18

If I use "select Max(NumColumn) from aTable", I will get the number: 18.

But I need to use SQL to the second biggest number: 11.

How to do that? Thanks.

Hi,

Try this

Code Snippet

select max(NumColumn) from aTable where NumColumn<=(select max(NumColumn) from atable)

-- Edited (Previous query i wrote was for Mysql.sorry about that)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Or this...

Code Snippet

SELECT MAX(NumColumn) FROM aTable WHERE NumColum < (SELECT MAX(NumColumn) FROM aTable)

|||

Hi,

To calculate the nth highest no.

Code Snippet

' For 2nd Highest

Declare @.temp int

set @.temp = 1

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

' For 3rd Highest

Declare @.temp int

set @.temp = 2

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Try:

if the values are unique:

with cte

as

(

select *, row_number() over(order by NumColumn ASC) as rn

from dbo.t1

)

select *

from cte

where rn = 2

if the values are not unique

with cte

as

(

select *, dense_rank() over(order by NumColumn ASC) as rn

from dbo.t1

)

select *

from cte

where rn = 2

Example:

Code Snippet

use tempdb

go

declare @.t table (

NumColumn int

)

insert into @.t values(1)

insert into @.t values(2)

insert into @.t values(3)

insert into @.t values(4)

insert into @.t values(10)

insert into @.t values(11)

insert into @.t values(18)

;with cte

as

(

select *, row_number() over(order by NumColumn) as rn

from @.t

)

select *

from cte

where rn = 2

insert into @.t values(1)

;with cte

as

(

select *, dense_rank() over(order by NumColumn) as rn

from @.t

)

select *

from cte

where rn = 2

go

AMB|||

Suprotim - your queries don't work as advertised

@.temp = 2 this gives you the the max

@.temp = 3 gives 2nd highest

|||

What if you have

NumColumn

1

2

3

4

10

11

17

17

17

18

18

What number should be returned?|||

Hi Sql-pro,

Which one doesn't work?

I tried it against this :

NumColumn

1

2

3

4

10

11

18

Suprotim

|||

Hi,

Sorry, not trying to be a jerk but all 3 of them didn't work against 1, 2, 3, 4

Code Snippet

select max(AccountID) from Check_Account where AccountID<=(select max(AccountID) from Check_Account)

go

= 4

--2nd highest

Declare @.temp int

set @.temp = 1

SELECT MAX(AccountID) from Check_Account WHERE AccountID NOT IN ( SELECT TOP (@.temp - 1) AccountID FROM Check_Account ORDER BY AccountID DESC)

go

= 4

--3rd highest

Declare @.temp int

set @.temp = 2

SELECT MAX(AccountID) from Check_Account WHERE AccountID NOT IN ( SELECT TOP (@.temp - 1) AccountID FROM Check_Account ORDER BY AccountID DESC)

= 3

|||

Is your NumberColumn guaranteed to be unique? In other words, might you have values like this:

NumColumn

1

1

2

3

4

4

4

5

5

6

7

8

8

8

9

9

If so, what would the number you would like returned?

|||

Dear rusag,

Modified the query :

Code Snippet

Declare @.temp int

set @.temp = 2

;with cte

as

(

select DISTINCT * from atable

)

SELECT MAX(NumColumn) from cte WHERE NumColumn NOT IN ( SELECT TOP (@.temp -1) NumColumn FROM cte ORDER BY NumColumn DESC)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Dear SqlPro,

Code Snippet

I took the data 1,2,3,4

' For 2nd Highest

Declare @.temp int

set @.temp = 1

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

Returns 3

' For 3rd Highest

Declare @.temp int

set @.temp = 2

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)


Returns 2

How is it that you get different results?

Suprotim

|||

Well if you look at your 2nd highest query

You have @.temp = 1

and your subquery is SELECT TOP @.temp - 1

1 - 1 = 0 so your subquery returns nothing, and therefore your just getting the max

it's all semantics anyway, I think your approach is fine, just need to know that

@.temp = 2 returns 2nd highest

@.temp = 3 return 3rd highest

|||

Hai,

Try the following query

select NumColumn from
aTable t1
where N=(

select count(distinct t2.NumColumn)

from aTable t2 where t2.NumColumn>t1.NumColumn


)

Where N= position-1

If uwant to find second largest N should be =1 (2-1)

|||SELECT * FROM TABLE WHERE CONDITION ORDER BY DESC FIELDNAME LIMIT 1,1sql

How to get the second biggest number using sql query?

Hi,

Now I have a task to get the second biggest number using sql query. I know that we can get the biggest number using SQL very easily: select Max(NumColumn) from aTable.

For example, I have the following records:

NumColumn

1

2

3

4

10

11

18

If I use "select Max(NumColumn) from aTable", I will get the number: 18.

But I need to use SQL to the second biggest number: 11.

How to do that? Thanks.

Hi,

Try this

Code Snippet

select max(NumColumn) from aTable where NumColumn<=(select max(NumColumn) from atable)

-- Edited (Previous query i wrote was for Mysql.sorry about that)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Or this...

Code Snippet

SELECT MAX(NumColumn) FROM aTable WHERE NumColum < (SELECT MAX(NumColumn) FROM aTable)

|||

Hi,

To calculate the nth highest no.

Code Snippet

' For 2nd Highest

Declare @.temp int

set @.temp = 1

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

' For 3rd Highest

Declare @.temp int

set @.temp = 2

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Try:

if the values are unique:

with cte

as

(

select *, row_number() over(order by NumColumn ASC) as rn

from dbo.t1

)

select *

from cte

where rn = 2

if the values are not unique

with cte

as

(

select *, dense_rank() over(order by NumColumn ASC) as rn

from dbo.t1

)

select *

from cte

where rn = 2

Example:

Code Snippet

use tempdb

go

declare @.t table (

NumColumn int

)

insert into @.t values(1)

insert into @.t values(2)

insert into @.t values(3)

insert into @.t values(4)

insert into @.t values(10)

insert into @.t values(11)

insert into @.t values(18)

;with cte

as

(

select *, row_number() over(order by NumColumn) as rn

from @.t

)

select *

from cte

where rn = 2

insert into @.t values(1)

;with cte

as

(

select *, dense_rank() over(order by NumColumn) as rn

from @.t

)

select *

from cte

where rn = 2

go

AMB|||

Suprotim - your queries don't work as advertised

@.temp = 2 this gives you the the max

@.temp = 3 gives 2nd highest

|||

What if you have

NumColumn

1

2

3

4

10

11

17

17

17

18

18

What number should be returned?|||

Hi Sql-pro,

Which one doesn't work?

I tried it against this :

NumColumn

1

2

3

4

10

11

18

Suprotim

|||

Hi,

Sorry, not trying to be a jerk but all 3 of them didn't work against 1, 2, 3, 4

Code Snippet

select max(AccountID) from Check_Account where AccountID<=(select max(AccountID) from Check_Account)

go

= 4

--2nd highest

Declare @.temp int

set @.temp = 1

SELECT MAX(AccountID) from Check_Account WHERE AccountID NOT IN ( SELECT TOP (@.temp - 1) AccountID FROM Check_Account ORDER BY AccountID DESC)

go

= 4

--3rd highest

Declare @.temp int

set @.temp = 2

SELECT MAX(AccountID) from Check_Account WHERE AccountID NOT IN ( SELECT TOP (@.temp - 1) AccountID FROM Check_Account ORDER BY AccountID DESC)

= 3

|||

Is your NumberColumn guaranteed to be unique? In other words, might you have values like this:

NumColumn

1

1

2

3

4

4

4

5

5

6

7

8

8

8

9

9

If so, what would the number you would like returned?

|||

Dear rusag,

Modified the query :

Code Snippet

Declare @.temp int

set @.temp = 2

;with cte

as

(

select DISTINCT * from atable

)

SELECT MAX(NumColumn) from cte WHERE NumColumn NOT IN ( SELECT TOP (@.temp -1) NumColumn FROM cte ORDER BY NumColumn DESC)

HTH,
Suprotim Agarwal

--
http://www.dotnetcurry.com
--

|||

Dear SqlPro,

Code Snippet

I took the data 1,2,3,4

' For 2nd Highest

Declare @.temp int

set @.temp = 1

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)

Returns 3

' For 3rd Highest

Declare @.temp int

set @.temp = 2

SELECT MAX(NumColumn) from aTable WHERE NumColumn NOT IN ( SELECT TOP (@.temp - 1) NumColumn FROM atable ORDER BY NumColumn DESC)


Returns 2

How is it that you get different results?

Suprotim

|||

Well if you look at your 2nd highest query

You have @.temp = 1

and your subquery is SELECT TOP @.temp - 1

1 - 1 = 0 so your subquery returns nothing, and therefore your just getting the max

it's all semantics anyway, I think your approach is fine, just need to know that

@.temp = 2 returns 2nd highest

@.temp = 3 return 3rd highest

|||

Hai,

Try the following query

select NumColumn from
aTable t1
where N=(

select count(distinct t2.NumColumn)

from aTable t2 where t2.NumColumn>t1.NumColumn


)

Where N= position-1

If uwant to find second largest N should be =1 (2-1)

How to get the Script for an object using query Analyser?

Hi,

I wanted to know how to get the script for an object using query analyser is there a system procedure to get the script. how does the enterprise manager generate the script?

Check out sp_helpText in BOL.

Cheers,
Loonysan

|||

sp_helptext is used for procedure,view,trigger etc

what if i want to get the scrip of a table? or job like what we get in the enterprise manage using the GENERATE sCRIPT option

|||

sp_help describes database objects. It might not be in the exact format you need it, but you should be able to manipulate the stored procedure in the way you need it. I also did a query like the following and this gave me information like column name, datatype and length of a table. There are other columns in the syscolumns table that specifiy collation and if it can contain a null (isnullable field in syscolumns).

select c.[name],t.[name],c.length
from sysobjects o
join syscolumns c
on o.id = c.id
join systypes t
on c.xtype = t.xtype
where o.[name] = 'nissannow_orders'

Results:

CreateDate datetime 8
OrderDate datetime 8
ExportSubmissionDate datetime 8
ModifiedDate datetime 8
OrderID int 4
CustomerID int 4
DealerIDDealerVisited int 4
CreatedBy varchar 50
ShipPrimaryPhone varchar 20
ShipEmailAddress varchar 50
ModifiedBy varchar 50
ShipCity varchar 50
ShipStateProvince varchar 50
ShipZip varchar 20
ShipFirstName varchar 100
ShipLastName varchar 100
ShipAddress1 varchar 100

Let me know if you need any more assistance with this.

|||There is no easy way to do this in TSQL. You need to either write a SP that does the work using the metadata in the system tables or use the built-in client API like DMO/SMO. You can write VB scripts for example that uses DMO to generate scripts or DTS/SSIS tasks.

Monday, March 26, 2012

how to Get the result of executed query in file

All ,

Is it possible that i can get the result of executed select statement in a .txt file.

some thing like this

select * from mytablw to <some file name.txt>

Regards,

Ashish

You need to use BCP.

You either invoke it from a cmd window or use xp_cmdshell in SS.

Code Snippet

From cmd:

bcp "SELECT * FROM MyTable" queryout "c:\My Output File.txt" -c -Smyserver -Umylogin -Pmypswd

From SQL Server:

EXEC master..xp_cmdshell 'bcp "SELECT * FROM MyTable" queryout "c:\My Output File.txt" -c -Smyserver -Umylogin -Pmypswd'

Look up BCP in BOL for more options and parameters.

How to get the MDX query through Cube browser in BIDS?

Is there any means to get the MDX query generated internally when we browser the cube in Business Intilligence Development Studio (BIDS)?

Please let me know.

Thanks,

Austin.

SQL Server Profiler will let you capture query generated by BIDS.

Vidas Matelis

Friday, March 23, 2012

How to get the last Query executed?

Hello, i have a trigger and i want to know the query that raised it, or want to retrieve the last executed query by the server. I think it's a hard question but i know that someone can help me... ThanksOriginally posted by parmaia
Hello, i have a trigger and i want to know the query that raised it, or want to retrieve the last executed query by the server. I think it's a hard question but i know that someone can help me... Thanks

Fire up SQL Profiler and run a trace with the filters configured to limit it to the table in question (object).|||if object_id('dbo.test') is not null
drop table dbo.test
go
create table dbo.test (f1 int null)
go
create trigger dbo.trgIUD_test on dbo.test for insert, update, delete as
dbcc inputbuffer (@.@.spid)
go
insert dbo.test values (1);
go
drop table dbo.test
go|||Originally posted by Steve Duncan
Fire up SQL Profiler and run a trace with the filters configured to limit it to the table in question (object).

Hey, i didn't know that exists, thank you for your help!, has very very use full!

How to get the index of each row from a SELECT query in SQL ?

Hi,
I am making as SELECT query to fill a repeater, and I need to retrieve the index of each line of the query.
ie, I want to get a dataset like :
"0", "dataCol1", "dataCol2" for the first line
"1", "dataCol1", "dataCol2" for the second line
"2", "dataCol1", "dataCol2" for the third line
etc.
Anyone knows if there is a sql statement that does it ?
Thanks
Johanncheck this|||You can also create a temp table with an int identity column, insert the first table into the temp, and return it.

How to get the in Quarterly

Hi All,

I want to select the data from the table in Quarterly
i have the following query but it is suming all the
months and giving
in following query i want to show sum of 01 to
03months in row and o4 to 06 in one row...like
that if i give 200101 to 200112...it has to give me 4
quaters...how to do that..

select CONVERT(CHAR(4),period,112), sum(composite)
from cdh_price_gap
where CONVERT(CHAR(6),period,112) between '200101' and
'200106'
group by CONVERT(CHAR(4),period,112)
order by CONVERT(CHAR(4),period,112)

i used to convert to compare the date in this formate
200101 thats it...

thanksselect cast( (month(period)+2) / 3 as integer ) as quarter
, sum(composite)
from cdh_price_gap
group by cast( (month(period)+2) / 3 as integer )

rudy
http://r937.com/

How to get the full-text catalog name of mssql 2005 database through query?

Hello All,

Could any one please let me know how can I get the name of full-text catalog of a MS-SQL database through query?

My Intention to write an SQL-query is to do the following:

1. check if a databse has full-text catalog enabled.

2. If so then get the name of the full-text catalog.

3. Add "MOVE sysft_<full-text catalog name> TO <desired loc>.

Thanks and Regards,

Anbu

Here's a script that will get you the databases, and you can join that to the fulltext catalog views from there to do the rest of your work:

select * from sys.databases
where is_fulltext_enabled = 1
order by name

Paste this link in the URL bar of Books Online to find the catalogs for fulltext:

ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/tsqlref9/html/ab95e6f8-51dc-4018-9d19-cc0a6de893a5.htm

Buck Woody

|||

If a database has fulltext catalog enabled, then

select name,path from database-name.sys.fulltext_catalogs

should return the name of the fulltext catalog and the physical location of the catalog.

If the database is not enabled with any fulltext catalog then the above query will not return any rows.

How to get the full contents of the text column in syscomments

HI All ,

I need to extract the full text of a procedure from the syscomments table. When I run the query in query Analyzer and do a 'save as' to a textfile, I get only part of the text.

Appreciate any response on this.

Thanks

Two things, the first one is that the definition, column [text], is nvarchar(4000), so the output in QA should be a least 4000 characters. You can set it changing "Tools - Options... - Results - Maximum characters per column:" to 8192 (8k).

Second, if the definition, for example of the stored procedure, is greater than 4000, then you will have to select from multiple rows. The value of the column [colid] give you the sequence.

AMB

|||Thanks a lot ,it worked.sql

How to get the first occurrence of a record from a table?

i also have a query like this !

select DISTINCT(HospitalName),AvgTotalPatients,TotalPatient from TotalPatients ORDER BY HospitalName,AvgTotalPatients,TotalPatient;

Hospitalnames are unique and AvgTotalPatients is also unique for every hospital now what i get is all records of all hopsitals Tongue Tied reason is because in column TotalPatient there are entered many records for every hoapital so it takes all of them, what i want that it should select distinct hospitals with their AVgTotalPatients and only first occurence of TotalPatient.

what should i do? please help urgent

It sounds like you are aggregating data in some fashion.

It might be easier to help you find a good solution if you provided the code that creates [TotalPatients], or at least a better understanding of what/how [AvgTotalPatients] and [TotalPatient] really means.

However, your thinking 'should' be somewhat like this:

Code Snippet


SELECT
HospitalName,
AvgTotalPatients = avg( TotalPatients ),
TotalPatient = min( TotalPatients )
FROM TotalPatients
GROUP BY HospitalName
ORDER BY
HospitalName

|||

Thnx Arnie. I found solution to it 2 days back and it was something like this !

select DISTINCT(TP.HospitalName),TP.AvgTotalPatients,TP.TotalPatient from TotalPatients TP where TotalPatient = ( Select TOP 1(TotalPatient ) from TotalPatients where HospitalName = TP.HospitalName) ORDER BY HospitalName,AvgTotalPatients,TotalPatient;

very complicated one but i got what i wanted Smile

Regards

How to get the first occurrence of a record from a table?

I have the following query:

SELECTNotifications.[TimeStamp])

FROMdbo.vwGrantsMaster LEFT OUTER JOIN

dbo.CoFundNotifications ON dbo.vwGrantsMaster.GrantFMBId = dbo.CoFundNotifications.GrantsFMBId

It is returning multiple records from Notifications table since it allows multiple entries under a single GrantFMBId. For example for a single GrantFMBId there can be multiple TimeStamp. When retrieved all are appearing even distinct key word is used.

What I am looking is that to get only the first occurrence of a record for a GrantFMBId from Notifications table.

Any help?

Thank you in advance.

Am I in the wrong place...?|||

If I understand you correctly, you wish the FIRST row entered for a particular GrantsFMBId, [TimeStamp] combination.

Perhaps something like this will produce your desired results:


Code Snippet


SELECT dt.TS
FROM (SELECT
GrantFMBId,
TS = min( [TimeStamp] )
FROM dbo.vwGrantsMaster
GROUP BY GrantFMBId
) dt
LEFT JOIN dbo.CoFundNotifications cf
ON dt.GrantFMBId = cf.GrantFMBId