Showing posts with label distinct. Show all posts
Showing posts with label distinct. Show all posts

Friday, March 30, 2012

Help with SQL Query

Given the following two tables below, I need help in writing a query that would retreive only 3 or less distinct values of BDesc from tbB table for every row found in tbA.

for example:

I expect result to be:

Aid Bdesc
100 1st Desc for 100
100 2nd Desc for 100
100 3rd Desc for 100
200 1st Desc for 200
200 2nd Desc for 200
200 3rd Desc for 200
300 1st Desc for 300
300 2nd Desc for 300
300 3rd Desc for 300
400 1st Desc for 400
500 1st Desc for 500
500 3rd Desc for 500

The tables are:

use tempdb

go

set nocount on

if exists (select name from sysobjects where name = 'TbA')

Drop table TbA

Create Table TbA ( Aid int )

Insert into TbA values(100)

Insert into TbA values(200)

Insert into TbA values(300)

Insert into TbA values(400)

--select * from TbA

if exists (select name from sysobjects where name = 'TbB')

Drop table TbB

Create Table TbB ( Bid int , BDesc varchar(50) )

INSERT INTO TbB Values(100, '1st Desc for 100')

INSERT INTO TbB Values(100, '2nd Desc for 100')

INSERT INTO TbB Values(100, '3rd Desc for 100')

INSERT INTO TbB Values(100, '3rd Desc for 100')

INSERT INTO TbB Values(200, '1st Desc for 200')

INSERT INTO TbB Values(200, '2nd Desc for 200')

INSERT INTO TbB Values(200, '3rd Desc for 200')

INSERT INTO TbB Values(200, '4th Desc for 200')

INSERT INTO TbB Values(200, '1st Desc for 200')

INSERT INTO TbB Values(300, '1st Desc for 300')

INSERT INTO TbB Values(300, '2nd Desc for 300')

INSERT INTO TbB Values(300, '3rd Desc for 300')

INSERT INTO TbB Values(300, '4th Desc for 300')

INSERT INTO TbB Values(400, '1st Desc for 400')

INSERT INTO TbB Values(400, '1st Desc for 400')

INSERT INTO TbB Values(500, '1st Desc for 500')

INSERT INTO TbB Values(500, '1st Desc for 500')

INSERT INTO TbB Values(500, '3rd Desc for 500')

--select * from TbB

Thanks for your help with this...

Here ya go

Code Snippet

selectdistinct TbB.*

from(selectdistinct aid from TbA)as TbA

innerjoin TbB

on TbA.Aid = TbB.Bid

and TbB.BDesc in

(selectdistincttop 3 BDesc from TbB where Bid = TbA.Aid orderby BDesc)

|||Thanks|||

How about if I wanted to get the result like this:

ColA ColB

100 1st Descfor 100, 2nd Descfor 100, 3rd Descfor 100

200 1st Descfor 200, 2nd Descfor 200, 3rd Descfor 200

300 1st Descfor 300, 2nd Descfor 300, 3rd Descfor 300

400 1st Descfor 400

500 1st Descfor 500, 3rd Descfor 500

|||hi, you can try using a udf

CREATE FUNCTION dbo.GetBDesc
(
@.AID int
)
RETURNS varchar(800)
AS
BEGIN
DECLARE @.BDesc varchar(100)
SET @.BDesc = ''
SELECT
@.BDesc = @.BDesc + BDesc + ','
FROM (SELECT DISTINCT TOP 3 * FROM TbB a WHERE a.BID = @.AID) b
WHERE BID = @.AID
ORDER BY
BDesc

IF @.BDesc <> '' SET @.BDesc = LEFT(@.BDesc, LEN(@.BDesc) - 1)

RETURN @.BDesc

END

GO

select *
, dbo.GetBDesc(AID)
from tba|||

If you use SQL Server 2005 you dont need a function...

Here the sample,

Code Snippet

Create Table #TableA(

Aid int );

Insert into #TableA values(100)

Insert into #TableA values(200)

Insert into #TableA values(300)

Insert into #TableA values(400)

Insert into #TableA values(500)

Create Table #TableB(

Bid int

,BDesc varchar(50)

)

INSERT INTO #TableB Values(100, '1st Desc for 100')

INSERT INTO #TableB Values(100, '2nd Desc for 100')

INSERT INTO #TableB Values(100, '3rd Desc for 100')

INSERT INTO #TableB Values(100, '3rd Desc for 100')

INSERT INTO #TableB Values(200, '1st Desc for 200')

INSERT INTO #TableB Values(200, '2nd Desc for 200')

INSERT INTO #TableB Values(200, '3rd Desc for 200')

INSERT INTO #TableB Values(200, '4th Desc for 200')

INSERT INTO #TableB Values(200, '1st Desc for 200')

INSERT INTO #TableB Values(300, '1st Desc for 300')

INSERT INTO #TableB Values(300, '2nd Desc for 300')

INSERT INTO #TableB Values(300, '3rd Desc for 300')

INSERT INTO #TableB Values(300, '4th Desc for 300')

INSERT INTO #TableB Values(400, '1st Desc for 400')

INSERT INTO #TableB Values(400, '1st Desc for 400')

INSERT INTO #TableB Values(500, '1st Desc for 500')

INSERT INTO #TableB Values(500, '1st Desc for 500')

INSERT INTO #TableB Values(500, '3rd Desc for 500')

;With DistinctData

as

(

Select Distinct A.Aid,B.BDesc from #TableA A Join #TableB B On A.Aid =B.Bid

),

RowData

as

(

Select Aid,Bdesc,Row_Number() Over(Partition By Aid Order By BDesc) RowID From DistinctData

)

/*

Select

Aid,

BDesc

From

RowData

Where

RowID <=3

*/

Select Distinct

Aid

,Substring((Select ',' + BDesc as [text()] From RowData Sub Where Sub.Aid=Main.Aid And Sub.RowId<=3 For XML Path(''), Elements),2,8000) as Descs

From

RowData Main

|||MG,

How about these two queries (both require SQL 2005)

select a.aid, b.bdesc
from tbA a
cross apply
(select distinct top (3) bdesc from tbB b where b.bid = a.aid) b
;

select a.aid as ColA, stuff((select distinct top (3) ', ' + bdesc from tbB b where b.bid = a.aid order by 1 for xml path('')),1,2,'') as ColB
from tbA a
;

The second one puts them into a single column for you.

Rob|||I should have mentioned that this is for SQL 2000 and for an OLTP environment. The procedure processes approx. 20,000 rows and right now it's using cursor logic which is slowing things down, so I was looking for ways to use set based processing. The function idea is good, but again its going to be row by row processing.|||

The function approach should be a significant improvement over any cursor processing.

Is there something we're not understanding about what you want to accomplish?

|||

Hi Rhamille Golimlim,

There is an issue when using "order by" during an aggregate concatenation query.

PRB: Execution Plan and Results of Aggregate Concatenation Queries Depend Upon Expression Location

http://support.microsoft.com/default.aspx/kb/287515

AMB

|||thanks for the tip hunchback. would it still show a different execution plan if we put the order by inside the subquery?|||

Hi Rhamille Golimlim,

If you put the "order by" clause inside the derived table, then how are you going to be sure that the result is sorted if the only way to asure a sorted resultset is using the "order by" clause in the statement that pull the data?. It is like sorting inside a view and not using "order by" clause when you pull from the view.

Concatenating row values in T-SQL

http://www.projectdmx.com/tsql/rowconcatenate.aspx

AMB

|||hi hunchback,

cool, would the xml path approach be the best work around for this scenario? or are there other alternatives or tsql hacks?

/rhamille

Friday, March 23, 2012

Help with select query

Hi All,
I'm new-ish to SQL so bear with me...
If I run this query
SELECT Distinct Top 5
c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
FROM acocmp1.currsale c
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
group by c.stkcode
order by Quantity desc
I get the correct data:
AAA0111.000022.0000
DVD0036.000053.5600
ZZZ0234.000044.5000
BMM0023.000029.8500
BMM0013.000032.8500
but if I run this query:
SELECT Distinct Top 5
c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
'Amount'
FROM acocmp1.currsale c, opacif_Detail od
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
and c.stkcode = od.stkcode
group by c.stkcode, od.Description
order by Quantity desc
I get:
AAA01blah blah 57750.0000115500.0000
BMM001blah blah blah 8739.000095692.0500
DVD003blah blah blabber DVD4230.000037759.8000
BMM002Yadda Yadda2772.000027581.4000
DVD001Dooddly doo DVD1605.000013658.5500
c and od don't share a key that I can reference them with to keep the
linking one to one which I guess is what is causing the massive jump.
I just need the description column so that staff who can't read the
stock codes can read the table.
I'm pretty sure that I'm either missing something or that what I want
isn't possible and I'll have to find another way around.
Always worth writing something down to figure out the answer...
almost as soon as I'd typed "c and od don't share a key"
I decided to look for another table that held the description and the
code and solved my own problem
P
On 25 Jul, 17:22, Panda <paul.dam...@.gmail.com> wrote:
> Hi All,
> I'm new-ish to SQL so bear with me...
> If I run this query
> SELECT Distinct Top 5
> c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
> FROM acocmp1.currsale c
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> group by c.stkcode
> order by Quantity desc
> I get the correct data:
> AAA01 11.0000 22.0000
> DVD003 6.0000 53.5600
> ZZZ023 4.0000 44.5000
> BMM002 3.0000 29.8500
> BMM001 3.0000 32.8500
> but if I run this query:
> SELECT Distinct Top 5
> c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
> 'Amount'
> FROM acocmp1.currsale c, opacif_Detail od
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> and c.stkcode = od.stkcode
> group by c.stkcode, od.Description
> order by Quantity desc
> I get:
> AAA01 blah blah 57750.0000 115500.0000
> BMM001 blah blah blah 8739.0000 95692.0500
> DVD003 blah blah blabber DVD 4230.0000 37759.8000
> BMM002 Yadda Yadda 2772.0000 27581.4000
> DVD001 Dooddly doo DVD 1605.0000 13658.5500
> c and od don't share a key that I can reference them with to keep the
> linking one to one which I guess is what is causing the massive jump.
> I just need the description column so that staff who can't read the
> stock codes can read the table.
> I'm pretty sure that I'm either missing something or that what I want
> isn't possible and I'll have to find another way around.

Help with select query

Hi All,
I'm new-ish to SQL so bear with me...
If I run this query
SELECT Distinct Top 5
c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
FROM acocmp1.currsale c
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
group by c.stkcode
order by Quantity desc
I get the correct data:
AAA01 11.0000 22.0000
DVD003 6.0000 53.5600
ZZZ023 4.0000 44.5000
BMM002 3.0000 29.8500
BMM001 3.0000 32.8500
but if I run this query:
SELECT Distinct Top 5
c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
'Amount'
FROM acocmp1.currsale c, opacif_Detail od
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
and c.stkcode = od.stkcode
group by c.stkcode, od.Description
order by Quantity desc
I get:
AAA01 blah blah 57750.0000 115500.0000
BMM001 blah blah blah 8739.0000 95692.0500
DVD003 blah blah blabber DVD 4230.0000 37759.8000
BMM002 Yadda Yadda 2772.0000 27581.4000
DVD001 Dooddly doo DVD 1605.0000 13658.5500
c and od don't share a key that I can reference them with to keep the
linking one to one which I guess is what is causing the massive jump.
I just need the description column so that staff who can't read the
stock codes can read the table.
I'm pretty sure that I'm either missing something or that what I want
isn't possible and I'll have to find another way around.Always worth writing something down to figure out the answer...
almost as soon as I'd typed "c and od don't share a key"
I decided to look for another table that held the description and the
code and solved my own problem
P
On 25 Jul, 17:22, Panda <paul.dam...@.gmail.com> wrote:
> Hi All,
> I'm new-ish to SQL so bear with me...
> If I run this query
> SELECT Distinct Top 5
> c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
> FROM acocmp1.currsale c
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> group by c.stkcode
> order by Quantity desc
> I get the correct data:
> AAA01 11.0000 22.0000
> DVD003 6.0000 53.5600
> ZZZ023 4.0000 44.5000
> BMM002 3.0000 29.8500
> BMM001 3.0000 32.8500
> but if I run this query:
> SELECT Distinct Top 5
> c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
> 'Amount'
> FROM acocmp1.currsale c, opacif_Detail od
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> and c.stkcode = od.stkcode
> group by c.stkcode, od.Description
> order by Quantity desc
> I get:
> AAA01 blah blah 57750.0000 115500.0000
> BMM001 blah blah blah 8739.0000 95692.0500
> DVD003 blah blah blabber DVD 4230.0000 37759.8000
> BMM002 Yadda Yadda 2772.0000 27581.4000
> DVD001 Dooddly doo DVD 1605.0000 13658.5500
> c and od don't share a key that I can reference them with to keep the
> linking one to one which I guess is what is causing the massive jump.
> I just need the description column so that staff who can't read the
> stock codes can read the table.
> I'm pretty sure that I'm either missing something or that what I want
> isn't possible and I'll have to find another way around.

Help with select query

Hi All,
I'm new-ish to SQL so bear with me...
If I run this query
SELECT Distinct Top 5
c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
FROM acocmp1.currsale c
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
group by c.stkcode
order by Quantity desc
I get the correct data:
AAA01 11.0000 22.0000
DVD003 6.0000 53.5600
ZZZ023 4.0000 44.5000
BMM002 3.0000 29.8500
BMM001 3.0000 32.8500
but if I run this query:
SELECT Distinct Top 5
c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
'Amount'
FROM acocmp1.currsale c, opacif_Detail od
WHERE (c.STKCODE Not In ('i98','SUBS'))
and (c.trandate = '2007-07-24 00:00:00')
and c.stkcode = od.stkcode
group by c.stkcode, od.Description
order by Quantity desc
I get:
AAA01 blah blah 57750.0000 115500.0000
BMM001 blah blah blah 8739.0000 95692.0500
DVD003 blah blah blabber DVD 4230.0000 37759.8000
BMM002 Yadda Yadda 2772.0000 27581.4000
DVD001 Dooddly doo DVD 1605.0000 13658.5500
c and od don't share a key that I can reference them with to keep the
linking one to one which I guess is what is causing the massive jump.
I just need the description column so that staff who can't read the
stock codes can read the table.
I'm pretty sure that I'm either missing something or that what I want
isn't possible and I'll have to find another way around.Always worth writing something down to figure out the answer...
almost as soon as I'd typed "c and od don't share a key"
I decided to look for another table that held the description and the
code and solved my own problem
P
On 25 Jul, 17:22, Panda <paul.dam...@.gmail.com> wrote:
> Hi All,
> I'm new-ish to SQL so bear with me...
> If I run this query
> SELECT Distinct Top 5
> c.stkcode, sum(c.qty) as 'Quantity', sum(c.amount) as 'Amount'
> FROM acocmp1.currsale c
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> group by c.stkcode
> order by Quantity desc
> I get the correct data:
> AAA01 11.0000 22.0000
> DVD003 6.0000 53.5600
> ZZZ023 4.0000 44.5000
> BMM002 3.0000 29.8500
> BMM001 3.0000 32.8500
> but if I run this query:
> SELECT Distinct Top 5
> c.stkcode, od.description, sum(c.qty) as 'Quantity', sum(c.amount) as
> 'Amount'
> FROM acocmp1.currsale c, opacif_Detail od
> WHERE (c.STKCODE Not In ('i98','SUBS'))
> and (c.trandate = '2007-07-24 00:00:00')
> and c.stkcode = od.stkcode
> group by c.stkcode, od.Description
> order by Quantity desc
> I get:
> AAA01 blah blah 57750.0000 115500.0000
> BMM001 blah blah blah 8739.0000 95692.0500
> DVD003 blah blah blabber DVD 4230.0000 37759.8000
> BMM002 Yadda Yadda 2772.0000 27581.4000
> DVD001 Dooddly doo DVD 1605.0000 13658.5500
> c and od don't share a key that I can reference them with to keep the
> linking one to one which I guess is what is causing the massive jump.
> I just need the description column so that staff who can't read the
> stock codes can read the table.
> I'm pretty sure that I'm either missing something or that what I want
> isn't possible and I'll have to find another way around.

Monday, March 19, 2012

Help with query....

Please see query below:

SELECT COUNT(DISTINCT target) FROM iislog where target like '%answeringservice%'

The result of the query is 71, is there a way to list the values out in the output of the query.

for example: /answeringservice/default.asp = 3200
/answeringservice/deny.asp = 3700

Thanking you all in advance.

Lystrayes

SELECT DISTINCT target FROM iislog where target like '%answeringservice%'|||No

SELECT DISTINCT target, Count(target) as 'total' FROM iislog where target like '%answeringservice%'
Group By target|||the question was "is there a way to list the values out in the output of the query"

so you're saying it's not possible, white knight?

:)

by the way, when you use GROUP BY, the DISTINCT is redundant|||Yes it's possible

The code given did not do it!
sorry If I confused the issue|||White Knight, the code work well, thanks

Lystra

Monday, March 12, 2012

help with query

Using the included stored procedure I am getting the following result.
However I need this to return the DISTINCT forum.ID from the tables while
maintaining the correct post count, topic count and last post date.
Columns
c_ID t_ID f_ID c_Name f_Titlle TopicCount PostCount LastPostDate
Results
2 1 55 Equipment Lures 4 1 2005-04-20 15:27:41.047
2 2 55 Equipment Lures 4 0 NULL
2 3 55 Equipment Lures 4 1 2005-04-20 15:27:41.093
2 4 55 Equipment Lures 4 0 NULL
2 5 57 Equipment Boats & Motors 4 2 2005-04-20 15:27:41.077
2 6 57 Equipment Boats & Motors 4 0 NULL
2 7 57 Equipment Boats & Motors 4 0 NULL
2 8 57 Equipment Boats & Motors 4 0 NULL
1 9 52 Fishing Bass Fishing 2 1 2005-04-20 15:27:41.077
1 10 52 Fishing Bass Fishing 2 0 NULL
1 11 53 Fishing Crappie Fishing 1 0 NULL
1 12 54 Fishing Cat Fishing 1 0 NULL
================================================== ==
attempt at storedprocedure
================================================== ==
SELECT C.ID AS c_ID, T.ID as t_ID, f.ID AS f_ID,
C.Name AS c_Name,
F.Title AS f_Title,
(SELECT COUNT(ID) FROM Topic WHERE [f_ID]=F.ID) AS TopicCount,
(SELECT COUNT(ID) FROM Post WHERE [t_ID]=T.ID) AS PostCount,
(SELECT MAX([Date Entered]) FROM Post WHERE [t_ID]=T.ID) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON t.f_ID = F.ID
================================================== ==
table structure being used
================================================== ==
CREATE TABLE [dbo].[Post] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Text] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[t_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[r_ID] [numeric](18, 0) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Category] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Topic] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[f_id] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Forum] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[cat_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO
I think that this is what you need:
SELECT C.ID AS c_ID, f.ID AS f_ID, C.Name AS c_Name, F.Title AS
f_Title,
COUNT(DISTINCT t.ID) as TopicCount,
COUNT(*) AS PostCount,
MAX(P.[Date Entered]) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON T.f_ID = F.ID
INNER JOIN Post P ON P.t_ID = T.ID
GROUP BY C.ID, f.ID, C.Name, F.Title
It would have been useful if you also posted sample data (as INSERT
statements) and expected results; see: http://www.aspfaq.com/5006
Razvan

Help With Query

Hello,
I am selecting DISTINCT records from a table:
"SELECT DISTINCT Model, Description FROM Warranty"
This works great, but I would like to concatinate some other data in the
returned records (possibly with a JOIN)
From the same table I would like the returned records to return "Family" and
"Price".
So the returned records would be:
Model Description Family Price (with the Model and Description being
Distrinct).
NOTE: There is a Primary Key Called "ID".
Maybe something like:
SELECT DISCTINCT C1.Model, C1.Description FROM Warranty AS C1, Warranty AS
C2 (Select C2.Family, C2.Price FROM C2 ON C1.ID = C2.ID)
Any help is greatly appreciated,
Thanks,
Chuck
Hi Charles
How about
SELECT Model, Description, MAX(Family) AS [Family], Max(Price) AS [Price]
FROM Warranty
GROUP BY Model, Description
John

>
"Charles A. Lackman" wrote:

> Hello,
> I am selecting DISTINCT records from a table:
> "SELECT DISTINCT Model, Description FROM Warranty"
> This works great, but I would like to concatinate some other data in the
> returned records (possibly with a JOIN)
> From the same table I would like the returned records to return "Family" and
> "Price".
> So the returned records would be:
> Model Description Family Price (with the Model and Description being
> Distrinct).
> NOTE: There is a Primary Key Called "ID".
> Maybe something like:
> SELECT DISCTINCT C1.Model, C1.Description FROM Warranty AS C1, Warranty AS
> C2 (Select C2.Family, C2.Price FROM C2 ON C1.ID = C2.ID)
> Any help is greatly appreciated,
> Thanks,
> Chuck
>
>

help with query

Using the included stored procedure I am getting the following result.
However I need this to return the DISTINCT forum.ID from the tables while
maintaining the correct post count, topic count and last post date.
Columns
c_ID t_ID f_ID c_Name f_Titlle TopicCount PostCount LastPostDate
Results
2 1 55 Equipment Lures 4 1 2005-04-20 15:27:41.047
2 2 55 Equipment Lures 4 0 NULL
2 3 55 Equipment Lures 4 1 2005-04-20 15:27:41.093
2 4 55 Equipment Lures 4 0 NULL
2 5 57 Equipment Boats & Motors 4 2 2005-04-20 15:27:41.077
2 6 57 Equipment Boats & Motors 4 0 NULL
2 7 57 Equipment Boats & Motors 4 0 NULL
2 8 57 Equipment Boats & Motors 4 0 NULL
1 9 52 Fishing Bass Fishing 2 1 2005-04-20 15:27:41.077
1 10 52 Fishing Bass Fishing 2 0 NULL
1 11 53 Fishing Crappie Fishing 1 0 NULL
1 12 54 Fishing Cat Fishing 1 0 NULL
==================================================== attempt at storedprocedure
==================================================== SELECT C.ID AS c_ID, T.ID as t_ID, f.ID AS f_ID,
C.Name AS c_Name,
F.Title AS f_Title,
(SELECT COUNT(ID) FROM Topic WHERE [f_ID]=F.ID) AS TopicCount,
(SELECT COUNT(ID) FROM Post WHERE [t_ID]=T.ID) AS PostCount,
(SELECT MAX([Date Entered]) FROM Post WHERE [t_ID]=T.ID) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON t.f_ID = F.ID
==================================================== table structure being used
==================================================== CREATE TABLE [dbo].[Post] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Text] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[t_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[r_ID] [numeric](18, 0) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Category] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Topic] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[f_id] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Forum] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[cat_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GOI think that this is what you need:
SELECT C.ID AS c_ID, f.ID AS f_ID, C.Name AS c_Name, F.Title AS
f_Title,
COUNT(DISTINCT t.ID) as TopicCount,
COUNT(*) AS PostCount,
MAX(P.[Date Entered]) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON T.f_ID = F.ID
INNER JOIN Post P ON P.t_ID = T.ID
GROUP BY C.ID, f.ID, C.Name, F.Title
It would have been useful if you also posted sample data (as INSERT
statements) and expected results; see: http://www.aspfaq.com/5006
Razvan

help with query

Using the included stored procedure I am getting the following result.
However I need this to return the DISTINCT forum.ID from the tables while
maintaining the correct post count, topic count and last post date.

Columns
c_ID t_ID f_ID c_Name f_Titlle TopicCount PostCount LastPostDate

Results
2 1 55 Equipment Lures 4 1 2005-04-20 15:27:41.047
2 2 55 Equipment Lures 4 0 NULL
2 3 55 Equipment Lures 4 1 2005-04-20 15:27:41.093
2 4 55 Equipment Lures 4 0 NULL
2 5 57 Equipment Boats & Motors 4 2 2005-04-20 15:27:41.077
2 6 57 Equipment Boats & Motors 4 0 NULL
2 7 57 Equipment Boats & Motors 4 0 NULL
2 8 57 Equipment Boats & Motors 4 0 NULL
1 9 52 Fishing Bass Fishing 2 1 2005-04-20 15:27:41.077
1 10 52 Fishing Bass Fishing 2 0 NULL
1 11 53 Fishing Crappie Fishing 1 0 NULL
1 12 54 Fishing Cat Fishing 1 0 NULL

================================================== ==
attempt at storedprocedure
================================================== ==
SELECT C.ID AS c_ID, T.ID as t_ID, f.ID AS f_ID,
C.Name AS c_Name,
F.Title AS f_Title,
(SELECT COUNT(ID) FROM Topic WHERE [f_ID]=F.ID) AS TopicCount,
(SELECT COUNT(ID) FROM Post WHERE [t_ID]=T.ID) AS PostCount,
(SELECT MAX([Date Entered]) FROM Post WHERE [t_ID]=T.ID) AS LastPostDate

FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON t.f_ID = F.ID

================================================== ==
table structure being used
================================================== ==
CREATE TABLE [dbo].[Post] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Text] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[t_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[r_ID] [numeric](18, 0) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

CREATE TABLE [dbo].[Category] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Topic] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[f_id] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Forum] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[cat_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GOI think that this is what you need:

SELECT C.ID AS c_ID, f.ID AS f_ID, C.Name AS c_Name, F.Title AS
f_Title,
COUNT(DISTINCT t.ID) as TopicCount,
COUNT(*) AS PostCount,
MAX(P.[Date Entered]) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON T.f_ID = F.ID
INNER JOIN Post P ON P.t_ID = T.ID
GROUP BY C.ID, f.ID, C.Name, F.Title

It would have been useful if you also posted sample data (as INSERT
statements) and expected results; see: http://www.aspfaq.com/5006

Razvan

Friday, March 9, 2012

Help with query

I have 3 tables:
Words
WordLists
WordsInLists
I need to make a query to select other words (distinct) that appear on the same list of a given word, so what I did was something like
Select the top 50 lists where word XXX appears, put into a cursor and loop the cursor to list all the words that belong to the same list where word XXX is, this works fine, but the problem is that I obviously get different sets of results (one for each list in the cursor), how can I make to put all the results in the same resultset?, is this possible without creating a temp table?
Thanks
I'm not sure that I completely understand the relationship between tables or what you're looking for ... but here is the SQL based on my interpretation of your question:

SELECT DISTINCT
wil2.list
, wil2.word
FROM wordsinlists AS wil2
, (SELECT wl.list
FROM words AS w
, wordlists AS wl
, wordsinlists AS wil
WHERE w.word = wil.word
AND wl.list = wil.list
AND w.word = 'XXX') AS subquery
WHERE subquery.list = wil2.list
AND wil2.word != 'XXX';

This will give you all lists and associated words in the lists containing 'XXX'. If you just want the words, delete wil2.list.

Hope this helps,
Josh|||This can be done in a single query. It would help if you post some sample schema and data using CREATE TABLE & INSERT statements. And the expected results.|||I ended up doing nested selects using the IN directive and everything works fine.
Thanks!

help with query

Using the included stored procedure I am getting the following result.
However I need this to return the DISTINCT forum.ID from the tables while
maintaining the correct post count, topic count and last post date.
Columns
c_ID t_ID f_ID c_Name f_Titlle TopicCount PostCount LastPostDate
Results
2 1 55 Equipment Lures 4 1 2005-04-20 15:27:41.047
2 2 55 Equipment Lures 4 0 NULL
2 3 55 Equipment Lures 4 1 2005-04-20 15:27:41.093
2 4 55 Equipment Lures 4 0 NULL
2 5 57 Equipment Boats & Motors 4 2 2005-04-20 15:27:41.077
2 6 57 Equipment Boats & Motors 4 0 NULL
2 7 57 Equipment Boats & Motors 4 0 NULL
2 8 57 Equipment Boats & Motors 4 0 NULL
1 9 52 Fishing Bass Fishing 2 1 2005-04-20 15:27:41.077
1 10 52 Fishing Bass Fishing 2 0 NULL
1 11 53 Fishing Crappie Fishing 1 0 NULL
1 12 54 Fishing Cat Fishing 1 0 NULL
========================================
============
attempt at storedprocedure
========================================
============
SELECT C.ID AS c_ID, T.ID as t_ID, f.ID AS f_ID,
C.Name AS c_Name,
F.Title AS f_Title,
(SELECT COUNT(ID) FROM Topic WHERE [f_ID]=F.ID) AS TopicCount,
(SELECT COUNT(ID) FROM Post WHERE [t_ID]=T.ID) AS PostCount,
(SELECT MAX([Date Entered]) FROM Post WHERE [t_ID]=T.ID) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON t.f_ID = F.ID
========================================
============
table structure being used
========================================
============
CREATE TABLE [dbo].[Post] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Text] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[t_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[r_ID] [numeric](18, 0) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Category] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Topic] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[f_id] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Forum] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[cat_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GOHere are a couple of possible solutions:
Select C.ID, C.Name, F.ID, F.Title
, (Select Count(*) From Topic As T1 Where T1.F_Id = F.Id) As TopicCount
, (Select Count(*)
From Post As P2
Join Topic As T2
On P2.T_Id = T2.ID
Where T2.F_Id = F.Id) As PostCount
, (Select Max(P3.[DateEntered]
From Post As P3
Join Topic As T3
On P3.T_Id = T3.ID
Where T3.F_Id = F.Id) As LastPostDate
From Category C
Join Forum F
On F.cat_ID = C.ID
Note that you do not need the join to Posts in the main query here. That avo
ids
your duplication problem.
Another, cleaner solution would be:
Select C.ID, C.Name, F.ID, F.Title
, Stats.PostCount
, Stats.TopicCount
, Stats.LastPostDate
From Category C
Join Forum F
On F.cat_ID = C.ID
Join (
Select F_Id
, Count(*) As PostCount
, Count(Distinct(T1.Id) As TopicCount
, Max(P1.DateEntered) As LastPostDate
From Post As P1
Join Topic As T1
On P1.T_Id = T3.ID
Group By F_Id
) As Stats
On F.ID = Stats.F_Id
HTH
Thomas|||I think that this is what you need:
SELECT C.ID AS c_ID, f.ID AS f_ID, C.Name AS c_Name, F.Title AS
f_Title,
COUNT(DISTINCT t.ID) as TopicCount,
COUNT(*) AS PostCount,
MAX(P.[Date Entered]) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON T.f_ID = F.ID
INNER JOIN Post P ON P.t_ID = T.ID
GROUP BY C.ID, f.ID, C.Name, F.Title
It would have been useful if you also posted sample data (as INSERT
statements) and expected results; see: http://www.aspfaq.com/5006
Razvan

Help With Query

Hello,
I am selecting DISTINCT records from a table:
"SELECT DISTINCT Model, Description FROM Warranty"
This works great, but I would like to concatinate some other data in the
returned records (possibly with a JOIN)
From the same table I would like the returned records to return "Family" and
"Price".
So the returned records would be:
Model Description Family Price (with the Model and Description being
Distrinct).
NOTE: There is a Primary Key Called "ID".
Maybe something like:
SELECT DISCTINCT C1.Model, C1.Description FROM Warranty AS C1, Warranty AS
C2 (Select C2.Family, C2.Price FROM C2 ON C1.ID = C2.ID)
Any help is greatly appreciated,
Thanks,
ChuckHi Charles
How about
SELECT Model, Description, MAX(Family) AS [Family], Max(Price) AS [P
rice]
FROM Warranty
GROUP BY Model, Description
John

>
"Charles A. Lackman" wrote:

> Hello,
> I am selecting DISTINCT records from a table:
> "SELECT DISTINCT Model, Description FROM Warranty"
> This works great, but I would like to concatinate some other data in the
> returned records (possibly with a JOIN)
> From the same table I would like the returned records to return "Family" a
nd
> "Price".
> So the returned records would be:
> Model Description Family Price (with the Model and Description being
> Distrinct).
> NOTE: There is a Primary Key Called "ID".
> Maybe something like:
> SELECT DISCTINCT C1.Model, C1.Description FROM Warranty AS C1, Warranty AS
> C2 (Select C2.Family, C2.Price FROM C2 ON C1.ID = C2.ID)
> Any help is greatly appreciated,
> Thanks,
> Chuck
>
>

help with query

Using the included stored procedure I am getting the following result.
However I need this to return the DISTINCT forum.ID from the tables while
maintaining the correct post count, topic count and last post date.
Columns
c_ID t_ID f_ID c_Name f_Titlle TopicCount PostCount LastPostDate
Results
2 1 55 Equipment Lures 4 1 2005-04-20 15:27:41.047
2 2 55 Equipment Lures 4 0 NULL
2 3 55 Equipment Lures 4 1 2005-04-20 15:27:41.093
2 4 55 Equipment Lures 4 0 NULL
2 5 57 Equipment Boats & Motors 4 2 2005-04-20 15:27:41.077
2 6 57 Equipment Boats & Motors 4 0 NULL
2 7 57 Equipment Boats & Motors 4 0 NULL
2 8 57 Equipment Boats & Motors 4 0 NULL
1 9 52 Fishing Bass Fishing 2 1 2005-04-20 15:27:41.077
1 10 52 Fishing Bass Fishing 2 0 NULL
1 11 53 Fishing Crappie Fishing 1 0 NULL
1 12 54 Fishing Cat Fishing 1 0 NULL
========================================
============
attempt at storedprocedure
========================================
============
SELECT C.ID AS c_ID, T.ID as t_ID, f.ID AS f_ID,
C.Name AS c_Name,
F.Title AS f_Title,
(SELECT COUNT(ID) FROM Topic WHERE [f_ID]=F.ID) AS TopicCount,
(SELECT COUNT(ID) FROM Post WHERE [t_ID]=T.ID) AS PostCount,
(SELECT MAX([Date Entered]) FROM Post WHERE [t_ID]=T.ID) AS LastPost
Date
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON t.f_ID = F.ID
========================================
============
table structure being used
========================================
============
CREATE TABLE [dbo].[Post] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Text] [text] COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[t_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL ,
[r_ID] [numeric](18, 0) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Category] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Topic] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NUL
L ,
[Date Entered] [datetime] NOT NULL ,
[f_id] [numeric](18, 0) NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Forum] (
[ID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NUL
L ,
[cat_ID] [numeric](18, 0) NOT NULL ,
[Date Entered] [datetime] NOT NULL
) ON [PRIMARY]
GOI think that this is what you need:
SELECT C.ID AS c_ID, f.ID AS f_ID, C.Name AS c_Name, F.Title AS
f_Title,
COUNT(DISTINCT t.ID) as TopicCount,
COUNT(*) AS PostCount,
MAX(P.[Date Entered]) AS LastPostDate
FROM Category C
INNER JOIN Forum F ON F.cat_ID = C.ID
INNER JOIN Topic T ON T.f_ID = F.ID
INNER JOIN Post P ON P.t_ID = T.ID
GROUP BY C.ID, f.ID, C.Name, F.Title
It would have been useful if you also posted sample data (as INSERT
statements) and expected results; see: http://www.aspfaq.com/5006
Razvan