Showing posts with label writing. Show all posts
Showing posts with label writing. Show all posts

Friday, March 23, 2012

Need some practice

Please point me to a web resource from where I can study:

1) writing complex queries such as those involving HAVING, mult-level
nested queries, GROUP BY, T-SQL functions

2) Joins - a lot of practice

3) Stored Procedures, transactions, cursors and triggers - I need some
heavy-duty practice

Where can I get some good practice of the above? Also, please recommend
a good SQL Server/T-SQL book in the light of the above requirement.Here's a good one for joins. I like the colors for the join tables:

http://www.tek-tips.com/faqs.cfm?fid=4785|||Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
working SQL programmers. And my house payment :)|||> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)

The book is of little use to working SQL programmers, a lot of the examples
aren't directly useable in SQL Server nor do they scale into the real world.

People are better off spending a couple of minutes searching GOOGLE for the
answers.

--
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials

"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1144801857.130733.158410@.i40g2000cwc.googlegr oups.com...
> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)

Need some practice

Please point me to a web resource from where I can study:
1) writing complex queries such as those involving HAVING, mult-level
nested queries, GROUP BY, T-SQL functions
2) Joins - a lot of practice
3) Stored Procedures, transactions, cursors and triggers - I need some
heavy-duty practice
Where can I get some good practice of the above? Also, please recommend
a good SQL Server/T-SQL book in the light of the above requirement.Some basic sites that have a couple examples...
http://www.w3schools.com/sql/sql_intro.asp
http://sqlzoo.net/
http://www.geocities.com/SiliconVal.../2207/sql1.html
If you want more comlicated examples, this forum may be the most useful.
You will have to sort through a lot of different posts that do not have what
you are looking for, but you will find dozens of solutions to various
problems that you can learn from.
"Water Cooler v2" <wtr_clr@.yahoo.com> wrote in message
news:1144682834.749751.324310@.i39g2000cwa.googlegroups.com...
> Please point me to a web resource from where I can study:
> 1) writing complex queries such as those involving HAVING, mult-level
> nested queries, GROUP BY, T-SQL functions
> 2) Joins - a lot of practice
> 3) Stored Procedures, transactions, cursors and triggers - I need some
> heavy-duty practice
>
> Where can I get some good practice of the above? Also, please recommend
> a good SQL Server/T-SQL book in the light of the above requirement.
>|||Here's a good one for joins. I like the colors for the join tables:
http://www.tek-tips.com/faqs.cfm?fid=4785|||Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
working SQL programmers. And my house payment :)|||> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)
The book is of little use to working SQL programmers, a lot of the examples
aren't directly useable in SQL Server nor do they scale into the real world.
People are better off spending a couple of minutes searching GOOGLE for the
answers.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1144801857.130733.158410@.i40g2000cwc.googlegroups.com...
> Have you gotten a copy of SQL FOR SMARTIES yet? It is required for
> working SQL programmers. And my house payment :)
>

Wednesday, March 21, 2012

Need some help writing part of the derived column component

Hey. I need to see if "/" is present in the column11 and if it's then just pass it as is or do the substring part. How do I get this to work? It's giving me an error. This is for a TimeDate column. I can get a 20060813 or 2006/08/13.I'm using the below and it's giving me an error saying that It should be DT_BOOL and I'm trying to return DT_I4.

findstring(Column11,"/",2) ? Column11 : SUBSTRING(TRIM(Column11),1,4) + "-" + SUBSTRING(TRIM(Column11),5,2) + "-" + SUBSTRING(TRIM(Column11),7,2)

Thank you

Tej

Tej,

Your test should be: findstring(Column11,"/",2)!=0 . You're testing for true or false(Boolean). findstring returns the location of the string to be found.

Frank

|||

Hey Frank. I tried (dt_bool)findstring(Column11,"/",2)

Is that correct or an error? Please let me know. I'll use what you asked me to in this case but just wanted to make sure. Thank you.

|||

Yes, that will work also.

Frank

Monday, March 12, 2012

Need Query Help for Search

I am writing a small search feature to return a list of companies whose name "Begins with" a certain string (up to 5 chars) provided by the user via a textbox. I want the results to only return results that begin with the letter/letters specified. Below I will put the code that I came up with that isn't working quite how I expected. I am new to this so any assistance and short explanation would be very much apperciated.

sql="SELECT distinct cm.cmmst_id, cm.cm_compno, cm.cm_cname1 + ' ' + cm.cm_cname2 AS cm_cname1, cm_tele, cm_fax, cm_s16 "

sql=sql & "FROM cmmst cm "

sql=sql & "WHERE cm_cname1 + ' ' + cm_cname2 LIKE '%" companyNameBegins,"'","''") & "%' " sql=sql & "AND (cm_mbtyp='M' OR cm_mbtyp='SUBDIV') " sql=sql & "ORDER BY cm_s16 DESC, cm_cname1 ASC"

companyNameBegins is the string passed in by the user

Thanks,

Zoop

(1) Use parameterized Queries. Your code will look simpler and neater and you can avoid SQL Injection Attacks (Google for more info on this topic)

(2) Append the "%" in the value rather than in the SQL. Also if you want to retrieve records starting with a value the % should be at the end like "SELECT...WHERE column like 'startwith%'"

Here's some sample code:

Dim myCommand As SqlCommand
Dim myParam As SqlParameter

myCommand = New SqlCommand()
myCommand.Connection = objcon
myCommand.CommandText = "SELECT distinct cm.cmmst_id, cm.cm_compno, cm.cm_cname1 + ' ' + cm.cm_cname2 AS cm_cname1, cm_tele, cm_fax, cm_s16 FROM cmmst cm WHERE cm_cname1 + ' ' + cm_cname2 LIKE @.companyNameBegins AND (cm_mbtyp='M' OR cm_mbtyp='SUBDIV') ORDER BY cm_s16 DESC, cm_cname1 ASC"

myCommand.Parameters.Add(New SqlParameter("@.companyNameBegins ",SqlDbType.varchar,100))
myCommand.Parameters("@.companyNameBegins").Value = companyNameBegins & "%"

Try
If objCon.State = 0 Then objCon.Open()
'ExecuteReader and fill some dataContainer.

Catch exc As Exception
Response.Write(exc)
Finally
If objCon.State = ConnectionState.Open Then
objCon.Close()
End If
End Try

|||

Thanks for the assistance, much smoother this way.

zoop

Wednesday, March 7, 2012

need ideas on how to approach this issue

----
--
All,
Need ideas on how to approach this I'm writing a c# program:
Have to compare account numbers in one table to account numbers in
another table and if they exist in the second table
The problem is the tables are in two separate databases (two different
physical places). One table in the ERP system and the other is in the
financial system.
table1 ERP system
table2 Financial system
1. Should I dump table 1 into dataset table, do the same with table
two. This way they are both in the same dataset then figure out how to
compare 1 to 2?
2. Do I dump table 1 into an array and iterate through the array
making sql calls (using a data reader) to see if the account numbers
exist in second table?
3. Put both tables in the arrays and hack away?
What do you consider a good approach or best practice?
Thanks in advance
RCThe fast way is to somehow get all the numbers in one location (on one
server). You can then execute a SQL statement that performs a JOIN or uses
WHERE EXISTS to determine which numbers match.
You could use DTS to get the data out. Or you could read them to a file
(from the one server) and then build insert statements to load the data into
a temp table (denoted by a # sign) on the other server -- against which you
would run the appropriate query.
Keith
"RC" <rick_castrejon@.email.com> wrote in message
news:1120869189.371998.244770@.g14g2000cwa.googlegroups.com...
> ----
--
> All,
> Need ideas on how to approach this I'm writing a c# program:
> Have to compare account numbers in one table to account numbers in
> another table and if they exist in the second table
> The problem is the tables are in two separate databases (two different
> physical places). One table in the ERP system and the other is in the
> financial system.
> table1 ERP system
> table2 Financial system
> 1. Should I dump table 1 into dataset table, do the same with table
> two. This way they are both in the same dataset then figure out how to
> compare 1 to 2?
> 2. Do I dump table 1 into an array and iterate through the array
> making sql calls (using a data reader) to see if the account numbers
> exist in second table?
> 3. Put both tables in the arrays and hack away?
> What do you consider a good approach or best practice?
> Thanks in advance
> RC
>

need ideas on how to approach this issue

All,
Need ideas on how to approach this I'm writing a c# program:
Have to compare account numbers in one table to account numbers in
another table and if they exist in the second table
The problem is the tables are in two separate databases (two different
physical places). One table in the ERP system and the other is in the
financial system.
table1 ERP system
table2 Financial system
1. Should I dump table 1 into dataset table, do the same with table
two. This way they are both in the same dataset then figure out how to
compare 1 to 2?
2. Do I dump table 1 into an array and iterate through the array
making sql calls (using a data reader) to see if the account numbers
exist in second table?
3. Put both tables in the arrays and hack away?
What do you consider a good approach or best practice?
Thanks in advance
RC
The fast way is to somehow get all the numbers in one location (on one
server). You can then execute a SQL statement that performs a JOIN or uses
WHERE EXISTS to determine which numbers match.
You could use DTS to get the data out. Or you could read them to a file
(from the one server) and then build insert statements to load the data into
a temp table (denoted by a # sign) on the other server -- against which you
would run the appropriate query.
Keith
"RC" <rick_castrejon@.email.com> wrote in message
news:1120869189.371998.244770@.g14g2000cwa.googlegr oups.com...
> ----
> All,
> Need ideas on how to approach this I'm writing a c# program:
> Have to compare account numbers in one table to account numbers in
> another table and if they exist in the second table
> The problem is the tables are in two separate databases (two different
> physical places). One table in the ERP system and the other is in the
> financial system.
> table1 ERP system
> table2 Financial system
> 1. Should I dump table 1 into dataset table, do the same with table
> two. This way they are both in the same dataset then figure out how to
> compare 1 to 2?
> 2. Do I dump table 1 into an array and iterate through the array
> making sql calls (using a data reader) to see if the account numbers
> exist in second table?
> 3. Put both tables in the arrays and hack away?
> What do you consider a good approach or best practice?
> Thanks in advance
> RC
>

need ideas on how to approach this issue

----
All,
Need ideas on how to approach this I'm writing a c# program:
Have to compare account numbers in one table to account numbers in
another table and if they exist in the second table
The problem is the tables are in two separate databases (two different
physical places). One table in the ERP system and the other is in the
financial system.
table1 ERP system
table2 Financial system
1. Should I dump table 1 into dataset table, do the same with table
two. This way they are both in the same dataset then figure out how to
compare 1 to 2?
2. Do I dump table 1 into an array and iterate through the array
making sql calls (using a data reader) to see if the account numbers
exist in second table?
3. Put both tables in the arrays and hack away?
What do you consider a good approach or best practice?
Thanks in advance
RCThe fast way is to somehow get all the numbers in one location (on one
server). You can then execute a SQL statement that performs a JOIN or uses
WHERE EXISTS to determine which numbers match.
You could use DTS to get the data out. Or you could read them to a file
(from the one server) and then build insert statements to load the data into
a temp table (denoted by a # sign) on the other server -- against which you
would run the appropriate query.
--
Keith
"RC" <rick_castrejon@.email.com> wrote in message
news:1120869189.371998.244770@.g14g2000cwa.googlegroups.com...
> ----
> All,
> Need ideas on how to approach this I'm writing a c# program:
> Have to compare account numbers in one table to account numbers in
> another table and if they exist in the second table
> The problem is the tables are in two separate databases (two different
> physical places). One table in the ERP system and the other is in the
> financial system.
> table1 ERP system
> table2 Financial system
> 1. Should I dump table 1 into dataset table, do the same with table
> two. This way they are both in the same dataset then figure out how to
> compare 1 to 2?
> 2. Do I dump table 1 into an array and iterate through the array
> making sql calls (using a data reader) to see if the account numbers
> exist in second table?
> 3. Put both tables in the arrays and hack away?
> What do you consider a good approach or best practice?
> Thanks in advance
> RC
>

need help-how to call a function by date in SQL server

I am writing a project in .NET.
I want to check every minute two fields in the data base:
time and start date
time end end date
if in the check the date and time arrives I want to call a function automaticly.
what is the best way to do it in windows service?
maybe directly from the database?
I would like to get sugestions to do it
thanksWell, you can fire a trigger in the db when a new record is added to the table. In that trigger you could shell out to run a .NET app that fires an event that the Windows service is watching for. Or you could poll the db from the Windows service every few seconds to see if there is new data.

Any of these work for you?

Don|||Well, you could also just add a job to the database that starts a stored procedure every x minutes.

In this particular case, the sp_add_job system procedure is agood place to start.

Monday, February 20, 2012

Need help writing stored procedure involving dates

I am trying to write a stored procedure which would execute following logic:

- The stored procedure takes 2 optional parameters @.StartDate and @.EndDate

@.StartDate Datetime = null
@.EndDate Datetime = null

- Since the parameters are optional user can enter either one or can leave both blank.
- If user doesnot enter any values for SD (start date) and ED (end date), stored procedure should run select query replacing those values with wildcard character '%' or NULL
- If user enters SD, query should use @.StartDate as the SD and GetDate() as the ED
- If user enters ED, query should use @.EndDate as the ED and MIN() of the Date field as SD

I was able to write query which did almost everything as is stated above expect for incorporating NULLs
The query is as below

CREATE PROCEDURE SearchDocumentTable

@.FName varchar(100) = null,
@.LName varchar(25) = null,
@.ID varchar(9) = null,
@.StartDate Datetime = null,
@.EndDate Datetime = null


AS
IF ( @.StartDate IS NULL)
Select @.StartDate = MIN(DateInputted) from Document

Select
FName as 'First Name',
LName as 'Last Name',
ID as 'Student ID',
Orphan as 'Orphan',
DocumentType as 'Document Type',
DocDesc as 'Description of the Document',
DateInputted as 'Date Entered',
InputtedBy as 'Entered by'

From Document,DocumentTypeCodes
Where FName LIKE ISNULL(@.FName,'%')
AND LName LIKE ISNULL(@.LName,'%' + NULL)
AND ID LIKE ISNULL(@.ID,'%' + NULL)
AND (DateInputted BETWEEN @.StartDate AND ISNULL(@.EndDate,GETDATE()) OR DateInputted IS NULL)
AND Document.DocTypeCode = DocumentTypeCodes.DocTypeCode

GO

Any help would be appreciated
Thanks in advance :)I'm a little confused. What is your question ?

did you mean except for incoporating NULLS ?

Cheers,
-Kilka|||I am sorry wasnt thinking right when I posted that to the forum in the morning. Let me try to explain my problem with an example.
To make it simple lets say I have a simple table with 3 columns: FName, LName and Date

FName LName Date
Aab 02/05/2005
Abc Bb 02/06/2005
Aaaa Bbb
02/07/2005
Baaaa Bbb
Baaca 02/07/2005
Caa Bbbb 02/07/2005

As can be seen that FName, LName and Date columns accept NULL values.
Now I want to write a stored procedure which takes 4 parameters ( all of them are optional) @.FName, @.LName, @.StartDate and @.EndDate and do a search on this table.
I am having trouble handling these NULL fields.

When I execute the stored procedure, I should get results as follows:
- If user enters @.FName LIKE 'A%', sp should return only the rows where first name matches that format ( no null first name or null last names or null dates should be returned). Result should be first 3 rows with first names: Aab, Abc, Aaaa
- Similarly when searching for start date and end date, procedure should return only the rows which match the date criteria ignoring null first name and last name fields

I hope this example would prove helpful, since everytime I try to write a query I always end up getting rows with null fields.
Thanks again for your time :)|||Do you really have '%' + NULL in the code? I would think you just want '%'.

Are you getting any data back from this query when you have data that looks like your example?|||You guys are good sorry forgot to update the stored procedure.
No, '%' + NULL doesnot return any records. So I changed the stored procedure and use only '%' for all null parameters and adds OR FIELDNAME IS NULL at the end:

CREATE PROCEDURE SearchDocumentTable

@.FName varchar(100) = null,
@.LName varchar(25) = null,
@.ID varchar(9) = null,
@.StartDate Datetime = null,
@.EndDate Datetime = null

AS

IF ( @.StartDate IS NULL)
Select @.StartDate = MIN(DateInputted) from Document

Select
FName as 'First Name',
LName as 'Last Name',
ID as 'Student ID',
Orphan as 'Orphan',
DocumentType as 'Document Type',
DocDesc as 'Description of the Document',
DateInputted as 'Date Entered',
InputtedBy as 'Entered by'

From Document,DocumentTypeCodes
Where FName LIKE ISNULL(@.FName,'%')
AND (LName LIKE ISNULL(@.LName,'%') OR LName IS NULL)
AND (ID LIKE ISNULL(@.ID,'%') OR ID IS NULL)
AND (DateInputted BETWEEN @.StartDate AND ISNULL(@.EndDate,GETDATE()) OR DateInputted IS NULL)
AND Document.DocTypeCode = DocumentTypeCodes.DocTypeCode

GO

This is the stored procedure and as can be seen it will return null fields when I pass last name, ID or date as the parameter.
Any ideas how can I modify the stored procedure to avoid returning null fields.

Thank you again guys, I really appreciate your help|||Do you get the correct results if you take out OR LName IS NULL and
OR ID IS NULL and OR DateInputted IS NULL?

If this is not the case then please type out using the example data you used above the exact results you would like to see if all the input fields are NULL.|||First, decide on precedence. What if the user passes all three parameters?

Assuming the precedence is LastName, FirstName, Date:Declare @.t Table(Table_Pk int identity(1,1), FirstName varchar(3) Null, LastName varchar(3) Null, EndDate datetime Null)

Insert @.t (FirstName, LastName, EndDate)
Select 'Kim', 'Cat', GetDate()
Union
Select 'Pat', 'Dog', Null
Union
Select 'Ted', Null, GetDate()
Union
Select 'Jim', Null, Null
Union
Select Null, 'Fox', GetDate()
Union
Select Null, 'Fox', Null
Union
Select Null, Null, GetDate()
Union
Select Null, Null, Null

Select * From @.t

Declare @.FirstName varchar(3)
, @.LastName varchar(3)
, @.EndDate datetime

Select @.LastName = 'F'

Select *
From @.t
Where (@.LastName Is Not Null And LastName Like @.LastName + '%')
Or
(@.LastName Is Null And @.FirstName Is Not Null And FirstName Like @.FirstName + '%')
Or
(@.LastName Is Null And @.FirstName Is Null And EndDate > = Coalesce(@.EndDate, '01/01/1950') )|||FYI, if you test for the IF statements and, inside the stored procedure, call a different function for each test to return the final result set, you will have no recompiles. This will make the overall execution of the stored proc much faster when you get larger recordsets. You also might want to consider having the developers use a checkbox for exact match. That sounds stupid, but the users will learn to love it if this table gets extremely large.

Need help writing search query

I am not very familiar with the syntax of MS SQL and I am trying to write a stored procedure which would do a search and return matching records.
This is what I need to achieve:
for instance I create a form with 4 text fields
- First Name
- Last Name
- Employee ID
- Date

I am interested in writing a stored procedure that would run a select query based on the input in the text fields
e.g.
- if the user enters First Name and the Last Name (leaving Employee ID and Date fields blank) query should be something like
select * from Employee where FirstName like @.FirstName and LastName like @.LastName
- or if the user enters only the Employee ID stored procedure should run a query similar to
select * from Employee where EmployeeID like @.EmployeeIDselect *
from Employee
where (FirstName like @.FirstName and LastName like @.LastName)
or
(EmployeeID like @.EmployeeID)|||Thanks for the your time blindman .. that was absolutely brilliant, shows you know your SQL :cool:
This query would sure work for the example I posted, but I was just wondering if I can give user more flexibility and allow him to enter lets say [partial first name (some string with wildcard characters) and partial ID] or [partial first name, last name and ID] or some such wierd combination. The query should adapt to the input and return result accordingly.
What is the best way to go about doing this, again thanks for any help I can get.
Thank you.
Have a great day.|||Yes.

You will need to add more complexity to your WHERE clause to accomplish the logic you want.

You will also need to use the LIKE operator if you want to allow wildcards.

You will also need to expect this query not to run very fast, if you include lots of logical operators and LIKE comparisons in your criteria...|||Since this is in a stored procedure you might use dynamic SQL to create the query on the fly and then execute it.

eg.

create x @.empid int, ...

declare @.sql varchar(200)

set @.sql = 'select * from Employee where '

if empid is not null set @.sql = @.sql & 'EmployeeID =' & @.empid

... etc etc

exec (@.sql)

...|||Thanks ejustuss and blindman, you guys were a tremendous help.
Since I am not very comfortable writing stored procedures this was my solution to the problem .. nothing ingenious but hey as long it works thats all I care about :D.
So I wrote this insanely strict stored procedure which would except user to input all the parameters (first name, last name, Employee ID, Date ... everything) and wrote a query something similar to this:
select * from Employee where FirstName like @.FirstName and LastName like @.LastName and EmployeeID like @.EmployeeID and ....
Since my stored procedure is not giving any flexibility to the user, I added flexibility on the client side in the web form code by replacing all fields left blank by the user with wildcard '%'. So if a user wanted to search by employee's first name, he would just enter the first name leaving other field blanks. These blank fields will be replaced with % and passed to the stored procedure.|||Not sure how effecient this is :

SELECT * FROM Employee
WHERE EmployeeID LIKE ISNULL('%' + @.EmployeeID + '%', EmployeeID)
AND FirstName LIKE ISNULL('%' + @.FirstName + '%', FirstName)
AND LAstName LIKE ISNULL('%' + @.LastName + '%', LastName)
AND DATEDIFF(Day, ISNULL(@.Date, Date), Date) = 0;|||Hey afx thanks for posting your version of the solution. I am sorry but I really did not understand the code you posted. Though your input was definetely useful since using ISNULL is by far a way better more efficient option :cool:
This is how I would use ISNULL

SELECT * FROM Employee
WHERE EmployeeID LIKE ISNULL( @.EmployeeID, '%')
AND FirstName LIKE ISNULL( @.FirstName, '%')
AND LAstName LIKE ISNULL( @.LastName, '%')

Thank you again for the input and effort :) :)|||Hi all,

I need help on building query statement. below is my table called inventory.

idx fabidx coloridx qty isReserved
1 1 1 15 Y
2 1 2 20
3 1 1 10
4 1 1 25 Y
5 1 2 23 Y
6 1 3 26
This is the output that i'm expecting.
fabidx coloridx qty isReserved
1 1 50 2
1 2 43 1
1 3 26 0
I need to get all distinct fabidx and coloridx, i need to get the sum of the distinct fabidx and coloridx, and i need to get the count of "Y" in the isReserved column of the distinct fabidx and coloridx.

Please help. Thanks.|||A simple aggregation query. Look up aggregation function in Books Online, and then post this as a new thread if you still need help.

Need help writing query/ stored proc

I need to write query or stored proc that is going to be used to gen. a
report
This is a structure of my table
Id Date ItemType OrdersPlaced
1 08/21 1 100
1 08/21 2 500
1 08/21 3 200
1 08/21 4 150
2 ... ... ...
2 ... ... ...
3 ... ... ...
4 ... ... ...
4 ... ... ...
The report is going to take Id and Date as inputs and report generated
is in following format
Id: 1
Date: 08/21
ItemType 1 ItemType 2 ItemType 3 ItemType 4
100 500 200 150
This can definetely be done creating a temp table and writing to this
temp table thru multiple selects for each itemtype.
Is there any better way'
ThanksHave a look at the PIVOT function in SQL 2005 Books online.
Or this example on SQL 2000 will get you on the way
http://www.dandyman.net/sql/samples/pivottable.txt
__________________________________________________
Dandy Weyn - Dandyman (r)
MCSE-MCSA-MCDBA-MCDST-MCT Community Leader
MCTS SQL 2005- MCITP Database Administrator
Author of Sybex Exam Study Guide MCTS SQL 2005
http://www.dandyman.net
"absoft" <arpit.00@.gmail.com> wrote in message
news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...
>I need to write query or stored proc that is going to be used to gen. a
> report
> This is a structure of my table
> Id Date ItemType OrdersPlaced
> 1 08/21 1 100
> 1 08/21 2 500
> 1 08/21 3 200
> 1 08/21 4 150
> 2 ... ... ...
> 2 ... ... ...
> 3 ... ... ...
> 4 ... ... ...
> 4 ... ... ...
> The report is going to take Id and Date as inputs and report generated
> is in following format
> Id: 1
> Date: 08/21
> ItemType 1 ItemType 2 ItemType 3 ItemType 4
> 100 500 200 150
> This can definetely be done creating a temp table and writing to this
> temp table thru multiple selects for each itemtype.
> Is there any better way'
> Thanks
>|||You can generate a summarized query using SUM(OrdersPlaced) and GROUP BY
[Id], [Date]. The sideways generation you're looking for is a pivot table
type query, which can be done with a "monster" CASE statement in SQL 2000 or
the PIVOT operator in SQL 2005. Either method would require you to know,
and hard-code, your column "headings" (Item Type 1, Item Type 2, etc.) in
advance. If you don't know them in advance you can use dynamic SQL to work
it out.
Personally I'd recommend doing the SUM()/GROUP BY and transferring the
results to a front-end app and format it there.
"absoft" <arpit.00@.gmail.com> wrote in message
news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...
>I need to write query or stored proc that is going to be used to gen. a
> report
> This is a structure of my table
> Id Date ItemType OrdersPlaced
> 1 08/21 1 100
> 1 08/21 2 500
> 1 08/21 3 200
> 1 08/21 4 150
> 2 ... ... ...
> 2 ... ... ...
> 3 ... ... ...
> 4 ... ... ...
> 4 ... ... ...
> The report is going to take Id and Date as inputs and report generated
> is in following format
> Id: 1
> Date: 08/21
> ItemType 1 ItemType 2 ItemType 3 ItemType 4
> 100 500 200 150
> This can definetely be done creating a temp table and writing to this
> temp table thru multiple selects for each itemtype.
> Is there any better way'
> Thanks
>|||Thanks y'all I am using SQL 2000 so pivot operator is not an option
open for me. I like the idea of using the "monster" CASE statement ...
and it almost returns the kind of report that I need ... just one snag
apart from the above fields there is one more calculated field that
references another table
e.g.
Table B
Id ItemType EstimatedTotal
1 1 200
1 2 800
1 3 200
1 4 200
The new field is a sum of EstimatedTotal for all ItemType and is used
for comparison to the actual total. The new report looks something like
this:
> > Id: 1
> > Date: 08/21
> > ItemType 1 ItemType 2 ItemType 3 ItemType 4 ActualTotal EstimatedTotal
> > 100 500 200 150 950 1400
going forward with the logic of using CASE and GROUP BY, can I get this
EstimatedTotal of 1400 returned by same query without using cursors or
temp tables
Any thoughts!!
Mike C# wrote:
> You can generate a summarized query using SUM(OrdersPlaced) and GROUP BY
> [Id], [Date]. The sideways generation you're looking for is a pivot table
> type query, which can be done with a "monster" CASE statement in SQL 2000 or
> the PIVOT operator in SQL 2005. Either method would require you to know,
> and hard-code, your column "headings" (Item Type 1, Item Type 2, etc.) in
> advance. If you don't know them in advance you can use dynamic SQL to work
> it out.
> Personally I'd recommend doing the SUM()/GROUP BY and transferring the
> results to a front-end app and format it there.
> "absoft" <arpit.00@.gmail.com> wrote in message
> news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...
> >I need to write query or stored proc that is going to be used to gen. a
> > report
> > This is a structure of my table
> >
> > Id Date ItemType OrdersPlaced
> > 1 08/21 1 100
> > 1 08/21 2 500
> > 1 08/21 3 200
> > 1 08/21 4 150
> > 2 ... ... ...
> > 2 ... ... ...
> > 3 ... ... ...
> > 4 ... ... ...
> > 4 ... ... ...
> >
> > The report is going to take Id and Date as inputs and report generated
> > is in following format
> >
> > Id: 1
> > Date: 08/21
> > ItemType 1 ItemType 2 ItemType 3 ItemType 4
> > 100 500 200 150
> >
> > This can definetely be done creating a temp table and writing to this
> > temp table thru multiple selects for each itemtype.
> > Is there any better way'
> >
> > Thanks
> >

Need help writing query/ stored proc

I need to write query or stored proc that is going to be used to gen. a
report
This is a structure of my table
Id Date ItemType OrdersPlaced
1 08/21 1 100
1 08/21 2 500
1 08/21 3 200
1 08/21 4 150
2 ... ... ...
2 ... ... ...
3 ... ... ...
4 ... ... ...
4 ... ... ...
The report is going to take Id and Date as inputs and report generated
is in following format
Id: 1
Date: 08/21
ItemType 1 ItemType 2 ItemType 3 ItemType 4
100 500 200 150
This can definetely be done creating a temp table and writing to this
temp table thru multiple selects for each itemtype.
Is there any better way'
ThanksHave a look at the PIVOT function in SQL 2005 Books online.
Or this example on SQL 2000 will get you on the way
http://www.dandyman.net/sql/samples/pivottable.txt
________________________________________
__________
Dandy Weyn - Dandyman (r)
MCSE-MCSA-MCDBA-MCDST-MCT Community Leader
MCTS SQL 2005- MCITP Database Administrator
Author of Sybex Exam Study Guide MCTS SQL 2005
http://www.dandyman.net
"absoft" <arpit.00@.gmail.com> wrote in message
news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...
>I need to write query or stored proc that is going to be used to gen. a
> report
> This is a structure of my table
> Id Date ItemType OrdersPlaced
> 1 08/21 1 100
> 1 08/21 2 500
> 1 08/21 3 200
> 1 08/21 4 150
> 2 ... ... ...
> 2 ... ... ...
> 3 ... ... ...
> 4 ... ... ...
> 4 ... ... ...
> The report is going to take Id and Date as inputs and report generated
> is in following format
> Id: 1
> Date: 08/21
> ItemType 1 ItemType 2 ItemType 3 ItemType 4
> 100 500 200 150
> This can definetely be done creating a temp table and writing to this
> temp table thru multiple selects for each itemtype.
> Is there any better way'
> Thanks
>|||You can generate a summarized query using SUM(OrdersPlaced) and GROUP BY
[Id], [Date]. The sideways generation you're looking for is a pivot
table
type query, which can be done with a "monster" CASE statement in SQL 2000 or
the PIVOT operator in SQL 2005. Either method would require you to know,
and hard-code, your column "headings" (Item Type 1, Item Type 2, etc.) in
advance. If you don't know them in advance you can use dynamic SQL to work
it out.
Personally I'd recommend doing the SUM()/GROUP BY and transferring the
results to a front-end app and format it there.
"absoft" <arpit.00@.gmail.com> wrote in message
news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...
>I need to write query or stored proc that is going to be used to gen. a
> report
> This is a structure of my table
> Id Date ItemType OrdersPlaced
> 1 08/21 1 100
> 1 08/21 2 500
> 1 08/21 3 200
> 1 08/21 4 150
> 2 ... ... ...
> 2 ... ... ...
> 3 ... ... ...
> 4 ... ... ...
> 4 ... ... ...
> The report is going to take Id and Date as inputs and report generated
> is in following format
> Id: 1
> Date: 08/21
> ItemType 1 ItemType 2 ItemType 3 ItemType 4
> 100 500 200 150
> This can definetely be done creating a temp table and writing to this
> temp table thru multiple selects for each itemtype.
> Is there any better way'
> Thanks
>|||Thanks y'all I am using SQL 2000 so pivot operator is not an option
open for me. I like the idea of using the "monster" CASE statement ...
and it almost returns the kind of report that I need ... just one snag
apart from the above fields there is one more calculated field that
references another table
e.g.
Table B
Id ItemType EstimatedTotal
1 1 200
1 2 800
1 3 200
1 4 200
The new field is a sum of EstimatedTotal for all ItemType and is used
for comparison to the actual total. The new report looks something like
this:
[vbcol=seagreen]
going forward with the logic of using CASE and GROUP BY, can I get this
EstimatedTotal of 1400 returned by same query without using cursors or
temp tables
Any thoughts!!
Mike C# wrote:[vbcol=seagreen]
> You can generate a summarized query using SUM(OrdersPlaced) and GROUP BY
> [Id], [Date]. The sideways generation you're looking for is a piv
ot table
> type query, which can be done with a "monster" CASE statement in SQL 2000
or
> the PIVOT operator in SQL 2005. Either method would require you to know,
> and hard-code, your column "headings" (Item Type 1, Item Type 2, etc.) in
> advance. If you don't know them in advance you can use dynamic SQL to wor
k
> it out.
> Personally I'd recommend doing the SUM()/GROUP BY and transferring the
> results to a front-end app and format it there.
> "absoft" <arpit.00@.gmail.com> wrote in message
> news:1156180618.673896.29220@.p79g2000cwp.googlegroups.com...

Need help writing query

I have a table with items bought by the sec. I would like to group them by 5
min intervals round the clock for a day and compare them with the same value
for other days of the w around the same time to get a percentage trend.
So input in a table A for eg: would be
TableA
Date1 Count1
2/1/2006 00:01 1
2/1/2006 00:03 1
2/1/2006 00:05 1
2/1/2006 00:07 1
2/1/2006 00:09 1
2/1/2006 00:11 1
2/1/2006 00:16 1
2/1/2006 01:03 1
2/1/2006 01:05 1
2/1/2006 01:13 1
2/2/2006 00:01 1
2/2/2006 00:03 1
2/2/2006 00:05 1
2/2/2006 00:07 1
2/2/2006 00:08 1
2/2/2006 00:09 1
2/2/2006 00:11 1
2/2/2006 00:16 1
2/2/2006 01:03 1
2/2/2006 01:05 1
2/2/2006 01:13 1
Create table tableA
(Date1 datetime,
count1 int)
insert tableA values('2/1/2006 00:01 ' , 1)
insert tableA values('2/1/2006 00:03' , 1)
insert tableA values('2/1/2006 00:05' , 1)
insert tableA values('2/1/2006 00:07' , 1)
insert tableA values('2/1/2006 00:09' , 1)
insert tableA values('2/1/2006 00:11' , 1)
insert tableA values('2/1/2006 00:16' , 1)
insert tableA values('2/1/2006 01:03' , 1)
insert tableA values('2/1/2006 01:05' , 1)
insert tableA values('2/1/2006 01:13' , 1)
insert tableA values('2/2/2006 00:01' , 1)
insert tableA values('2/2/2006 00:03' , 1)
insert tableA values('2/2/2006 00:05' , 1)
insert tableA values('2/2/2006 00:07' , 1)
insert tableA values('2/2/2006 00:08' , 1)
insert tableA values('2/2/2006 00:09' , 1)
insert tableA values('2/2/2006 00:11' , 1)
insert tableA values('2/2/2006 00:16' , 1)
insert tableA values('2/2/2006 01:03' , 1)
insert tableA values('2/2/2006 01:05' , 1)
insert tableA values('2/2/2006 01:13' , 1)
Output required
Hr IntervalPeriod 2/1/2006(TotalCount) 2/2/2006(TotalCount)
00 0 0 0
00 5 2 2
00 10 3 4
00 15 1 1
00 20 1 1
00 25 0 0
00 30 0 0
00 35 0 0
00 40 0 0
00 45 0 0
00 50 0 0
00 55 0 0
01 00 0 0
01 5 2 2
01 10 3 3
01 15 1 1
01 20 1 1
01 25 0 0
01 30 0 0
01 35 0 0
01 40 0 0
01 45 0 0
01 50 0 0
01 55 0 0
........
As you can see, I would like to group within 5 minute intervals of the hour.
I would then like to pivot the dates so I can trend day over day. Ideally Id
like to group daily for 7 days .. that way its not dynamic
Can someone assist ?Hassan
Take a look at Erland's example. Perhaps it is not exactly what you wanted
but it certainly give you an idea
CREATE TABLE sessions (start datetime NOT NULL,
stop datetime NULL)
go
SET DATEFORMAT dmy
go
SELECT TOP 80000 n = identity(int, 1, 1)
INTO numbers
FROM Northwind..Orders a
CROSS JOIN Northwind..Orders b
go
INSERT sessions (start, stop)
SELECT '22/11/2004 14:02', '22/11/2004 17:30' UNION
SELECT '22/11/2004 09:00', '22/11/2004 17:12' UNION
SELECT '22/11/2004 10:25', '22/11/2004 16:30' UNION
SELECT '22/11/2004 11:02', '22/11/2004 12:30' UNION
SELECT '22/11/2004 16:00', '22/11/2004 17:30' UNION
SELECT '22/11/2004 16:00', '22/11/2004 16:05' UNION
SELECT '22/11/2004 16:06', '22/11/2004 16:10'
go
CREATE PROCEDURE get_peaks @.start datetime,
@.stop datetime,
@.len smallint AS
SELECT intstart, intstop = dateadd(mi, @.len, intstart), MAX(cnt)
FROM (SELECT intstart = dateadd(mi, @.len *
(datediff(mi, @.start, a.minute) / @.len), @.start),
a.cnt
FROM (SELECT mi.minute, cnt = COUNT(s.start)
FROM (SELECT minute = dateadd(mi, n, @.start)
FROM numbers
WHERE n <= datediff(mi, @.start, @.stop)) AS mi
LEFT JOIN sessions s
ON mi.minute BETWEEN s.start AND s.stop
GROUP BY mi.minute) AS a
) AS b
GROUP BY intstart
ORDER BY intstart
go
EXEC get_peaks '20041122 08:00', '20041122 18:00', 5
go
DROP TABLE numbers
DROP TABLE sessions
DROP PROCEDURE get_peaks
"Hassan" <Hassan@.hotmail.com> wrote in message
news:eSVEB7wOGHA.2124@.TK2MSFTNGP14.phx.gbl...
>I have a table with items bought by the sec. I would like to group them by
>5 min intervals round the clock for a day and compare them with the same
>value for other days of the w around the same time to get a percentage
>trend.
> So input in a table A for eg: would be
> TableA
> Date1 Count1
> 2/1/2006 00:01 1
> 2/1/2006 00:03 1
> 2/1/2006 00:05 1
> 2/1/2006 00:07 1
> 2/1/2006 00:09 1
> 2/1/2006 00:11 1
> 2/1/2006 00:16 1
> 2/1/2006 01:03 1
> 2/1/2006 01:05 1
> 2/1/2006 01:13 1
> 2/2/2006 00:01 1
> 2/2/2006 00:03 1
> 2/2/2006 00:05 1
> 2/2/2006 00:07 1
> 2/2/2006 00:08 1
> 2/2/2006 00:09 1
> 2/2/2006 00:11 1
> 2/2/2006 00:16 1
> 2/2/2006 01:03 1
> 2/2/2006 01:05 1
> 2/2/2006 01:13 1
>
> Create table tableA
> (Date1 datetime,
> count1 int)
> insert tableA values('2/1/2006 00:01 ' , 1)
> insert tableA values('2/1/2006 00:03' , 1)
> insert tableA values('2/1/2006 00:05' , 1)
> insert tableA values('2/1/2006 00:07' , 1)
> insert tableA values('2/1/2006 00:09' , 1)
> insert tableA values('2/1/2006 00:11' , 1)
> insert tableA values('2/1/2006 00:16' , 1)
> insert tableA values('2/1/2006 01:03' , 1)
> insert tableA values('2/1/2006 01:05' , 1)
> insert tableA values('2/1/2006 01:13' , 1)
> insert tableA values('2/2/2006 00:01' , 1)
> insert tableA values('2/2/2006 00:03' , 1)
> insert tableA values('2/2/2006 00:05' , 1)
> insert tableA values('2/2/2006 00:07' , 1)
> insert tableA values('2/2/2006 00:08' , 1)
> insert tableA values('2/2/2006 00:09' , 1)
> insert tableA values('2/2/2006 00:11' , 1)
> insert tableA values('2/2/2006 00:16' , 1)
> insert tableA values('2/2/2006 01:03' , 1)
> insert tableA values('2/2/2006 01:05' , 1)
> insert tableA values('2/2/2006 01:13' , 1)
> Output required
> Hr IntervalPeriod 2/1/2006(TotalCount) 2/2/2006(TotalCount)
> 00 0 0 0
> 00 5 2 2
> 00 10 3 4
> 00 15 1 1
> 00 20 1 1
> 00 25 0 0
> 00 30 0 0
> 00 35 0 0
> 00 40 0 0
> 00 45 0 0
> 00 50 0 0
> 00 55 0 0
> 01 00 0 0
> 01 5 2 2
> 01 10 3 3
> 01 15 1 1
> 01 20 1 1
> 01 25 0 0
> 01 30 0 0
> 01 35 0 0
> 01 40 0 0
> 01 45 0 0
> 01 50 0 0
> 01 55 0 0
> ........
>
> As you can see, I would like to group within 5 minute intervals of the
> hour. I would then like to pivot the dates so I can trend day over day.
> Ideally Id like to group daily for 7 days .. that way its not dynamic
> Can someone assist ?
>
>|||On Sun, 26 Feb 2006 11:56:36 -0800, Hassan wrote:

>I have a table with items bought by the sec. I would like to group them by
5
>min intervals round the clock for a day and compare them with the same valu
e
>for other days of the w around the same time to get a percentage trend.
(snip)
Hi Hassan,
Thanks for posting CREATE TABLE and INSERT statements and expected
output. This made it very easy to develop the query below, which will
return the expected results, BUT:
1. Rows with only 0 count are excluded. If you really need them, you'll
have to add a numbers table to the query to get the desired result (let
me know if you need assistance with that part as well)
2. Not all output matches your expected output. I think that the errors
are in your post. If not, I must have misunderstood the requirements.
Anyway, here's the query:
DECLARE @.BaseDate datetime
SET @.BaseDate = '20060201'
SELECT FiveMinIntervals / 12 AS Hours,
FiveMinIntervals % 12 * 5 AS Minutes,
SUM(CASE WHEN Days = 0 THEN count1 ELSE 0 END) AS Day1,
SUM(CASE WHEN Days = 1 THEN count1 ELSE 0 END) AS Day2,
-- repeat some more times
SUM(CASE WHEN Days = 6 THEN count1 ELSE 0 END) AS Day7
FROM (SELECT DATEDIFF(day, @.BaseDate, Date1) AS Days,
DATEDIFF(minute, @.BaseDate, Date1) / 5 % 288
AS FiveMinIntervals,
count1
FROM tableA) AS d
GROUP BY FiveMinIntervals
Hugo Kornelis, SQL Server MVP

need help writing batch without cursor

i'm trying to write a batch that will perform a complex task using
set-based selects instead of a row-based cursor. let me know if you can
help me figure out how.
description of what i'm trying to do:
there is TABLE1, TABLE2, and TABLE3
i want to select each row from TABLE1, do some analysis on the data of
that row, and then perform an insert of some data into TABLE2, and some
data into TABLE3
how do i do this in a T-SQL batch?
thanks in advance!What kind of analysis?
AMB
"iaesun@.yahoo.com" wrote:

> i'm trying to write a batch that will perform a complex task using
> set-based selects instead of a row-based cursor. let me know if you can
> help me figure out how.
> description of what i'm trying to do:
> there is TABLE1, TABLE2, and TABLE3
> i want to select each row from TABLE1, do some analysis on the data of
> that row, and then perform an insert of some data into TABLE2, and some
> data into TABLE3
> how do i do this in a T-SQL batch?
> thanks in advance!
>|||i'd be curious how to do it even if there were no analysis, since it's
the row-by-row part that i'm not sure how to do in a set-based
solution.
but! in case it helps, here's the analysis i was thinking of (pardon
the psuedo-code for the row-by-row portion)
for each ROW in TABLE1
{
if not exists (select * from TABLE2 where COLUMNA = ROW.COLUMN1)
begin
insert into TABLE2 (COLUMNA) values (ROW.COLUMN1)
end
set @.table2id = select ID from TABLE2 where COLUMNA = ROW.COLUMN1
insert into TABLE3 values (ROW.COLUMN2, ROW.COLUMN3, @.table2id)
}|||>> i want to select each row from TABLE1, do some analysis on the data
of
that row, and then perform an insert of some data into TABLE2, and some
data into TABLE3 <<
Read what you wrote! What kind of spec is that? How do we debug code
which is not here. Please post DDL, so that people do not have to guess
what the keys, constraints, Declarative Referential Integrity,
datatypes, etc. in your schema are. Sample data is also a good idea,
along with clear specifications.
Frankly, it sounds likeyou are splitting this vague Table1 into two
tables when you should be using a VIEW or a column with whatever the
criteria for this split is. The whole idea of databases was to avoid
redundant data.|||You don't know Joe.
Maybe he's actually normalizing table1.
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1112986095.913817.293370@.g14g2000cwa.googlegroups.com...
> of
> that row, and then perform an insert of some data into TABLE2, and some
> data into TABLE3 <<
> Read what you wrote! What kind of spec is that? How do we debug code
> which is not here. Please post DDL, so that people do not have to guess
> what the keys, constraints, Declarative Referential Integrity,
> datatypes, etc. in your schema are. Sample data is also a good idea,
> along with clear specifications.
> Frankly, it sounds likeyou are splitting this vague Table1 into two
> tables when you should be using a VIEW or a column with whatever the
> criteria for this split is. The whole idea of databases was to avoid
> redundant data.
>|||Try,
insert into t2 (colA)
select col1
from t1
where not exists (select * from t2 where t2.colA = t1.col1)
insert into t3 (colB, colC)
select col2, col3
from t1
where not exists (select * from t2 where t2.colA = t1.col1)
AMB
"iaesun@.yahoo.com" wrote:

> i'd be curious how to do it even if there were no analysis, since it's
> the row-by-row part that i'm not sure how to do in a set-based
> solution.
> but! in case it helps, here's the analysis i was thinking of (pardon
> the psuedo-code for the row-by-row portion)
> for each ROW in TABLE1
> {
> if not exists (select * from TABLE2 where COLUMNA = ROW.COLUMN1)
> begin
> insert into TABLE2 (COLUMNA) values (ROW.COLUMN1)
> end
> set @.table2id = select ID from TABLE2 where COLUMNA = ROW.COLUMN1
> insert into TABLE3 values (ROW.COLUMN2, ROW.COLUMN3, @.table2id)
> }
>|||Correction,
Swith the order of the statements.
insert into t3 (colB, colC)
select col2, col3
from t1
where not exists (select * from t2 where t2.colA = t1.col1)
insert into t2 (colA)
select col1
from t1
where not exists (select * from t2 where t2.colA = t1.col1)
AMB
"Alejandro Mesa" wrote:
> Try,
> insert into t2 (colA)
> select col1
> from t1
> where not exists (select * from t2 where t2.colA = t1.col1)
> insert into t3 (colB, colC)
> select col2, col3
> from t1
> where not exists (select * from t2 where t2.colA = t1.col1)
>
> AMB
> "iaesun@.yahoo.com" wrote:
>|||well, i'm trying to keep the topic abstract, because i was hoping for a
more general description of how to do row-by-row processing in a
set-based solution. but, if such details are needed in this case, then
let me try to invent some. regarding the latter portion of your
message: this is, in a manner of speaking, splitting table1 into two
tables. however, it is more of a complex tranformation, not redundant
information. table1 is a staging table, and will be dropped after this
process is complete.
first, the three table definitions:
CREATE TABLE [sourcetable] (
[ID] [int] NOT NULL,
[column1] [int] NULL,
[column2] [int] NULL,
) ON [primary]
GO
CREATE TABLE [destinationtable1] (
[ID] [int] NOT NULL,
[columnA] [int] NULL,
[columnB] [int] NULL,
) ON [primary]
GO
CREATE TABLE [destinationtable2] (
[ID] [int] NOT NULL,
[columnY] [int] NULL,
[columnZ] [int] NULL,
) ON [primary]
GO
what i would like to do, read [sourcetable] row-by-row. for each row, i
would like to perform the following batch:
IF NOT EXISTS (SELECT * FROM destinationtable1 WHERE
destinationtable1.columnA = sourcetable.column1)
begin
INSERT INTO destinationtable1 (columnA) VALUES
(sourcetable.column1)
end
SELECT @.idvariable = ID FROM destinationtable1 WHERE
destinationtable1.columnA = sourcetable.column1
INSERT INTO destinationtable2 (columnY, columnZ) VALUES
(sourcetable.column2, @.table2id)
is that any clearer?|||yes, that is precisely the nature of this task. table1 is an imported
table from an outside system. i'm just splicing it into its logical,
normalized form.|||> what i would like to do, read [sourcetable] row-by-row. for each row,
i
would like to perform the following batch
Wrong. The idea is precisely to AVOID processing anything row-by-row.
Try this:
INSERT INTO destinationtable1 (columna)
SELECT DISTINCT column1
FROM sourcetable
WHERE NOT EXISTS
(SELECT *
FROM destinationtable1
WHERE columna = sourcetable.column1)
INSERT INTO destinationtable2 (columny, columnz)
SELECT S.column2, D.id
FROM sourcetable AS S
JOIN destinationtable1 AS D
ON S.column1 = D.columna
David Portas
SQL Server MVP
--

Need help writing a trigger

Please find the necessary SQL scripts to generate a small version of my database and some data at the bottom of this post.

Here's a short description of what the database is all about: It's a project tracking and management system. Contracts go into the tblDeals table. Because each project may be different in nature, project phases are defined in tblPhaseType and tblPhase tables. The table used to keep track of what's going on is the tblProduction table.

Here's what I need to do. When a project is completed -- meaning it has gone through all the phases that it needs to go through -- I want a trigger to fire up and change the contract status in the tblDeals table to "Completed" whose value is 1. When a new contract gets entered into the table, the Contract Status is set to 5 by default which means "In Progress" -- as defined in tblContractStatus. The tricky part is that because, each project is different and has different number of phases, the trigger has to make sure that all the phases have been submitted into the tblProduction table for that particular deal.

I'd really appreciate some help here. Thanks in advance for all your help.

------------
Here's the script
------------


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblCompany]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblCompany
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblContractStatus]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblContractStatus
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblDeals_tblPhaseType]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblDeals] DROP CONSTRAINT FK_tblDeals_tblPhaseType
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblPhase_tblPhaseType]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblPhase] DROP CONSTRAINT FK_tblPhase_tblPhaseType
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblProduction_tblDeals]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblProduction] DROP CONSTRAINT FK_tblProduction_tblDeals
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_tblProduction_tblPhase]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[tblProduction] DROP CONSTRAINT FK_tblProduction_tblPhase
GO

/****** Object: Table [dbo].[tblProduction] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblProduction]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblProduction]
GO

/****** Object: Table [dbo].[tblDeals] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblDeals]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblDeals]
GO

/****** Object: Table [dbo].[tblPhase] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblPhase]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblPhase]
GO

/****** Object: Table [dbo].[tblCompany] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblCompany]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblCompany]
GO

/****** Object: Table [dbo].[tblContractStatus] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblContractStatus]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblContractStatus]
GO

/****** Object: Table [dbo].[tblPhaseType] Script Date: 11/20/2003 11:30:48 AM ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblPhaseType]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblPhaseType]
GO

/****** Object: Table [dbo].[tblCompany] Script Date: 11/20/2003 11:30:50 AM ******/
CREATE TABLE [dbo].[tblCompany] (
[CompanyID] [int] IDENTITY (1, 1) NOT NULL ,
[CompanyName] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[tblContractStatus] Script Date: 11/20/2003 11:30:50 AM ******/
CREATE TABLE [dbo].[tblContractStatus] (
[StatusID] [tinyint] IDENTITY (1, 1) NOT NULL ,
[Status] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[tblPhaseType] Script Date: 11/20/2003 11:30:51 AM ******/
CREATE TABLE [dbo].[tblPhaseType] (
[PhaseTypeID] [tinyint] IDENTITY (1, 1) NOT NULL ,
[Desription] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[tblDeals] Script Date: 11/20/2003 11:30:51 AM ******/
CREATE TABLE [dbo].[tblDeals] (
[DealID] [int] IDENTITY (1, 1) NOT NULL ,
[CompanyID] [int] NOT NULL ,
[DealDate] [smalldatetime] NOT NULL ,
[PhaseTypeID] [tinyint] NOT NULL ,
[CashAmount] [smallmoney] NOT NULL ,
[StatusID] [tinyint] NOT NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[tblPhase] Script Date: 11/20/2003 11:30:52 AM ******/
CREATE TABLE [dbo].[tblPhase] (
[PhaseID] [tinyint] IDENTITY (1, 1) NOT NULL ,
[PhaseTypeID] [tinyint] NOT NULL ,
[PhaseDescription] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[PhasePercentage] [float] NOT NULL
) ON [PRIMARY]
GO

/****** Object: Table [dbo].[tblProduction] Script Date: 11/20/2003 11:30:52 AM ******/
CREATE TABLE [dbo].[tblProduction] (
[TransactionID] [int] IDENTITY (1, 1) NOT NULL ,
[DealID] [int] NOT NULL ,
[PhaseID] [tinyint] NOT NULL ,
[TransactionTimeStamp] [smalldatetime] NOT NULL ,
[Comments] [varchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblCompany] WITH NOCHECK ADD
CONSTRAINT [PK_tblCompany] PRIMARY KEY CLUSTERED
(
[CompanyID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblContractStatus] WITH NOCHECK ADD
CONSTRAINT [PK_tblContractStatus] PRIMARY KEY CLUSTERED
(
[StatusID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblPhaseType] WITH NOCHECK ADD
CONSTRAINT [PK_tblPhaseType] PRIMARY KEY CLUSTERED
(
[PhaseTypeID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblDeals] WITH NOCHECK ADD
CONSTRAINT [PK_tblDeals] PRIMARY KEY CLUSTERED
(
[DealID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblPhase] WITH NOCHECK ADD
CONSTRAINT [PK_tblPhase] PRIMARY KEY CLUSTERED
(
[PhaseID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblProduction] WITH NOCHECK ADD
CONSTRAINT [PK_tblProduction] PRIMARY KEY CLUSTERED
(
[TransactionID]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblDeals] ADD
CONSTRAINT [DF_tblDeals_StatusID] DEFAULT (5) FOR [StatusID]
GO

ALTER TABLE [dbo].[tblProduction] ADD
CONSTRAINT [DF_tblProduction_TransactionTimeStamp] DEFAULT (getdate()) FOR [TransactionTimeStamp]
GO

ALTER TABLE [dbo].[tblDeals] ADD
CONSTRAINT [FK_tblDeals_tblCompany] FOREIGN KEY
(
[CompanyID]
) REFERENCES [dbo].[tblCompany] (
[CompanyID]
),
CONSTRAINT [FK_tblDeals_tblContractStatus] FOREIGN KEY
(
[StatusID]
) REFERENCES [dbo].[tblContractStatus] (
[StatusID]
),
CONSTRAINT [FK_tblDeals_tblPhaseType] FOREIGN KEY
(
[PhaseTypeID]
) REFERENCES [dbo].[tblPhaseType] (
[PhaseTypeID]
)
GO

ALTER TABLE [dbo].[tblPhase] ADD
CONSTRAINT [FK_tblPhase_tblPhaseType] FOREIGN KEY
(
[PhaseTypeID]
) REFERENCES [dbo].[tblPhaseType] (
[PhaseTypeID]
)
GO

ALTER TABLE [dbo].[tblProduction] ADD
CONSTRAINT [FK_tblProduction_tblDeals] FOREIGN KEY
(
[DealID]
) REFERENCES [dbo].[tblDeals] (
[DealID]
),
CONSTRAINT [FK_tblProduction_tblPhase] FOREIGN KEY
(
[PhaseID]
) REFERENCES [dbo].[tblPhase] (
[PhaseID]
)
GO

exec sp_addextendedproperty N'MS_Description', N'Identifier', N'user', N'dbo', N'table', N'tblContractStatus', N'column', N'StatusID'
GO
exec sp_addextendedproperty N'MS_Description', N'Description', N'user', N'dbo', N'table', N'tblContractStatus', N'column', N'Status'

GO

exec sp_addextendedproperty N'MS_Description', N'Determines the type of phase structure this deal will go through', N'user', N'dbo', N'table', N'tblDeals', N'column', N'PhaseTypeID'
GO
exec sp_addextendedproperty N'MS_Description', N'Identifies the current status of deal', N'user', N'dbo', N'table', N'tblDeals', N'column', N'StatusID'

GO

exec sp_addextendedproperty N'MS_Description', N'Determines the percentage value of the phase', N'user', N'dbo', N'table', N'tblPhase', N'column', N'PhasePercentage'

GO

exec sp_addextendedproperty N'MS_Description', null, N'user', N'dbo', N'table', N'tblProduction', N'column', N'TransactionTimeStamp'

GO

------------
And here's some data
------------


INSERT INTO [tblPhaseType] ([Desription])VALUES('TV Commercial - 4 Phases')
INSERT INTO [tblPhaseType] ([Desription])VALUES('Full Campaign - 6 Phases')

INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Customer Info',1.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Write script',2.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Shoot',3.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(1,'Edit commercial',2.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Customer info',1.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Write script',1.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Design print ad',1.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Shoot',1.500000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Edit',2.000000000000000e-001)
INSERT INTO [tblPhase] ([PhaseTypeID],[PhaseDescription],[PhasePercentage])VALUES(2,'Publish',2.000000000000000e-001)

INSERT INTO [tblContractStatus] ([Status])VALUES('Completed')
INSERT INTO [tblContractStatus] ([Status])VALUES('Hold')
INSERT INTO [tblContractStatus] ([Status])VALUES('Collections')
INSERT INTO [tblContractStatus] ([Status])VALUES('Legal')
INSERT INTO [tblContractStatus] ([Status])VALUES('In Progress')

INSERT INTO [tblCompany] ([CompanyName])VALUES('Johnny''s Remodeling')
INSERT INTO [tblCompany] ([CompanyName])VALUES('Perfect Cut Lawncare')
INSERT INTO [tblCompany] ([CompanyName])VALUES('Useless Ideas Unlimited')
INSERT INTO [tblCompany] ([CompanyName])VALUES('Try-It-Again, Inc.')

INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(1,'Aug 5 2003 12:00:00:000AM',1,120.0000,5)
INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(2,'Sep 9 2003 12:00:00:000AM',2,150.0000,5)
INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(3,'Sep 10 2003 12:00:00:000AM',2,130.0000,5)
INSERT INTO [tblDeals] ([CompanyID],[DealDate],[PhaseTypeID],[CashAmount],[StatusID])VALUES(4,'Nov 20 2003 12:00:00:000AM',1,190.0000,5)

INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,1,'Nov 10 2003 10:23:00:000AM','Received company logo')
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,2,'Nov 10 2003 10:23:00:000AM','Finished writing script')
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(2,5,'Nov 10 2003 10:23:00:000AM','Just received company info')
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(2,7,'Nov 10 2003 10:24:00:000AM','Finished designing ad copy')
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,3,'Nov 20 2003 11:29:00:000AM','Did more work')
INSERT INTO [tblProduction] ([DealID],[PhaseID],[TransactionTimeStamp],[Comments])VALUES(1,4,'Nov 20 2003 11:29:00:000AM','Finally finished the job')

OK,
The trigger should be placed in the table TransactionTimeStamp.
The Trigger Fires on Insert

The SQL should look Like This


Declare
@.phasesDone int,
@.phasesNeeded int,
@.dealid int,
@.phaseid int,
@.phasetypeid int

Select @.dealid = dealid, @.phaseid = phaseid from inserted

Select @.phasesdone = count(*) from tblProduction where dealid = @.dealid and phaseid = @.phaseid

Select @.phasesneeded = count(*) from tblphase INNER JOIN tbldeals on tblphase.phasetypeid = tbldeals.phasetypeid where tbldeals.id = @.dealid

If @.phasesdone = @.phasesneeded
begin
update tbldeals set statusid = 1 where id = @.dealid
end

that shoul work i'm quite sure.
hope this helps you.|||Hi Misiu,

Thanks for the help. I'm getting an error. I think it has somehting to do with getting the PhaseID and the DealID from the "inserted". For some reason I've never been able to get this to work for me. Is there anything I need to do i.e. activate, some kind of setting or something -- so that I can get data from the inserted?|||What error do you get?
As I know you don't have to activate any setting.

Need help writing a SQL Server Query


Could someone please help me out? I need to write a sql stored proc to query the following table.
My SQL experience is very week. If someone can help me with this, I will be happy to pay you$40 for
your help.

I need the proc to do the following:
1.) For every Superintendent in a region, country state and county; return the state name, superintendent name,
the county name and and a string which is a comma delimited list of schools they supervise. See the sample output italicised and bold.

So the big challenge here is to also return a string that is a concatenation of school names for a particular
Superintendent in a given state and county. For example:East,Kennedy,Apolo,Morrison.

So basically the stored proc should accept input parameters of the Region, Country, State, and County

Here is the data table:


REGION COUNTRY STATE SUPER_INTENDENT PHONE_NO SCHOOL County


NA USA Texas Mike Andrews 789-3614 East Lake
NA USA Texas Mike Andrews 789-3614 Kennedy Lake
NA USA Texas Mike Andrews 789-3614 Apolo Lake
NA USA Texas Mike Andrews 789-3614 Morrison Lake
NA USA Texas Amy Markson 789-2134 Anderson Maylor
NA USA Texas Amy Markson 789-2134 Molina Maylor
NA USA Texas Amy Markson 789-2134 Polima Maylor
NA USA Ohio Terry Ellis 966-8314 Kingston Keel
NA USA Ohio Terry Ellis 966-8314 Martin Keel
NA USA Ohio Terry Ellis 966-8314 Eastmore Keel
NA USA Ohio Terry Ellis 966-8314 Canondale Keel


Here is the sample output the way it will appear on a web form:


State:Texas

County:Lake


Mike Andrews East,Kennedy,Apolo,Morrison
789-3614

County:Maylor

Amy Markson
789-2134 Anderson,Molina,Polima


State:Ohio

County:Keel

Terry Ellis Kingston,Martin,Eastomore,Keel

You can mail me the check..

You could create a stored proc that would concatenate the values based on given state and county.

Declare

@.schoolvarchar(500)

select

@.school=isnull(@.school,'')+','+ school

from

yourTable

where

state= @.state and county=@.county

Given the above hint, I hope you can figure out the rest.

|||Sorry your post has not helped me at all. I need someone to write the query for me. I will be happy to pay that person. please do not respond to this post if you are not serious about helping me.|||

ndinakar:

You can mail me the check..

That was meant to be a joke. I forgot to put a "smiley face" at the end. I was trying to show you how to write the code yourself since what you are trying to do is pretty simple. Now, I do agree that if you cannot figure out how to put the rest of the puzle together, you definetely need someone to write you the code. And perhaps you will need to spend more than the $40 you are offering..

|||

I appreciate your sense of humor. No problem.Big Smile

Another fellow on the forum has offered to help me. I will see take his advice and try to get it working. Thank you.

Need help writing a SQL Script

Im attempting to write a script to add specific permissions to tables each
morning.
The problem is I have a database that gets purged each morning along with
the tables, and any permissions I have set for a user is also purged.
My user name is "workflow" with only public rights. In the database, users
"workflow " has select permissions to three tables which are FMS_Acct,
APS_Vendor, APS_Master.
If anyone can assist with the proper SQL that restorse the permissions would
be of great assistance.
Thank you in advance
RobertYou mean something like:
GRANT SELECT ON FMS_Acct TO workflow
"robert_at_cbb" wrote:
> Im attempting to write a script to add specific permissions to tables each
> morning.
> The problem is I have a database that gets purged each morning along with
> the tables, and any permissions I have set for a user is also purged.
> My user name is "workflow" with only public rights. In the database, users
> "workflow " has select permissions to three tables which are FMS_Acct,
> APS_Vendor, APS_Master.
> If anyone can assist with the proper SQL that restorse the permissions would
> be of great assistance.
> Thank you in advance
> Robert|||Yes thank you
"Jack" wrote:
> You mean something like:
> GRANT SELECT ON FMS_Acct TO workflow
> "robert_at_cbb" wrote:
> > Im attempting to write a script to add specific permissions to tables each
> > morning.
> >
> > The problem is I have a database that gets purged each morning along with
> > the tables, and any permissions I have set for a user is also purged.
> >
> > My user name is "workflow" with only public rights. In the database, users
> > "workflow " has select permissions to three tables which are FMS_Acct,
> > APS_Vendor, APS_Master.
> >
> > If anyone can assist with the proper SQL that restorse the permissions would
> > be of great assistance.
> >
> > Thank you in advance
> > Robert

Need help writing a SQL Script

Im attempting to write a script to add specific permissions to tables each
morning.
The problem is I have a database that gets purged each morning along with
the tables, and any permissions I have set for a user is also purged.
My user name is "workflow" with only public rights. In the database, users
"workflow " has select permissions to three tables which are FMS_Acct,
APS_Vendor, APS_Master.
If anyone can assist with the proper SQL that restorse the permissions would
be of great assistance.
Thank you in advance
Robert
You mean something like:
GRANT SELECT ON FMS_Acct TO workflow
"robert_at_cbb" wrote:

> Im attempting to write a script to add specific permissions to tables each
> morning.
> The problem is I have a database that gets purged each morning along with
> the tables, and any permissions I have set for a user is also purged.
> My user name is "workflow" with only public rights. In the database, users
> "workflow " has select permissions to three tables which are FMS_Acct,
> APS_Vendor, APS_Master.
> If anyone can assist with the proper SQL that restorse the permissions would
> be of great assistance.
> Thank you in advance
> Robert
|||Yes thank you
"Jack" wrote:
[vbcol=seagreen]
> You mean something like:
> GRANT SELECT ON FMS_Acct TO workflow
> "robert_at_cbb" wrote:

Need help writing a SQL Script

Im attempting to write a script to add specific permissions to tables each
morning.
The problem is I have a database that gets purged each morning along with
the tables, and any permissions I have set for a user is also purged.
My user name is "workflow" with only public rights. In the database, users
"workflow " has select permissions to three tables which are FMS_Acct,
APS_Vendor, APS_Master.
If anyone can assist with the proper SQL that restorse the permissions would
be of great assistance.
Thank you in advance
RobertYou mean something like:
GRANT SELECT ON FMS_Acct TO workflow
"robert_at_cbb" wrote:

> Im attempting to write a script to add specific permissions to tables each
> morning.
> The problem is I have a database that gets purged each morning along with
> the tables, and any permissions I have set for a user is also purged.
> My user name is "workflow" with only public rights. In the database, users
> "workflow " has select permissions to three tables which are FMS_Acct,
> APS_Vendor, APS_Master.
> If anyone can assist with the proper SQL that restorse the permissions wou
ld
> be of great assistance.
> Thank you in advance
> Robert|||Yes thank you
"Jack" wrote:
[vbcol=seagreen]
> You mean something like:
> GRANT SELECT ON FMS_Acct TO workflow
> "robert_at_cbb" wrote:
>

Need help writing a query

Database consists of the following 4 tables with respective
attributes:

CUSTOMER(C#, CUSTOMER NAME, ADDRESS), the key is [C#]
ITEM(I#, ITEM NAME, MANUFACTURER, YEAR), the key is [I#]
BOUGHT(C#, I#, DATE, QUANTITY), the key is [C#, I#,DATE]
PREFER(I#, C#), the key is [I#, C#]

I'm trying to construct the following query (in SQL)

List of customers that bought all the items that John prefers.

I can get the list of all the items that John prefers, but I'm not
sure how to check that list against customers who bought ALL those
items. I'm assuming it's either a division or some sort of subtraction
but I'm not sure how to formulate the SQL query.

Any and all help is appreciated, thanks!(tizmagik@.gmail.com) writes:

Quote:

Originally Posted by

Database consists of the following 4 tables with respective
attributes:
>
CUSTOMER(C#, CUSTOMER NAME, ADDRESS), the key is [C#]
ITEM(I#, ITEM NAME, MANUFACTURER, YEAR), the key is [I#]
BOUGHT(C#, I#, DATE, QUANTITY), the key is [C#, I#,DATE]
PREFER(I#, C#), the key is [I#, C#]
>
I'm trying to construct the following query (in SQL)
>
List of customers that bought all the items that John prefers.
>
I can get the list of all the items that John prefers, but I'm not
sure how to check that list against customers who bought ALL those
items. I'm assuming it's either a division or some sort of subtraction
but I'm not sure how to formulate the SQL query.


This smells of class assignment, but OK, let's go for it anyway.

If memory serves this is something they for some reason I've never
understood call relational division. In less occluded terms, a HAVING
clause can shortcut the need for a couple of EXISTS and NOT EXISTS.

SELKCT C.C#, C.CUSTOMER_NAME
FROM CUSTOMER C
JOIN (SELECT B.C#
FROM BOUGHT B
GROUP BY B.C#
HAVING COUNT(DISTINCT B.I#) =
(SELECT COUNT(*)
FROM PREFER P
JOIN CUSTOMER C ON P.C# = C.C#
WHERE C.CUSTOMER_NAME = 'John')) AS res
ON C.C# = res.C#

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Erland Sommarskog wrote:

Quote:

Originally Posted by

(tizmagik@.gmail.com) writes:

Quote:

Originally Posted by

>Database consists of the following 4 tables with respective
>attributes:
>>
>CUSTOMER(C#, CUSTOMER NAME, ADDRESS), the key is [C#]
>ITEM(I#, ITEM NAME, MANUFACTURER, YEAR), the key is [I#]
>BOUGHT(C#, I#, DATE, QUANTITY), the key is [C#, I#,DATE]
>PREFER(I#, C#), the key is [I#, C#]
>>
>I'm trying to construct the following query (in SQL)
>>
>List of customers that bought all the items that John prefers.
>>
>I can get the list of all the items that John prefers, but I'm not
>sure how to check that list against customers who bought ALL those
>items. I'm assuming it's either a division or some sort of subtraction
>but I'm not sure how to formulate the SQL query.


>
This smells of class assignment, but OK, let's go for it anyway.
>
If memory serves this is something they for some reason I've never
understood call relational division. In less occluded terms, a HAVING
clause can shortcut the need for a couple of EXISTS and NOT EXISTS.
>
SELKCT C.C#, C.CUSTOMER_NAME
FROM CUSTOMER C
JOIN (SELECT B.C#
FROM BOUGHT B
GROUP BY B.C#
HAVING COUNT(DISTINCT B.I#) =
(SELECT COUNT(*)
FROM PREFER P
JOIN CUSTOMER C ON P.C# = C.C#
WHERE C.CUSTOMER_NAME = 'John')) AS res
ON C.C# = res.C#


That will select all customers who bought the same /number/ of
items as what John prefers, but not necessarily the same items.

I think this will select all customers who bought all the items
that John prefers:

SELECT C.C#, C.CUSTOMER_NAME
FROM CUSTOMER C
JOIN BOUGHT B ON C.C# = B.C#
JOIN PREFER P ON B.I# = P.I#
JOIN CUSTOMER J ON P.C# = J.C# AND J.CUSTOMER_NAME = 'John'
GROUP BY C.C#, C.CUSTOMER_NAME
HAVING COUNT(*) = (
SELECT COUNT(*)
FROM PREFER P
JOIN CUSTOMER J ON P.C# = J.C# AND J.CUSTOMER_NAME = 'John'
)|||Erland: Why would it matter if it's a class assignment or not? Is not
the purpose of a Usenet group to share and learn from each other? What
relevance is it what the knowledge will be used for? Thank you for
your attempt anyway, but Ed's answer seems more in line with what the
query is intended to do.

Thank you Ed, seems to be what I'm looking for, it's interesting, I
never even though of setting up a Count, but now that I look at it,
it's hard to imagine any other way of doing it.

Thanks again :)|||tizmagik@.gmail.com wrote:

Quote:

Originally Posted by

Thank you Ed, seems to be what I'm looking for, it's interesting, I
never even though of setting up a Count, but now that I look at it,
it's hard to imagine any other way of doing it.


I thought of doing J JOIN P LEFT JOIN B and looking for nulls, but I
can't figure out a way to do it, and even if there is one, it would
probably be less clear than the COUNT = COUNT method.|||<tizmagik@.gmail.comwrote in message
news:1176697766.757819.271590@.b75g2000hsg.googlegr oups.com...

Quote:

Originally Posted by

Erland: Why would it matter if it's a class assignment or not?


It matters if you're asking others to do your homework. Some professors
frown upon that. (and it could, in some cases, be considered a form of
cheating.)

Quote:

Originally Posted by

Is not
the purpose of a Usenet group to share and learn from each other?


Oh certainly. And I think Erland would agree, many of us here love to help
others (and certainly to learn from others). But from time to time (and I'm
not claiming you're one of them) who come here looking simply for answers to
homework problems, not necessarily understanding. That benefits no one in
the long run.

Quote:

Originally Posted by

What
relevance is it what the knowledge will be used for? Thank you for
your attempt anyway, but Ed's answer seems more in line with what the
query is intended to do.
>
Thank you Ed, seems to be what I'm looking for, it's interesting, I
never even though of setting up a Count, but now that I look at it,
it's hard to imagine any other way of doing it.
>
Thanks again :)
>


--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||>Why would it matter if it's a class assignment or not? Is not the purpose of a Usenet group to share and learn from each other? <<

In most university systems having someone else do your homework gets
you kicked out of school. It is academic fraud. I know. I have had
two kids expelled from schools in New Zealand and Australia for doing
this. An old friend of mine got a "social engineer" taken out of
Georgia Tech; etc.|||--CELKO-- wrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

Quote:

Originally Posted by

>>Why would it matter if it's a class assignment or not? Is not the purpose of a Usenet group to share and learn from each other? <<


>
In most university systems having someone else do your homework gets
you kicked out of school. It is academic fraud. I know. I have had
two kids expelled from schools in New Zealand and Australia for doing
this. An old friend of mine got a "social engineer" taken out of
Georgia Tech; etc.


Same rule applies here at the University of Washington.

Get caught cheating and it is a one-way trip.

Anyone that thinks instructors such as myself are not watching
these groups is in the wrong business.
--
Daniel A. Morgan
University of Washington
damorgan@.x.washington.edu
(replace x with u to respond)
Puget Sound Oracle Users Group
www.psoug.org|||(tizmagik@.gmail.com) writes:

Quote:

Originally Posted by

Erland: Why would it matter if it's a class assignment or not? Is not
the purpose of a Usenet group to share and learn from each other?


But Usenet is not the best place to learn everything. If you have some
experience in the field of SQL programming, I can assume that you can
understand the solution I post to some extend and learn from it.

But if you are a student who is not interested in doing his homework?

I remember way back when, when I was a student myself, and also worked as
an assistant teacher in programming. Back in those days, the assignments
were made on paper, and when the student was approved for this week's
exercise I would give him a paper with the "ideal" solution. Sometimes
it happened that students arrived to the classroom with this ideal
solution, in which case I told them not do to it again. And I did not
approve them for that assignment. (It was permitted to miss one or two.)

One year I had a group in Programming 2, an optional class which taught
programming structures. I had one guy who consistently arrived with
the ideal solution, and I knew that his girlfriend was taking the same
class. I figured that at this stage, he should know better than cheating,
so I did not say anything. I approved his "solutions" without a comment
and let him go. But these assignments were not all - there was a written
exam as well. And when the results came up, his girl-friend was there.
But, not surprisingly, he wasn't. He had just copied the ideal solutions,
but he hadn't learnt anything.

Quote:

Originally Posted by

Thank you Ed, seems to be what I'm looking for, it's interesting, I
never even though of setting up a Count, but now that I look at it,
it's hard to imagine any other way of doing it.


Sorry for the incorrect solution, but there is a standard recommendation
for this type of questions, and that is that you post:

o CREATE TABLE statements for your table(s).
o INSERT statements with sample data.
o The desireed output, given the sample.

That makes it easy to copy and paste to develop a tested solution. Without
that, most people here tend to just type something up, and sometimes
there are errors.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||I am fairly new to SQL programming and believe me that wasn't the only
thing that the assignment asked, however this question was the one
question that I had a lot of trouble with and the lack of a book for
the class (it's strictly lecture notes) was what brought me to look
for help elsewhere.

If I would have based the SQL query on the examples given by the
professor I would have gotten a list of all customers who bought *at
least one* item that "john" prefers, as apposed to the correct list
(all customers who bought *all* the items that john prefers).
Furthermore, the professor did not go over COUNT so I really did not
see any way of doing it with what he has gone over so far. Perhaps
there is a solution without using COUNT, I will be sure to ask the
professor during next lecture.

Thanks for those that helped.|||On 16 Apr 2007 21:15:59 -0700, tizmagik@.gmail.com wrote:

Quote:

Originally Posted by

Perhaps
>there is a solution without using COUNT, I will be sure to ask the
>professor during next lecture.


Hi tizmagik,

Indeed, there is. It is called "inverse logic". If a customer has bought
every item John prefers, than clearly, there can not be any single item
that is preferred by John but that the customer didn't buy. I'm sure
that you're able to cough up the actual query for that logic. :-)

This solution is actually the solution most people produce first for
this problem. Maybe because many classes explain subqueries and NOT
EXISTS before moving on to aggregates and HAVING? Or maybe it's just
related to how our brain functions? Anyway, the version as posted by Ed
looks like (I didn't check in detail) the second standard solution to
this problem, based on the logic "if a customer buys everything John
prefers, then the number of items bought by the customers *and* prefered
by John must be equal to the number of items prefered by John. Outside
of class, you'd probably try both against the actual data on the actual
database to figure out which one gives the best performance.

--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||(tizmagik@.gmail.com) writes:

Quote:

Originally Posted by

I am fairly new to SQL programming and believe me that wasn't the only
thing that the assignment asked, however this question was the one
question that I had a lot of trouble with and the lack of a book for
the class (it's strictly lecture notes) was what brought me to look
for help elsewhere.
>
If I would have based the SQL query on the examples given by the
professor I would have gotten a list of all customers who bought *at
least one* item that "john" prefers, as apposed to the correct list
(all customers who bought *all* the items that john prefers).
Furthermore, the professor did not go over COUNT so I really did not
see any way of doing it with what he has gone over so far. Perhaps
there is a solution without using COUNT, I will be sure to ask the
professor during next lecture.


So that's another problem with asking for help with class assignments
on Usenet. While the COUNT may be a more elegant solution, the professor
probably wanted you to exercise in the use of EXISTS and NOT EXISTS.
Which certainly is an investment worth making, because such problem
as commonplace. (While the exercise you had, has a disctinct flavoour
of class assignment. Did I ever encounter such a problem myself? I can't
recall any.)

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks for your input guys.

I'll be sure to post here when the solution without using COUNT is
covered (assuming there is one).|||Okay, this is what I have come up with so far:

SELECT c1.Customer_Name
FROM Customer c1
WHERE c1.CustomerID IN (
SELECT B.CustomerID
FROM Bought B
WHERE B.ItemID IN (
SELECT P.ItemID
FROM Prefer P, Customer c2
WHERE c2.Customer_Name = 'John'
AND c2.CustomerID = P.CustomerID ) )

But that brings me back to the problem where it will list customers
that bought *at least one* of the items that John prefers, not ALL of
the items that John prefers, that query gives:
John
Jeremy
Michelle

The expected answer is just 'Michelle' as being the only customer that
bought ALL of the items that John prefers with the following data:

-CUSTOMER table
CREATE TABLE Customer (
CustomerID int(4) NOT NULL,
Customer_Name varchar(30) NOT NULL,
Address varchar(30) NOT NULL,
PRIMARY KEY (CustomerID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO Customer VALUES (1000, 'John', '123 John St.');
INSERT INTO Customer VALUES (1001, 'Jeremy', '456 Jeremy Ave.');
INSERT INTO Customer VALUES (1002, 'Michelle', '789 Michelle Blvd.');
INSERT INTO Customer VALUES (1003, 'Laura', '1011 Laura Way');
INSERT INTO Customer VALUES (1004, 'Nicholas', '1004 Nicholas Place');
INSERT INTO Customer VALUES (1005, 'James', '1005 James Drive');

-ITEM table
CREATE TABLE Item (
ItemID int(11) NOT NULL,
Item_Name varchar(30) NOT NULL,
Manufacturer varchar(30) NOT NULL,
`Year` int(4) NOT NULL,
PRIMARY KEY (ItemID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO Item VALUES (9000, 'Camera', 'Nikkon', 1997);
INSERT INTO Item VALUES (9001, 'Camera', 'Sony', 1998);
INSERT INTO Item VALUES (9002, 'Camera', 'Olympus', 2001);
INSERT INTO Item VALUES (9003, 'Camera', 'Olympus', 2001);
INSERT INTO Item VALUES (9004, 'Camera', 'Polaroid', 1991);
INSERT INTO Item VALUES (9005, 'Laptop', 'Dell', 2006);
INSERT INTO Item VALUES (9006, 'Laptop', 'HP', 2005);
INSERT INTO Item VALUES (9007, 'Desktop', 'Dell', 2002);
INSERT INTO Item VALUES (9008, 'Desktop', 'Apple', 2004);
INSERT INTO Item VALUES (9009, 'PDA', 'Palm', 2003);
INSERT INTO Item VALUES (9010, 'PDA', 'Handspring', 1998);
INSERT INTO Item VALUES (9011, 'HDTV', 'Sony', 2004);
INSERT INTO Item VALUES (9012, 'HDTV', 'Samsung', 2005);
INSERT INTO Item VALUES (9013, 'HDTV', 'Toshiba', 2003);
INSERT INTO Item VALUES (9014, 'HDTV', 'Mitsubishi', 2003);

-BOUGHT table
CREATE TABLE Bought (
CustomerID int(4) NOT NULL,
ItemID int(4) NOT NULL,
`Date` date NOT NULL,
Quantity int(5) NOT NULL,
PRIMARY KEY (CustomerID,ItemID,`Date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO Bought VALUES (1002, 9000, '2007-04-01', 5);
INSERT INTO Bought VALUES (1002, 9001, '2007-04-30', 2);
INSERT INTO Bought VALUES (1002, 9008, '2007-04-09', 1);
INSERT INTO Bought VALUES (1002, 9014, '2007-04-15', 1);
INSERT INTO Bought VALUES (1001, 9001, '2007-04-16', 1);
INSERT INTO Bought VALUES (1001, 9008, '2007-04-16', 1);
INSERT INTO Bought VALUES (1000, 9008, '2007-04-16', 5);
INSERT INTO Bought VALUES (1000, 9001, '2007-04-17', 2);
INSERT INTO Bought VALUES (1005, 9003, '2007-04-16', 2);
INSERT INTO Bought VALUES (1004, 9002, '2007-04-16', 1);
INSERT INTO Bought VALUES (1001, 9011, '2007-02-16', 3);
INSERT INTO Bought VALUES (1001, 9010, '2007-02-16', 3);
INSERT INTO Bought VALUES (1003, 9012, '2007-02-16', 1);
INSERT INTO Bought VALUES (1005, 9013, '2007-02-16', 2);
INSERT INTO Bought VALUES (1004, 9006, '2007-04-01', 1);

-PREFER table
CREATE TABLE Prefer (
ItemID int(4) NOT NULL,
CustomerID int(4) NOT NULL,
PRIMARY KEY (ItemID,CustomerID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO Prefer VALUES (9000, 1000);
INSERT INTO Prefer VALUES (9001, 1000);
INSERT INTO Prefer VALUES (9002, 1004);
INSERT INTO Prefer VALUES (9003, 1003);
INSERT INTO Prefer VALUES (9006, 1001);
INSERT INTO Prefer VALUES (9007, 1004);
INSERT INTO Prefer VALUES (9007, 1005);
INSERT INTO Prefer VALUES (9008, 1000);
INSERT INTO Prefer VALUES (9008, 1002);
INSERT INTO Prefer VALUES (9008, 1004);
INSERT INTO Prefer VALUES (9009, 1002);
INSERT INTO Prefer VALUES (9013, 1005);
INSERT INTO Prefer VALUES (9014, 1000);

Again, any help is appreciated. (Yes, the professor didn't go over
AutoNumber fields yet in case you're wondering :) )|||A little closer... I believe this would be the right SQL
theoretically, but this will only work in an Oracle DB or DB that
supports the MINUS operation (MySQL doesnt), so I will try to
reformulate this without using MINUS. I'm guessing it's some sort of
JOIN operation where you check for Nulls and select those that are not
Null...

SELECT B1.CustomerID
FROM Bought B1
WHERE NOT EXISTS (
( SELECT Prefer.ItemID
FROM Prefer, Customer
WHERE Customer.Customer_Name = 'John'
AND Prefer.CustomerID = Customer.CustomerID
) MINUS (
SELECT B2.ItemID
FROM Bought B2
WHERE B2.CustomerID = B1.CustomerID )
)

Any help would be appreciated.|||tizmagik@.gmail.com wrote:

Quote:

Originally Posted by

Okay, this is what I have come up with so far:
>
SELECT c1.Customer_Name
FROM Customer c1
WHERE c1.CustomerID IN (
SELECT B.CustomerID
FROM Bought B
WHERE B.ItemID IN (
SELECT P.ItemID
FROM Prefer P, Customer c2
WHERE c2.Customer_Name = 'John'
AND c2.CustomerID = P.CustomerID ) )
>
But that brings me back to the problem where it will list customers
that bought *at least one* of the items that John prefers, not ALL of
the items that John prefers, that query gives:


I think this will work:

SELECT c1.Customer_Name
FROM Customer c1
WHERE 0 = (
SELECT COUNT(*)
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
LEFT JOIN Bought B ON P.ItemID = B.ItemID
AND B.CustomerID = C1.CustomerID
WHERE C2.Customer_Name = 'John'
AND B.CustomerID IS NULL
)

but I still think the positive approach (COUNT = COUNT) is a lot
easier to understand.|||On Apr 17, 9:43 pm, Ed Murphy <emurph...@.socal.rr.comwrote:

Quote:

Originally Posted by

tizma...@.gmail.com wrote:

Quote:

Originally Posted by

Okay, this is what I have come up with so far:


>

Quote:

Originally Posted by

SELECT c1.Customer_Name
FROM Customer c1
WHERE c1.CustomerID IN (
SELECT B.CustomerID
FROM Bought B
WHERE B.ItemID IN (
SELECT P.ItemID
FROM Prefer P, Customer c2
WHERE c2.Customer_Name = 'John'
AND c2.CustomerID = P.CustomerID ) )


>

Quote:

Originally Posted by

But that brings me back to the problem where it will list customers
that bought *at least one* of the items that John prefers, not ALL of
the items that John prefers, that query gives:


>
I think this will work:
>
SELECT c1.Customer_Name
FROM Customer c1
WHERE 0 = (
SELECT COUNT(*)
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
LEFT JOIN Bought B ON P.ItemID = B.ItemID
AND B.CustomerID = C1.CustomerID
WHERE C2.Customer_Name = 'John'
AND B.CustomerID IS NULL
)
>
but I still think the positive approach (COUNT = COUNT) is a lot
easier to understand.


Thanks Ed, but I'm trying to avoid using COUNT since that was not
covered in class.|||tizmagik@.gmail.com wrote:

Quote:

Originally Posted by

On Apr 17, 9:43 pm, Ed Murphy <emurph...@.socal.rr.comwrote:

Quote:

Originally Posted by

>tizma...@.gmail.com wrote:

Quote:

Originally Posted by

>>Okay, this is what I have come up with so far:
>>SELECT c1.Customer_Name
>>FROM Customer c1
>>WHERE c1.CustomerID IN (
>> SELECT B.CustomerID
>> FROM Bought B
>> WHERE B.ItemID IN (
>> SELECT P.ItemID
>> FROM Prefer P, Customer c2
>> WHERE c2.Customer_Name = 'John'
>> AND c2.CustomerID = P.CustomerID ) )
>>But that brings me back to the problem where it will list customers
>>that bought *at least one* of the items that John prefers, not ALL of
>>the items that John prefers, that query gives:


>I think this will work:
>>
>SELECT c1.Customer_Name
>FROM Customer c1
>WHERE 0 = (
> SELECT COUNT(*)
> FROM Customer C2
> JOIN Prefer P ON C2.CustomerID = P.CustomerID
> LEFT JOIN Bought B ON P.ItemID = B.ItemID
> AND B.CustomerID = C1.CustomerID
> WHERE C2.Customer_Name = 'John'
> AND B.CustomerID IS NULL
>)
>>
>but I still think the positive approach (COUNT = COUNT) is a lot
>easier to understand.


>
Thanks Ed, but I'm trying to avoid using COUNT since that was not
covered in class.


SELECT C1.Customer_Name
FROM Customer C1
WHERE NOT EXISTS (
SELECT P.ItemID
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
LEFT JOIN Bought B ON P.ItemID = B.ItemID
AND B.CustomerID = C1.CustomerID
WHERE C2.Customer_Name = 'John'
AND B.CustomerID IS NULL
)

or

SELECT C1.Customer_Name
FROM Customer C1
WHERE NOT EXISTS (
SELECT P.ItemID
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
WHERE C2.Customer_Name = 'John'
AND P.ItemID NOT IN (
SELECT B.ItemID
FROM Bought B
WHERE B.CustomerID = C1.CustomerID
)
)|||On Apr 17, 10:03 pm, Ed Murphy <emurph...@.socal.rr.comwrote:

Quote:

Originally Posted by

tizma...@.gmail.com wrote:

Quote:

Originally Posted by

On Apr 17, 9:43 pm, Ed Murphy <emurph...@.socal.rr.comwrote:

Quote:

Originally Posted by

tizma...@.gmail.com wrote:
>Okay, this is what I have come up with so far:
>SELECT c1.Customer_Name
>FROM Customer c1
>WHERE c1.CustomerID IN (
> SELECT B.CustomerID
> FROM Bought B
> WHERE B.ItemID IN (
> SELECT P.ItemID
> FROM Prefer P, Customer c2
> WHERE c2.Customer_Name = 'John'
> AND c2.CustomerID = P.CustomerID ) )
>But that brings me back to the problem where it will list customers
>that bought *at least one* of the items that John prefers, not ALL of
>the items that John prefers, that query gives:
I think this will work:


>

Quote:

Originally Posted by

Quote:

Originally Posted by

SELECT c1.Customer_Name
FROM Customer c1
WHERE 0 = (
SELECT COUNT(*)
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
LEFT JOIN Bought B ON P.ItemID = B.ItemID
AND B.CustomerID = C1.CustomerID
WHERE C2.Customer_Name = 'John'
AND B.CustomerID IS NULL
)


>

Quote:

Originally Posted by

Quote:

Originally Posted by

but I still think the positive approach (COUNT = COUNT) is a lot
easier to understand.


>

Quote:

Originally Posted by

Thanks Ed, but I'm trying to avoid using COUNT since that was not
covered in class.


>
SELECT C1.Customer_Name
FROM Customer C1
WHERE NOT EXISTS (
SELECT P.ItemID
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
LEFT JOIN Bought B ON P.ItemID = B.ItemID
AND B.CustomerID = C1.CustomerID
WHERE C2.Customer_Name = 'John'
AND B.CustomerID IS NULL
)
>
or
>
SELECT C1.Customer_Name
FROM Customer C1
WHERE NOT EXISTS (
SELECT P.ItemID
FROM Customer C2
JOIN Prefer P ON C2.CustomerID = P.CustomerID
WHERE C2.Customer_Name = 'John'
AND P.ItemID NOT IN (
SELECT B.ItemID
FROM Bought B
WHERE B.CustomerID = C1.CustomerID
)
)


That first one didn't work for me, some syntax error, not sure why,
might just be a phpMyAdmin problem, but that second one worked
beautifully.

I'm trying to step through it and understand it line by line now...
this is what I understand from it:

You are selecting all the customers that are not in the following:
- You are selecting all the Items that john prefers, from the list of
items that are not in the list of items that customers have bought

haha really confusing, but I think I get it. Thanks so much for your
help.|||tizmagik@.gmail.com wrote:

Quote:

Originally Posted by

That first one didn't work for me, some syntax error, not sure why,
might just be a phpMyAdmin problem,


You do realize this isn't a MySQL group?

Quote:

Originally Posted by

but that second one worked beautifully.
>
I'm trying to step through it and understand it line by line now...
this is what I understand from it:
>
You are selecting all the customers that are not in the following:
- You are selecting all the Items that john prefers, from the list of
items that are not in the list of items that customers have bought


For each customer, you're looking for items that John prefers
but the customer didn't buy; if there is no such item, then the
customer gets selected.|||I couldn't find a suitable MySQL (or just SQL group) that was as
active as this one. Thanks though.|||(tizmagik@.gmail.com) writes:

Quote:

Originally Posted by

I couldn't find a suitable MySQL (or just SQL group) that was as
active as this one. Thanks though.


There is a comp.databases.mysql. Don't how much traffic there is though.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx