Complicated Query? Cant Figure Out What I Need...

Jan 3, 2006

I have run into a problem, I have 2 fields in my database, both key fields:

Table 1
=====
Field X <key>
Field Y <key>

In field X, there are say about 3 records for each unique Field Y. I let my users query the data base like follows:

Enter the Codes you want: 1000 and 3000 and 8500

So I want to pick up records where there will be the above values for All Y values. i.e 1000/AAA, 3000/AAA, and 8500 for AAA - if there is even ONE of the X values not matching a record without a matching X value, leave it out.

i.e:
X=1000,Y=AAA
X=3000,Y=AAA
X=8500,Y=AAA
X=1000,Y=BBB
X=3000,Y=BBB
X=8500,Y=BBB
X=1000,Y=CCC
X=3000,Y=CCC
X=9999,Y=CCC

When the query runs, I want to see the following records:

X=1000,Y=AAA
X=3000,Y=AAA
X=8500,Y=AAA
X=1000,Y=BBB
X=3000,Y=BBB
X=8500,Y=BBB

BUT NOT:

X=1000,Y=CCC
X=3000,Y=CCC
X=9999,Y=CCC

because one of the X values was not matched (the last X value =9999 and not one of the requirements of the search)

So I guess I want something like this:

SELECT X,Y from TABLE1 WHERE ALL Y VALUES HAVE ALL OF THESE X VALUES (X=1000,X=3000,X=8500) IF ANY X VALUES ARE MISSING SKIP RECORD

^^ Hope the above makes sense... but I am really stuck. The only other way I think I could do it is, copy all records that match all 3 X values into a temp table, and weed out any that are missing any one of the X values after they are copied but, I am running this on MYSQL 5.0 Clustered, and there is not enough room in memory for it probably... and query time has to remain under a second.

Anyhelp would be appreciated...

View 5 Replies


ADVERTISEMENT

Real Figure Instead Of Exponential Figure Needed

May 29, 2008

Hello,

I use OPENROWSET to read values from Excel and store them in a SQL Server table. In the Excel file I have a row having format 'Number' with two decimal places.

Example: 1225000.00

When I select this value using SSMS I get the correct value:

1225000

Strange enough, I cannot see the decimals anymore. However, when I now store this value into my table and then select it from there I get: (the datatype in the table is VARCHAR(max))

1.225e+006

I would not care if I could convert this back to a numeric datatype but this seems not to work: CAST('1.225e+006' as INT) throws an exception. Obviously OPENROWSET sends the data strictly as a character string. Storing this into varchar(max) works for small figures but it starts to use exp values for big figures.

Does anybody has an idea how to bring huge Excel based figures safely into a MS SQL Table ?

Thanks: Peter

View 5 Replies View Related

Cannot Figure Query Out

May 2, 2008

I have a small database in which Employee's are linked to "Tags".   These tags can be red or yellow.  So,  I have 3 tables.
Tag_Colors :    tag_color_ID   ,    tag_colors
Employee_Table:  employeeID    ,      employee_name  
Tag_Table:      tagID,    tag_color_ID,   employeeID,   tag_notes
 
I need to be able to perform a query, where I can list employee's by the number of tags they have.
I don't even know how to get started on this  --     could anybody point me in the right direction?
After I can et a query working,  I think I can take it from there  -- and get it to display on a web page.
 
Thanks in advance. 
 
 
 
 
 
 
 
 

View 4 Replies View Related

Can't Figure Out This Query

Feb 21, 2007

I have a table with multiple records.

Some have the same value in the 'subkey' field.
I want to select all the records from the table that have their highest MAINKEY.

So say there were 4 records in the table that has 3 fields (id, subkey and mainkey)

Each record has a unique id field but the subkeys are the same for the first two and the sub keys are the same for the last two while the Mainkey can be different.

So the tables looks sort of lLike this:

ID SK MK
1 10 2
2 10 3
3 25 2
4 25 3

I want to query and select one record for each subkey, but I want it to be record that has the highest mainkey. In this case, it would be records with ID 2 and 4.

I can not figure this out. :eek:

Any help would be GREATLY appreciated.

View 3 Replies View Related

Complicated SQL Query

May 23, 2007

Hello
I am trying to write and SQL query...

I have a table with 4 columns, ID, Key, Value and SiteID.

SiteID can be Null or an int.

As an example I could have these four rows,
ID=1, key=colour, value=red, siteID=Null
ID=2, key=colour, value=green, siteID=2
ID=3, key=font, value=arial, siteID=2
ID=4, key=size, value=6,siteID=Null

My query will pass in a siteID and I need to bring back all rows with that site ID plus any rows whos key I haven't already got who's siteID =Null.

The Null site ID is default, so it always needs to bring back the null if a key doesn't exist with a siteID.

Does anyone know if that is even possible with just a straight SQL query?

Thanks

Becky

View 3 Replies View Related

HELP With SQL Query - (complicated)

Oct 10, 2006

Hi I have been tearing my hair out trying to resolve this problem.
A form is submitted with a number in to checkthe database for the items with that number of items in the quantity field(s) and display them.

There are 2 relevant Tables in the 2005 server SQL Database, One called "Products" the other called "ProductDetails"

In both tables is a field called Quantity, this hold a numerical value for the quantity of the product.

Some products have additional attributes such as sizes or colours and these are stored in the ProductDetails table.

Every product is stored in the "Products" table and has a unique ProductID, where a product has additional attributes, these along with the ProductID and the quantity for that particular attribute are stored in the ProductDetails table.

I am trying to loop through the database and produce a list of all the items and if they have any additional size or colour attributes then display these too, and if they dont have additional attributes then just display the product details and quantity stored in the Products table.


What I have actually done instead is produce a list of every item and every attribute in the database, but for example Where product 1 doesnt have any attributes, and neither does product 2, but product 3 and product 3 do, when the details are displayed on the page (Using ASP),

Rather than displaying product 1 details and the quantity in the "Products" table, product 2 and the details & quantity in the Products table, then product 3 and each of the attributes & Quanity pertaining to that item in the "ProductDetails" table, and so on, it shows every item as having every combination of attributes,

so although products 1 and 2 have no attributes, it will show product 1 with the first attribute of the other products and then show another product 1 with the next attribute from another product and keep going untill all the attributes in the whole of the Product details table is shown , then do the same thing with product 2 and then product 3 and so on.....

Also the products that have no attributes are not only shown with the attributes that they dont have, they are not shown without attribues and with the correct details in the list.




Here is my string, which has changed a million times, I am just learning as I go along so if it is obvious please be pateient with me and help me out...


rsResults.Source = "SELECT DISTINCT Products.ProductID, Products.ProductName, Products.ProductPict, Products.Quantity, ProductDetails.ProductDetailID, ProductDetails.P_Size, ProductDetails.P_Color, ProductDetails.Quantity FROM Products, ProductDetails WHERE Products.ProductID = Products.ProductID AND Products.Quantity <= "& +rsResults__var1 & " OR Products.ProductID = ProductDetails.ProductID AND ProductDetails.Quantity <= "& +rsResults__var1 & " Order by Products.ProductID asc "


Can anyone see why it is doing this instead of only showing the attributes next to the items that have attribues?

Please help

Warm Regards,
Joe

View 14 Replies View Related

Help With Complicated SQL Query

Sep 26, 2005

Hi everyone.

This is my scenario:

I have two tables:
persons (id,age,roleid)
roles (roleid,description)

I want to build a sql query to produce the following rows (example):
range(age) role1 role2 role3 .... rolen
0 to 4 11 24 5 7
5 to 9 42 7 1 0
10 to 14 14 21 9 8
15 to 20 7 0 7 19

I was reading an information concerning to ROLLUP and CUBE but I have no idea how to do a query like this.

Thanks for all your help!

Roland

View 4 Replies View Related

Complicated Query

Mar 2, 2008

I am trying to use ssis (sql query or .net-script task)
to transfer data from one table to another.
I have difficulties to make the query:

i have one table tbl_games which fields are :
type ,startDateTime, EndDateTime, playerId.
I need to check every 1/2 hour according to the startDateTime,
How many times a person is playing and to show it in a new table
tbl_collectData like this:
TimeplayerId Games_0-30_secondsGames_30-50_seconds

8-8:30 A 3 2
8:30-9B 2 10
9-:30C 20 7

The length of the game is measured by the StartDateTime -EndDateTime,
and only games type # 2 is being collected.
The number 3 example is: 3 games that lasted between 0-30 seconds and were played between 8-8:30 by player A, and the game type is 2.

I tryed to start by doing something like this , but it is not a complete query:
INSERT INTO tbl_collectData
(Time, playerId, Games_0-30_seconds)
SELECT '12 / 26 / 2007 4 : 53 : 03 PM' AS Expr1, playerId, COUNT(DATEDIFF(ss, StartDateTime, EndDateTime)) AS numberOfCalls_0_30
FROM tbl_games WHERE (Type = 2) AND (DATEDIFF(ss, StartDateTime, EndDateTime) < 31) AND (StartDateTime > '12 / 26 / 2007 4 : 53 : 03 PM') AND
(StartDateTime < '12 / 26 / 2007 5 : 23 : 03 PM')
GROUP BY playerId

I just don't know how to do it! Please help!!!!

View 2 Replies View Related

Complicated Query

Sep 6, 2007

Hi,I have two tables Trade table and Cons table. Records are inserted inboth the tables independent of each other. There are fields likeExc_Ref, Qty, Date in both the tables.I need to write a query which should give me records :1. Where there is missing Exc_Ref value in either of the table. i.e.If Trade table has a Exc_Ref value but missing in Cons table then thatrecord should be displayed. Similarly if Cons has a Exc_Ref valuewhich is not found in Trade table then that too should be displayed.2. In case where both the tables have matching Exc_Ref data then itshould display the record only when the remaining column does notmatch like Qty or Date.Please help me to resolve this complicated query.ThanksNick

View 2 Replies View Related

Complicated Query

Sep 18, 2006

Hi Guys

I Have not been able to solve this problem from quiete a while now.

I am using sql server 2005.


I have got a table which contains these columns - start date, end date and volumes
if the month in the start date is same as that of end date, the volume remains same, else if the months in the two dates are different, then i have to distribute the volume in such a way that some part will go in the first month and the rest in the other month.. i have to somehow calculate (or prorate) the volume according to the no of days in each month


I have to perform a query on this table so that I can group the volumes for different months and different years.

Here is the sample data...









Service Start
Service End
FMIS Code
No of Units
Year
Month
Volumes

01-Oct-00
15-Aug-01
6440
32
?
?
?

01-Oct-00
30-Sep-02
6441
40
?
?
?

01-Oct-02
22-May-03
6440
78
?
?
?

01-Oct-02
23-May-03
6990
87
?
?
?

06-Mar-03
31-Jul-03
6997
102
?
?
?

07-Mar-03
31-Jul-03
6744
3
?
?
?

01-May-03
31-May-03
6440
789
?
?
?

23-Jun-03
31-Aug-03
6447
1000
?
?
?

29-Jun-03
30-Jun-03
6440
981
?
?
?

30-Jun-03
31-Jul-03
6000
50
?
?
?

01-Jul-03
08-Jul-03
6002
54
?
?
?

01-Jul-03
13-Jul-03
6000
562
?
?
?



I have to calculate the columns coloured in blue..

Please help guys!



Thanks

Mita

View 2 Replies View Related

Complicated Query

Mar 2, 2008



I am trying to use ssis (sql query or .net-script task)
to transfer data from one table to another.
I have difficulties to make the query:

i have one table tbl_games which fields are :
type ,startDateTime, EndDateTime, playerId.
I need to check every 1/2 hour according to the startDateTime,
How many times a person is playing and to show it in a new table
tbl_collectData like this:
Time playerId Games_0-30_seconds Games_30-50_seconds

8-8:30 A 3 5
8:30-9 B 2 10
9-:30 C 20 7

The length of the game is measured by the StartDateTime -EndDateTime,
and only games type # 2 is being collected.
The number 3 in the example is: 3 games that lasted between 0-30 seconds and were played between 8-8:30 by player A, and the game type is 2.

I tryed to start by doing something like this , but it is not a complete query:
INSERT INTO tbl_collectData
(Time, playerId, Games_0-30_seconds)
SELECT '12 / 26 / 2007 4 : 53 : 03 PM' AS Expr1, playerId, COUNT(DATEDIFF(ss, StartDateTime, EndDateTime)) AS Games_0-30_seconds
FROM tbl_games WHERE (Type = 2) AND (DATEDIFF(ss, StartDateTime, EndDateTime) < 31) AND (StartDateTime > '12 / 26 / 2007 4 : 53 : 03 PM') AND
(StartDateTime < '12 / 26 / 2007 5 : 23 : 03 PM')
GROUP BY playerId

I just don't know how to do it! Please help!!!!

View 20 Replies View Related

Including MTD And YTD Figure With A Daily Figure

Feb 4, 2008

Hello,
I have a query that returns a daily revenue figure. The query is as follows:

SELECT top 1000
ds.AcctCode,
ds.TxnDate,
SUM(isnull(ds.FuelFee,0)) + SUM(isnull(ds.CashFee,0)) + SUM(isnull(ds.ScFee,0)) AS TotalDailyRevenue,
--"MTD" = ?,
--"YDT" = ?,
ps.TC,
CASE
WHEN ps.Proj = 100 THEN 'New Account'
WHEN ps.Proj = 200 THEN 'Current Account'
END AS ProjStatus,
ps.FSR,
ps.SubmitRep1

FROM
TxnRptg.dbo.tbl_DailySummary ds
INNER JOIN SalesData.dbo.tbl_CYProcessedSales ps
ON ds.AcctCode = ps.Acct

WHERE
MONTH(ds.TxnDate) = 1
AND
Proj IN (100,200)
AND TC = 'HV'

GROUP BY
ds.AcctCode, ds.TxnDate, ps.TC, ps.Proj, ps.FSR, ps.SubmitRep1

ORDER BY
ds.AcctCode, ds.TxnDate

--*********************************

TxnDate represents a single day of the month. How can I include MTD so that the dates for the revenue total are from DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) (beginning of current month) to TxnDate, and YTD so that the revenue totals are from DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) (beginning of the current year) to TxnDate?


Thank you for your help!


cdun2

View 5 Replies View Related

Baffled! Can't Figure Out How To Do This Query. Is It Even Possible?

Jan 13, 2006

I have an "Issues" table for my technicians. An issue can be on "hold"or "assigned".I want to get a count for each tech with a column showing number ofissues on hold and a column for number of issues assigned. It wouldlook like this --Tech Num_Assigned Num_On_HoldFred 3 10Carol 6 7I can get each column separately, but I want both in the same answertable!Is that too much to ask??? :)

View 2 Replies View Related

Simple Query, But Can't Figure It Out

Jul 20, 2005

I'm sure this is simple -- I'm just spacing it today. Assume the following:freq fruit---- ----10 apple5 apple7 banana6 pear3 pear2 orange8 orange13 kiwiHow do I find the highest [freq] for each [fruit] all at the same time, e.g.:10 apple7 banana6 pear8 orange13 kiwiThanks in advance.Mark D.

View 3 Replies View Related

Bit Of A Complicated SQL Query To Try And Write...

Feb 12, 2008

I'll start by giving the basic idea of the data structure I'm looking at in the database (pardon my MS Paint skills!):

And this all starts with a root plan. So (taking projects out of the picture for the minute), it could be a structure going any number of levels down like so: plan -> goal -> strategy -> plan -> goal -> strategy -> plan -> goal -> strategy, etc.And not forgetting, that a strategy can also have any number of projects, and all these relationships are one to many, so it ends up being like a large tree structure.
What I am trying to accomplish is user security related, in that I need to enforce rules set to say whether a single user is allowed to view a project. You can define the rules at any level in the structure above. So if for instance, a user is given a rule that they can access anything from a goal, they can see any projects that exist in any strategies underneath that goal in the tree structure. I hope this is making sense so far... The rules can also just be defined at a specific project level.
These rules (at the moment, I'm more than happy to change if this is a silly way of doing it) are set in a table that has the columns:user_id intplan_id intgoal_id intstrategy_id intproject_id intallow bitEvery row will have a user_id value, and one of either a plan_id, goal_id, strategy_id or project id (which I thought would be a simple way to pull out what kind of rule if needed), and the allow column just defines if it's an allow or deny rule (a specific deny rule on any object lower in the tree structure will override any cascaded allow rule).
The way my application needs to grab this information, is to simply have some way of returning a list project_id values for which the current user is allowed to access. I'm basically stumped. The closest I have gotten (which still didn't quite work) was going to end up using quite a large number of cursors... Which is bad. It can be inefficient to an extent, as once these values are gathered once, I can store them in a Session variable, so it's not grabbing them every time the user tries to load a project.
Thanks for any help!

View 4 Replies View Related

Complicated Cross-Tab Query

Feb 15, 2006

I have the following table and data:tblDepartments: (each department can only have a maximum of 3 sections attached to it)Columns: DepartmentName , SectionName Row1: dep1, sec1.0Row2: dep1, sec1.1Row3: dep1, sec1.2Row 4: dep2, sec2.0Row 5: dep3, sec3.0Row 6: dep3, sec3.1I need to derive the following table from tblDepartments :Columns: DepartmentName, SectionName1, SectionName2,  SectionName3Row1: dep1, sec1.0, sec1.1, sec1.2Row2: dep2, sec2.0, '', ''Row3: dep3, sec3.0, sec3.1, ''Any ideas?

View 3 Replies View Related

Complicated Query - SQL Gurus Help Please

Mar 20, 2008

Hi,
I am positive some SQL Gurus can help me with this complicated query. I am not sure if it is possible with a single query or needs multiple queries.

I have 3 objects. First, PaintOrder; Second, Combination; and Third, Material. Each Paint Order can have multiple Combinations and each Combination can have multiple (from 0 to 5) Materials. All the data is stored in single table called paintMatCom.

Here is the sample Data

PaintOrderId CombId MaterialId
1000 1 1
1000 1 2
1000 2 3
2000 1 1
2000 2 3
2000 2 4
3000 1 1
3000 1 2
3000 2 3
3000 3 4
3000 3 5

I have a Search Screen where user can select multiple Materials (upto 5) to search for the appropriate PaintOrders. Also, use has the option to select AND/OR between materials. Please look at the attached image for clear understanding.

Some of the sample searches are as follows (Combination IDs are not needed in the Output; just PaintOrder IDs).
1. Find PaintOrders with MaterialIDs 1 AND 2 OR 4
2. Find PaintOrders with MaterialIDs 2 OR 3 OR 4
3. Find PaintOrders with MaterialIDs 3 AND 4 OR 5 OR 1

Hope you got the idea. I think it would require some Joins and GROUP BY which I am not expert at. I would appreciate any help.

[IMG]C:Documents and SettingsOwnerDesktopmaterials.JPG[/IMG]

Thanks
vmrao

View 13 Replies View Related

Page 2 - HELP With SQL Query - (complicated)

Oct 10, 2006

You can display both by referring to their position in the recordset or by aliasing them in the query and referring to the alias in your code.
Note that in order to put Products.Quantity or ProductDetails.Quantity in just one column you'll have to add some logic in the query, using a coalesce, like:

sql Code:






Original
- sql Code




SELECT
Products.ProductID, Products.ProductName, Products.ProductPict,
COALESCE(Products.Quantity, ProductDetails.Quantity, 0) Quantity,
ProductDetails.ProductDetailID, ProductDetails.P_Size, ProductDetails.P_Color
FROM
Products
LEFT OUTER JOIN
ProductDetails
ON Products.ProductID = ProductDetails.ProductID
WHERE
Products.Quantity <= "& +rsResults__var1 & "
OR
ProductDetails.Quantity <= "& +rsResults__var1 & "
Order by Products.ProductID asc;






SELECT Products.ProductID, Products.ProductName, Products.ProductPict, COALESCE(Products.Quantity, ProductDetails.Quantity, 0) Quantity,ProductDetails.ProductDetailID, ProductDetails.P_Size, ProductDetails.P_ColorFROM Products LEFT OUTER JOIN ProductDetails ON Products.ProductID = ProductDetails.ProductID WHERE Products.Quantity <= "& +rsResults__var1 & " OR  ProductDetails.Quantity <= "& +rsResults__var1 & " ORDER BY Products.ProductID ASC;

Untested, beware of syntax errors!
In this case you'll have just one Quantity colum and you won't have to change anything in your asp code.

View 1 Replies View Related

SQL Server Query (complicated)

Jul 20, 2005

Folks,I have the following data in a table:4 NULL NULL2 abc NULL2 aaa NULL4 xyz NULL4 xyz pqr4 pyz xqrI want to get only one record for each record number. that is, theresult set should be like this:4 NULL NULL2 abc NULLPlease suggest how the query should be built. Thanks for the help.Murali

View 3 Replies View Related

Complicated Query In Ssis

Mar 2, 2008



I am trying to use ssis (sql query or .net-script task)
to transfer data from one table to another.
I have difficulties to make the query:

i have one table tbl_games which fields are :
type ,startDateTime, EndDateTime, playerId.
I need to check every 1/2 hour according to the startDateTime,
How many times a person is playing and to show it in a new table
tbl_collectData like this:
Time playerId Games_0-30_seconds Games_30-50_seconds

8-8:30 A 3 5
8:30-9 B 2 10
9-:30 C 20 7

The length of the game is measured by the StartDateTime -EndDateTime,
and only games type # 2 is being collected.
The number 3 in the example is: 3 games that lasted between 0-30 seconds and were played between 8-8:30 by player A, and the game type is 2.

I tryed to start by doing something like this , but it is not a complete query:
INSERT INTO tbl_collectData
(Time, playerId, Games_0-30_seconds)
SELECT '12 / 26 / 2007 4 : 53 : 03 PM' AS Expr1, playerId, COUNT(DATEDIFF(ss, StartDateTime, EndDateTime)) AS Games_0-30_seconds
FROM tbl_games WHERE (Type = 2) AND (DATEDIFF(ss, StartDateTime, EndDateTime) < 31) AND (StartDateTime > '12 / 26 / 2007 4 : 53 : 03 PM') AND
(StartDateTime < '12 / 26 / 2007 5 : 23 : 03 PM')
GROUP BY playerId

I just don't know how to do it! other ways? ideas? Please help!!!!

View 6 Replies View Related

Complicated Sql Condition Query

Sep 12, 2007

Hi,
hope someone can help or suggest something to help me with the issue.

I have a list of projects. this list contains all master (parent) and all subprojects(child). when I click on a project I want to be able to retreive information about that project and it's subprojects. here is my delema. I want my sql query to check if project is master or sub. if master then get all data for this project and its subprojects but if it's sub then get data only for that sub. below is a sample data that I hope it clear things up

parent_ID child_id Type projname
-----------------------------------------------
100 100 P parent_X_proj
100 25 C child_X_proj
100 29 C child_X_proj2
200 200 P parent_Z
300 300 P parent_Y
etc................

this is how my table is constructed. my application passes child_id and what I want is if someone clicks on parent_X_proj I want to be able to retreive the three projects (100,25,29) but if someone clicks on child project (29) then I want only that project.
so I want my query to look for the type and if my type is P (parent) then get all project where parent_id = 100(for example) but if type= C then get child_id = 29.

I know it could be done in stored procedure buy my application cannon executre SP but only sql statements.

Thank you for any help

View 3 Replies View Related

Stuck - Cant Figure Out A Query For This Situation

Jan 3, 2006

I have run into a problem, I have 2 fields in my database, both keyfields:Table 1=====Field X <key>Field Y <key>In field X, there are say about 3 records for each unique Field Y. Ilet my users query the data base like follows:Enter the Codes you want: 1000 and 3000 and 8500So I want to pick up records where there will be the above values forAll Y values. i.e 1000/AAA, 3000/AAA, and 8500 for AAA - if there iseven ONE of the X values not matching a record without a matching Xvalue, leave it out.i.e:X=1000,Y=AAAX=3000,Y=AAAX=8500,Y=AAAX=1000,Y=BBBX=3000,Y=BBBX=8500,Y=BBBX=1000,Y=CCCX=3000,Y=CCCX=9999,Y=CCCWhen the query runs, I want to see the following records:X=1000,Y=AAAX=3000,Y=AAAX=8500,Y=AAAX=1000,Y=BBBX=3000,Y=BBBX=8500,Y=BBBBUT NOT:X=1000,Y=CCCX=3000,Y=CCCX=9999,Y=CCCbecause one of the X values was not matched (the last X value =9999 andnot one of the requirements of the search)So I guess I want something like this:SELECT X,Y from TABLE1 WHERE ALL Y VALUES HAVE ALL OF THESE X VALUES(X=1000,X=3000,X=8500) IF ANY X VALUES ARE MISSING SKIP RECORD^^ Hope the above makes sense... but I am really stuck. The only otherway I think I could do it is, copy all records that match all 3 Xvalues into a temp table, and weed out any that are missing any one ofthe X values after they are copied but, I am running this on MYSQL 5.0Clustered, and there is not enough room in memory for it probably...and query time has to remain under a second.Anyhelp would be appreciated...

View 2 Replies View Related

Complicated Query - Select Based On Value

Jul 23, 2005

SQL2K on W2KserverI need some help revamping a rather complicated query. I've given thetable and existing query information below. (FYI, changing thedatabase structure is right out.)The current query lists addresses with two particular types('MN30D843J2', 'SC93JDL39D'). I need to change this to (1) check eachcontact for address type 'AM39DK3KD9' and then (2) if the contact hastype 'AM39DK3KD9' select types ('AM39DK3KD9', 'ASKD943KDI') OR if thecontact does not have that type then select types ('MN30D843J2','SC93JDL39D'). (Context - the current query selects two standardaddress types "Main" and "Secondary"; we've added new data and now havetypes "Alternate Main" and "Alternate Secondary". If the Contact hasAlternate addresses, I need to select those; if not, I need to selectthe standard addresses. There are other address types in use, so Imust specify which types to select.)Can anyone point me in the right direction?Thanks very much! jamilehCREATE TABLE [CONTACTS] ([CONTACT_X] [char] (10),[LONGNAME] [char] (75),[ACTIVE] [bit])CREATE TABLE [CONTACTADDRESSES] ([CONTACT_X] [char] (10),[ADDRESS_X] [char] (10),[ADDRESSTYPE_REFX] [char] (10),[ACTIVE] [bit])CREATE TABLE [ADDRESSES] ([ADDRESS_X] [char] (10),[ADDRESSLINE1] [char] (60),[ADDRESSLINE2] [char] (60),[CITY] [char] (20),[STATE] [char] (2),[ZIPCODE] [char] (11),[PHONE] [char] (10))CREATE TABLE [REFERENCETABLE] ([REFERENCETABLE_X] [char] (10),[ADDRESS_X] [char] (10),[DESCRIPTION] [char] (60))CREATE TABLE [MASTERTABLE] ([CONTACT_X] [char] (10),[RECORDTYPE] [char] (1),[ACTIVE] [bit])CREATE VIEW vw_CONTACTInfo_ListLocASSELECT CONTACTS.CONTACT_X, CONTACTS.LONGNAME,CONTACTADDRESSES.ADDRESSTYPE_REFX,Type_REFERENCETABLE.DESCRIPTION AS Type_DESCRIPTION,CONTACTADDRESSES.ADDRESS_X, ADDRESSES.ADDRESSLINE1,ADDRESSES.ADDRESSLINE2, ADDRESSES.CITY, ADDRESSES.STATE,ADDRESSES.ZIPCODE, ADDRESSES.PHONEFROM CONTACTS INNER JOIN CONTACTADDRESSES ONCONTACTS.CONTACT_X = CONTACTADDRESSES.CONTACT_X INNER JOINADDRESSES ON CONTACTADDRESSES.ADDRESS_X =ADDRESSES.ADDRESS_XINNER JOIN REFERENCETABLE Type_REFERENCETABLE ONCONTACTADDRESSES.ADDRESSTYPE_REFX =Type_REFERENCETABLE.REFERENCETABLE_XWHERE (CONTACTS.ACTIVE = 1) AND (CONTACTADDRESSES.ADDRESSTYPE_REFXIN('MN30D843J2', 'SC93JDL39D') AND (CONTACTADDRESSES.ACTIVE =1)) AND(CONTACTS.CONTACT_X IN(SELECT CONTACT_X FROM MASTERTABLE WHEREACTIVE = 1 AND RECORDTYPE = 'E'))

View 10 Replies View Related

Query Table For Cheapest Items (but A Little More Complicated Than That)

Oct 18, 2006

I'm not sure if this is even possible but can i pull out rows from two tables (that have a one-to-many relationship) but only if they satisfy a few conditions.


tblWine tblSources
ID Name ID WineID Source Price Status
----------------- -----------------------------------------
1 Le Dome 1 1 Smith 100.00 IB
2 Teyssier 2 1 Jones 110.00 IB
3 Muscat 3 1 Hill 100.00 DP
4 2 Smith 135.00 DP
5 2 Hill 125.00 DP


I only want to pull out row that contain the cheapest wine for their status. So the result would look something like this.


tblWineSources
WineID Name SourceID Source Price Status
-------------------------------------------------------------
1 Le Dome 1 Smith 110.00 IB
1 Le Dome 3 Hill 100.00 DP
2 Teyssier 5 Hill 125.00 DP

View 9 Replies View Related

Update SubQuery(two Tables), Pls Advice Wats Wrong With The Query. 1 Hole Day I Spent Still Cant Figure

Oct 27, 2006

Table A, Table B. need to update table A balance field from table b sum of amount

UPDATE CUSTOMERS SET BALANCE=(SELECT SUM(AMOUNT) FROM PAYMENT,CUSTOMERS

WHERE CUSTOMERS.ID=PAYMENT.ID GROUP BY PAYMENT.ID)





Msg 512, Level 16, State 1, Line 25

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

The statement has been terminated.

View 4 Replies View Related

HELP! Can't Figure This One Out!

Jan 19, 2004

I'm in desperate need of help. I'm setting up an intranet portal using DNN. I added an event calendar module, but whenever I try to add events to it, the system rejects it with a nasty Sql exception saying the conversion from char to datetime produced an out of bounds result.

The string the table uses to convert to datetime is (I have not modified it, the module is exactly as it came when i downloaded)

(convert(varchar,getdate(),101))

The whole stack trace for the error is:

Stack Trace:


[SqlException: La conversión del tipo de datos char a datetime produjo un valor datetime fuera de intervalo.]
System.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) +642
System.Data.SqlClient.SqlCommand.ExecuteReader() +11
DotNetNuke.AVCalendarDB.Save() +1067
DotNetNuke.AVCalendarEdit.updateButton_Click(Objec t sender, EventArgs e) +3367
System.Web.UI.WebControls.LinkButton.OnClick(Event Args e) +108
System.Web.UI.WebControls.LinkButton.System.Web.UI .IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
System.Web.UI.Page.RaisePostBackEvent(IPostBackEve ntHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCol lection postData) +138
System.Web.UI.Page.ProcessRequestMain() +1263

At first I thought it could be a language issue (DNN and the module are in english and my system runs XP Pro in Spanish) but I discarded it since it didn't work when I installed XP Pro in english

Any ideas?? I would really appreciate your help
Best regards from Chile
Javier L.

View 5 Replies View Related

Please Help Me Figure This One Out.

May 1, 2008



Hi, I am somewhat new to t-sql and what I do know is from trial & error and help from this forum. What I need to do is add a column of counts for id numbers that are not unique.

This is my code:

ALTER procedure [dbo].[rptMgmtRpt]


@RptMonthBegin datetime,

@RptMonthEnd datetime


as




SELECT Summons.ID, Convert(varchar, Venire.VenireDateTime,101)as VenireDateTime, Venire.VenireStatusID, Summons.SummonsStatusID, Summons.ExcusalCodeID,

Venire.ID AS VenireID, { fn WEEK(Venire.VenireDateTime) } AS wkNum, { fn DAYOFWEEK(Venire.VenireDateTime) } AS wkDay, Venire.JuryTypeID,

Venire.VenireLocationID, summons.compensationTypeID

,{fn IFNULL(AccountingTransactionRequest.PaymentAmount,0)} AS payAmt

,Convert(varchar,AccountingTransactionRequest.ServiceDate,101) as AcctServDate

,{fn count(summons.id)}

FROM Venire INNER JOIN

Summons ON Venire.ID = Summons.VenireID

LEFT outer JOIN

AccountingTransactionRequest ON Summons.ID = AccountingTransactionRequest.SummonsID

Where Venire.VenireLocationID <> 16 and (VenireDateTime BETWEEN @RptMonthBegin AND @RptMonthEnd)

ORDER BY wknum, wkday , Summons.ID

This is a sample of what I get for results:

640404 11/5/2007 128 144 2866 45 2 8 0 11/5/2007
640888 11/5/2007 128 32 2866 45 2 8 0 11/5/2007
640979 11/5/2007 32 2 2866 45 2 112 15 11/5/2007
640979 11/5/2007 32 2 2866 45 2 112 15 11/6/2007
640979 11/5/2007 32 2 2866 45 2 112 15 11/7/2007
641533 11/5/2007 128 32 2866 45 2 8 0 11/5/2007
641762 11/5/2007 128 144 2866 45 2 8 0 11/5/2007
641851 11/5/2007 1024 2 2866 45 2 8 0 11/5/2007




What I need are results that look like this:

640404 11/5/2007 128 144 2866 45 2 8 0 11/5/2007 1
640888 11/5/2007 128 32 2866 45 2 8 0 11/5/2007 1
640979 11/5/2007 32 2 2866 45 2 112 15 11/5/2007 1
640979 11/5/2007 32 2 2866 45 2 112 15 11/6/2007 2
640979 11/5/2007 32 2 2866 45 2 112 15 11/7/2007 3
641533 11/5/2007 128 32 2866 45 2 8 0 11/5/2007 1
641762 11/5/2007 128 144 2866 45 2 8 0 11/5/2007 1
641851 11/5/2007 1024 2 2866 45 2 8 0 11/5/2007 1


In the first column, 640979 appears three times.
How do I get that count in the last column of my results ?

Thanks so much for your help!!!

View 4 Replies View Related

Complicated SQL Help

Apr 27, 2007

Perhaps you can help with something that I consider kind of omplicated? (I am SO hoping that I am NOT going to have to do this manually!!!)

I have a table (about 3000 rows) where two of the columns have Domain User information.

COL1 has DOMAINUsername and COL2 has (or SHOULD have) DOMAIN@username.com

I need to look at each field in COL1 and if exists DOMAINusername, I need to populate COL2 with username@DOMAIN.com

Is this possible???

View 8 Replies View Related

It's Complicated

Aug 27, 2007

The low down:
Local Web Server on Windows 2003
Local SQL Server on Windows 2003
Hosting dynamic website tied to inhouse Access Application

Ok, basically, how it is set up, people can login to our website and enter data (insert record), on our end, we have an Access application where we can play with the data that was entered via the website. Currently, we do not have either server set up as a Mail server.

What we need to be able to do:
When a customer enters data on our website, their supervisor, and about 2-3 other people related to the transaction need to be emailed to be notified that an order was submitted. So how do I code that? On the page with the Insert Record? OR after Insert Record redirect them to another page that sends the mail out?

Which server do I enable the mail?

I was reading about SQL Mail etc, which would be good since we do mass emails to clients weekly, but I have no idea how to set that up and I look crossed eyed at any tutorial.

Do I want to set up theSQL server to also be a Mail Server that way we can use the SQL database to email as well as data entered from the website? But then again, the website points to the Web Server which pulls data off the SQL server (so unless the Web Server is a mail server, nothing will be sent, am I right?)

*sigh*

I know very little about SQL and I'm being asked to impliment this and I am 100% confused. I'm a graphics artist not a programmer! LOL

Thanks in advance to anyone who can/will help me.

View 6 Replies View Related

Who's Smart Enough To Figure This Out?

Mar 9, 2004

Hello All,

I've been trying to get a range of values out of my SQL Server 2000 db without sucess. The field in question has the data type of char(8) and looks like this:

House_numbr_pub (leading spaces in front of each value)
140A
140
141
142
143
144
145
146
147
148
149
150
151
.
.
.
14500
.
.
.

Does anyone know how write a sql statement that will return 140-150, but excluding the ' 14500' and 100-1000. I tried the following where clause to return a range between 100-1000.

WHERE (cook.STREET_PUB LIKE 'lincoln%') AND (LEN(LTRIM(cook.HOUSE_NUMBR_PUB)) BETWEEN 3 AND 4) AND (
(LTRIM(cook.HOUSE_NUMBR_PUB) >= '100') and (LTRIM(cook.HOUSE_NUMBR_PUB) <= '1000') )

This where clause only return two records (100 and 1000). I want it to return 100-1000.

I also tried the following where clause:

WHERE LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]'
OR
LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]'

However, building this on the fly with .net will take some effort if someone is trying to search range 1-10000000.


Please Help,

James

View 3 Replies View Related

Figure Is Rounding Up

Mar 13, 2007

I have the following sp which is appending records into my table. However the values appended are being round up eg

SC_PrimaryPupilPrice is 1.5

but when it is inserted into the sql table it is 2

The field in the sql table is numeric.

CREATE PROCEDURE spSM_AddWeeksandMealPrices

@dteWeekEnding datetime

as

INSERT INTO tblSM_Meals
(ML_Id,
ML_WeekEnding,
ML_SchoolNumber,
ML_PupilMealPrice,
ML_AdultMealPrice,
ML_SpillagesMealPrice,
ML_AdultRechargeMealPrice,
ML_ReservedMealPrice)

select convert(varchar,@dteWeekEnding ,103) + '*' + cast(SC_SchoolNumber as varchar(10)) , convert(datetime,@dteWeekEnding ,106),
SC_SchoolNumber,
SC_PrimaryPupilPrice,
SC_PrimaryAdultPrice,
SC_PrimaryPupilPrice,
SC_PrimaryAdultPrice,
SC_PrimaryAdultPrice
from tblSM_Schools
GO

View 4 Replies View Related

Can't Figure Out This Error!

Jun 8, 2007

Here is my code below. When I attempt to run the data flow task that calls this script, I get this error:



"Index was outside the bounds of the array."



I honestly do not know what the problem is here. There are definitely 6 columns in the file. In fact, even if comment out everything except the first line (myCol1), I still get the "Index was outside the bounds of the array." error.



Any ideas??? Need help.



Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

Dim rowValues As String()

rowValues = Row.Line.Split(columnDelimiter) 'parse row by comma

If Row.Line Like "*OPENING BALANCE*" Then

Row.AccountNumber = Nothing 'set to null for conditional split

Row.OpeningBalance = CDec(rowValues(3)) 'get the 4th value



ElseIf Row.Line Like "*CLOSING BALANCE*" Then

Row.AccountNumber = Nothing 'set to null for conditional split

Row.ClosingBalance = CDec(rowValues(2)) 'get the 3rd value



Else

Row.myCol1 = CStr(rowValues(0)).Replace("""", String.Empty)

Row.myCol2 = CStr(rowValues(1)).Replace("""", String.Empty)

Row.myCol3 = CStr(rowValues(2)).Replace("""", String.Empty)

Row.myCol4 = CStr(rowValues(3)).Replace("""", String.Empty)

Row.myCol5 = CStr(rowValues(4)).Replace("""", String.Empty)

Row.myCol6 = CDec(rowValues(5))



End If

End Sub

View 10 Replies View Related

I Think I Have Made Something Way To Complicated...

Dec 27, 2007

All I am trying to do is use a SqlDataSource, Read that Data from the Session Variable, Do a RowFilter off the Data and then return the Data (Currently a DataSet but doesnt matter).  But Since I dont use SqlDataSource that much not sure all the code I have is neccasry:
 protected DataSet GetSearchAppData(string strWhere)
{
DataSet dsSearchAppTable = new DataSet("SearchAppTable");
SqlDataSource ss = new SqlDataSource();
DataView dv = new DataView();
DataSourceSelectArguments dsArgg = new DataSourceSelectArguments();

dsArgg = DataSourceSelectArguments.Empty;
ss = ((SqlDataSource)Session["SearchAppTable"]);
dv = (DataView)ss.Select(dsArgg);
dv.RowFilter = strWhere;
dsSearchAppTable.Tables.Add(dv.Table.Clone());

return dsSearchAppTable;
}
 And to mention it, dsSearchAppTable returns a Table with 0 rows.  Not sure what the heck I'm doing wrong.
 
J

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved