Stumped...cartesian Product Brain Teaser

May 10, 2007

I have a table with 2 columns as follows:

COORD LEVEL===== =====1 11 22 23 21 32 33 34 35 3


I need to produce a result that has 1 column that is the concatenation of each COORD separated by a '.' by increasing LEVEL


EX: The result should look like this
1.1.1
1.2.1
1.2.2
1.2.3
1.2.4
1.2.5
1.3.1
1.3.2
1.3.3
1.3.4
1.3.5

Please note that the answer must be flexible enough to handle any number of levels and coordinates (although levels will most likely be less than 5 and coordinates less than 100)

Can this be done in a simple SQL statement?

ANY help is very much appreciated.

View 7 Replies


ADVERTISEMENT

Small Sql Statement Brain Teaser

Nov 14, 2003

I’ve just remembered a very small yet challenging SQL statement brain teaser a friend of mine asked me long ago.

Though as simple as it might seem, I still couldn’t figure out how to solve it until this day. I just thought that some of you guys might have an answer to it.

Here is the question:

You have a table named “table1� that has only 2 fields: “name� and “phone�.

This table is populated with the following sample data

NamePhone
---------------------
John111111
Tom222222
Jack333333
John444444
Smith555555
----------------------
5 records


To get all the distinct names in this table, you would write the sql statement:
Select distinct name from table1

And the result would be:

Name
-------
John
Tom
Jack
Smith
-------
4 records

The question is: can you write a sql statement that can return all the distinct names along with their phone numbers.

E.g.

NamePhone
---------------------
John111111
Tom222222
Jack333333
Smith555555
----------------------
4 Records

View 3 Replies View Related

Brain Teaser - Stagger The Order Of The Results

Sep 5, 2005

This one has been stumping me for several days. I can run a query thatreturns several different items from several different manufacturers,each with a ranking score. Each manufacturer can have any number ofitems:Item_Name Manufacturer rankItem 1 Manu_A 82Item 2 Manu_A 65Item 3 Manu_A 41Item 4 Manu_B 32Item 5 Manu_C 21Item 6 Manu_B 19However, I would like the records to be ordered so that the highestranking item is shown first, then the next highest item from adifferent manufacturer is shown second, then the next highest item froma third manufacturer is show, etc.:Item 1 Manu_A 82Item 4 Manu_B 32Item 5 Manu_C 21Item 2 Manu_A 65Item 6 Manu_B 19Item 3 Manu_A 41Does anyone have any thoughts on how to order the results in thisfashion?thanks,Matt Weiner

View 2 Replies View Related

Query Brain Teaser - Revenue Projections

Mar 8, 2006

I have a requirement (motivated by a SOX thing) that is just giving mefits. I know it should be easy and I'm probably overthinking it, but Ijust can seem to find the best way to get where I need to go.I have some payment projection data derived from a huge procedure thatI'm dumping into a temp table that looks like looks this:Key Pd Start End AnnualAmt MonthAmt DailyAmt6789 1 2005-06-01 2010-05-31 49,500.00 4,125.00 135.6164386789 2 2010-06-01 2015-05-31 54,450.00 4,537.50 149.1780826789 3 2015-06-01 2020-05-31 59,895.00 4,991.25 164.0958906789 4 2020-06-01 2024-05-31 65,884.50 5,490.38 180.505479(there are actually 6 levels of keys, but you get the idea)I need it to get into a reporting table looking like this:Key Rev Year ProjectedAmt6789 2005 29,021.926789 2006 49,500.006789 2007 49,500.006789 2008 49,500.006789 2009 49,500.006789 2010 20,478.086789 2010 31,924.116789 2011 54,450.006789 2012 54,450.006789 2013 54,450.006789 2014 54,450.006789 2015 22,525.886789 2015 35,117.406789 2016 59,895.006789 2017 59,895.006789 2018 59,895.006789 2019 59,895.006789 2020 24.779.10etc...I'm having a problem wrapping my head around how to get the rows in themiddle of each period.The other, probably minor and statistically insignificant, issue isproration on a leap year. If a proration occurs on a leap year and Ihave to calculate the proration based on a DATEDIFF and an Annual orMonthly Amount, I'm going to be a day over.Anybody have any tricks or ideas???Thanks so much for your help!Jody

View 3 Replies View Related

Eliminating A Cartesian Product

Jul 29, 2013

I have a SQL statement with two left outer joins which connects 3 tables. Vendors, Tracking & Activity. For whatever reason, even though each is a one-to-many relationship, I am able to join 2 tables (from Vendors to Tracking) without an issue. when I then join Activity, I get a Cartesian product.I suspected that 'DISTINCT'.

SELECT DISTINCT CASE
WHEN `vendor`.`companyname` IS NULL then 'No Company Assigned'
ELSE `vendor`.`companyname`
END AS companyNameSQL, `tracking`.`pkgTracking`, CASE

[code]....

View 4 Replies View Related

Left Outer Join Produces Cartesian Product

Feb 9, 2006

Tables have 100K rows. Inner join produces 99k. The outer join should be 100K. It is 1000 times larger.

If I do a SELECT DISTINCT, the right # rows are returned (100K)

What gives?

SELECT tblEarth.key1, tblEarth.key2a, tblEarth.key2b
FROM ((tblEarth INNER JOIN tblMoon ON Mid(tblEarth.key1,1,6) = tblMoon.key1) LEFT OUTER JOIN
tblVenus ON (tblEarth.key2b = tblVenus.key2b)
AND (tblEarth.key2a = tblVenus.key2a)) LEFT OUTER JOIN
tblMars ON tblEarth.key2a = tblMars.key2a;

Laurence

View 1 Replies View Related

SQL Teaser

May 31, 1999

I have a table (POS) with 3 columns and 4 rows:

KEY COLUMNA COLUMNB
1 1 dog
2 1 cat
3 2 dog
4 2 cat

What is the SQL to return
COLUMNA COLUMNB
1 dog
2 dog
?

Thanks

View 2 Replies View Related

Transact SQL :: Get All Children Of A Product With Product ID In Result Set

Aug 30, 2015

I am using the code below to get all the children of a particular product and it is working fine. How to get the particular product's id in the select statement. for example, i need to show 891 in a separate column for all the records returned by the query below.

DECLARE @Hierarchy TABLE (Product_Id INT, Parent_Product_Id INT)
INSERT INTO @Hierarchy VALUES (123, 234)
INSERT INTO @Hierarchy VALUES (234, 456)
INSERT INTO @Hierarchy VALUES (456, 678)
INSERT INTO @Hierarchy VALUES (678, 891)
INSERT INTO @Hierarchy VALUES (891, NULL)

[Code] .....

View 3 Replies View Related

SQL Brain Fart

Oct 5, 2004

I feel like I am having a total brain fart. I am trying to use a select * where statement to get all the records from my database that match a given setup and using a URL variable:
Code:

SELECT * FROM dbo.TerraLogMain WHERE Volume = '#URL.VolumeID#'


Now I know for a fact that there are multiple records for Volume = Maps6 (for example) but I am only getting one record returned.

It also looks like the URL variable is getting passed okay:
Code:

http://localhost/GISTerraLog/VolumeDetail.cfm?VolumeID=Maps6

I also tried using a direct statement just to see if that gave up any hints:

SELECT *
FROM dbo.TerraLogMain
WHERE Volume = 'Maps6'

but I still only get one record returned.

So any clues as to what I am missing?

Thanks for any help!

Cheers,
Melissa

View 8 Replies View Related

Having A MAJOR Brain Fart Here...

Feb 18, 2007

Guys I'm sorry to be asking such a routine question...
I'm having trouble figuring out how to make this function dynamic enough to handle multiple insert statements.1 public int Add()
2
3 {
4
5 string SQL;
6
7 SQL = "INSERT INTO [BuildingInterior] (PropertyID, CeilingHeight, " +
8
9 "LoadingDocks, PassengerElevators, FreightElevators, PassengerEscalators, " +
10
11 "FireSprinklersID, SecurityCameras, SmokeDetection, FireAlarms, " +
12
13 "GasDetection, SecureAccess, HeatTypeID, AirConditioningID, " +
14
15 "AirExchange, InternetAccessID, InteriorDescription) " +
16
17 "VALUES ( @PropertyID, @CeilingHeight, " +
18
19 "@LoadingDocks, @PassengerElevators, @FreightElevators, @PassengerEscalators, " +
20
21 "@FireSprinklersID, @SecurityCameras, @SmokeDetection, @FireAlarms, " +
22
23 "@GasDetection, @SecureAccess, @HeatTypeID, @AirConditioningID, " +
24
25 "@AirExchange, @InternetAccessID, @InteriorDescription)";
26
27 PropertyDB myConnection = new PropertyDB();
28
29 SqlConnection conn = myConnection.GetOpenConnection();
30
31 SqlCommand cmd = new SqlCommand(SQL, conn);
32
33 cmd.Parameters.Add("@PropertyID", SqlDbType.Int).Value = PropertyID;
34
35 cmd.Parameters.Add("@CeilingHeight", SqlDbType.NVarChar, 50).Value = CeilingHeight;
36
37 cmd.Parameters.Add("@LoadingDocks", SqlDbType.NVarChar, 50).Value = LoadingDocks;
38
39 cmd.Parameters.Add("@PassengerElevators", SqlDbType.NVarChar, 50).Value = PassengerElevators;
40
41 cmd.Parameters.Add("@FreightElevators", SqlDbType.NVarChar, 50).Value = FreightElevators;
42
43 cmd.Parameters.Add("@PassengerEscalators", SqlDbType.NVarChar, 50).Value = PassengerEscalators;
44
45 cmd.Parameters.Add("@FireSprinklersID", SqlDbType.Int).Value = FireSprinklersID;
46
47 cmd.Parameters.Add("@SecurityCameras", SqlDbType.NVarChar, 50).Value = SecurityCameras;
48
49 cmd.Parameters.Add("@SecurityAlarms", SqlDbType.NVarChar, 50).Value = SecurityAlarms;
50
51 cmd.Parameters.Add("@SmokeDetection", SqlDbType.NVarChar, 50).Value = SmokeDetection;
52
53 cmd.Parameters.Add("@FireAlarms", SqlDbType.NVarChar, 50).Value = FireAlarms;
54
55 cmd.Parameters.Add("@GasDetection", SqlDbType.NVarChar, 50).Value = GasDetection;
56
57 cmd.Parameters.Add("@SecureAccess", SqlDbType.NVarChar, 50).Value = SecureAccess;
58
59 cmd.Parameters.Add("@HeatTypeID", SqlDbType.Int).Value = HeatTypeID;
60
61 cmd.Parameters.Add("@AirConditioningID", SqlDbType.Int).Value = AirConditioningID;
62
63 cmd.Parameters.Add("@AirExchange", SqlDbType.NVarChar, 50).Value = AirExchange;
64
65 cmd.Parameters.Add("@InternetAccessID", SqlDbType.Int).Value = InternetAccessID;
66
67 cmd.Parameters.Add("@InteriorDescription", SqlDbType.NVarChar, 50).Value = InteriorDescription;
68
69 cmd.ExecuteNonQuery();
70
71 cmd.CommandText = "SELECT @@IDENTITY";
72
73 this.BuildingInteriorID = Int32.Parse(cmd.ExecuteScalar().ToString());
74
75 conn.Close();
76
77 return this.BuildingInteriorID;
78
79 }
80

 Should I just pass an array of column names and use the AddWithValues SqlCommand method while looping through the array?
Any comments are greatly welcomed.

View 2 Replies View Related

Localization.Brain Storming.

Mar 16, 2007

 Hello,I am working on a Blog and a Documents systems.What I need is:1. Each blog can have various language versions.2. Each document can have various language versions.I have been thinking about this and I end up with two approaches:1. Use a structure where all tables depend on a localized table:BLOGS|---- BlogsLocalized|---- BlogsPosts|---- BlogsRatings|---- BlogsComments2. Use a structure where each table has a localized versionBLOGS|---- BlogsLocalized|---- BlogsPosts|---- BlogsPostsLocalized|---- BlogsComments|---- BlogsCommentsLocalized3. Create a simpler, without localization, in SQL and in my web sites have different versions for each language.The same approach is under thinking for DocumentsTables.Could someone give me some advice?I have been looking in internet but until no I couldn't find anything really useful.Thanks,Miguel

View 1 Replies View Related

Brain-Dead Newbie - SQL Question

Sep 8, 2005

Any help is sincerely appreciated:I have data in a table that represents the following:Admin Visit Type            Registration Date         Discharge Date D                                    20050301                  20050301D                                    20050301                  20050301W                                   20050301                  20050301E                                    20050301                  20050301D                                    20050301                  20050302W                                   20050301                 20050303W                                   20050301                 20050311D                                    20050301                 20050301Patient Type is always and I for the records I want but there are also Patient Types = O which I don't care about..What I would like to do is accoumlate a counter on the number of Registrations per date as well as Discharges per date.There can be thousands of registrations per day as well as thousands of discharges per day.  So lets say I want to pass a date parameter to accumulate the total registrations and discharges per day.  I have beat my head against the desk for the last two days because I believe this is a simple query but I just cannot get the results I want  - so any help is greatly appreciated.   I have written the following sql but I do not get a sum of the total registrations and discharges and EXPR3 and Expr4 always equal each other which is not the case .  For example on 20040301 I have 88 registrations and 17 discharges but I can't ever get the correct totals...I wrote the following in Query Analyzer - but it does not work and I have went around in circles and have tried so many things I am just frustrated.........Declare @Parm_Beg_Date as nvarchar(8)Set @Parm_Beg_Date = 20040313
SELECT
Patient_Visit_Result_Master.PVR_Admin_Visit_Type,Patient_Visit_Result_Master.PVR_Patient_Type, Patient_Visit_Result_Master.PVR_Registration_Date,Patient_Visit_Result_Master.PVR_Discharge_Date, Count(Distinct(Patient_Visit_Result_Master.PVR_Registration_Date)) as Expr3,Count(Distinct(Patient_Visit_Result_Master.PVR_Discharge_Date)) as Expr4
FROM         Patient_Visit_Result_Master INNER JOINPatient_Visit_Result_Master Patient_Visit_Result_Master_1 ON Patient_Visit_Result_Master.PVR_Hospital_ID = Patient_Visit_Result_Master_1.PVR_Hospital_ID  AND @Parm_Beg_Date = Cast(Patient_Visit_Result_Master_1.PVR_Registration_Date as nvarchar(8))or@Parm_Beg_Date = Cast(Patient_Visit_Result_Master_1.PVR_Discharge_Date as nvarchar(8))
WHERE     (Patient_Visit_Result_Master.PVR_Admin_Visit_Type = 'E') AND (Patient_Visit_Result_Master.PVR_Patient_Type =  'I')  AND (Cast(Patient_Visit_Result_Master.PVR_Registration_Date as nvarchar(8)) = @Parm_Beg_Date)  OR    (Patient_Visit_Result_Master.PVR_Admin_Visit_Type = 'D') AND (Patient_Visit_Result_Master.PVR_Patient_Type =  'I')  AND (Cast(Patient_Visit_Result_Master.PVR_Registration_Date as nvarchar(8)) = @Parm_Beg_Date)
 Or (Patient_Visit_Result_Master.PVR_Admin_Visit_Type = 'W') AND (Patient_Visit_Result_Master.PVR_Patient_Type =  'I') and (Cast(Patient_Visit_Result_Master.PVR_Discharge_Date as nvarchar(8)) = @Parm_Beg_Date)
 Or (Patient_Visit_Result_Master.PVR_Admin_Visit_Type = 'D') AND (Patient_Visit_Result_Master.PVR_Patient_Type =  'I') and (Cast(Patient_Visit_Result_Master.PVR_Discharge_Date as nvarchar(8)) = @Parm_Beg_Date)
GROUP BY Patient_Visit_Result_Master.PVR_Admin_Visit_Type,Patient_Visit_Result_Master.PVR_Patient_Type, Patient_Visit_Result_Master.PVR_Registration_Date,Patient_Visit_Result_Master.PVR_Discharge_Date
Order By Patient_Visit_Result_Master.PVR_Admin_Visit_TypeThanks in advance

View 10 Replies View Related

Stumped

Jul 28, 2005

Im stumped on my SQL connection string when using the "SQLGridSelectedView" module. The tables im accessing reside in the same database as DNN on the local machine. My current string is "Provider=SQLOLEDB;Server=ADVANCED02;DATABASE=XP;Trusted_Connection=TRUE"My SQL statement as a test was a simple select all ...... "SELECT * FROM atm info"The error im getting is that ASPNET is not a trusted user"System.Data.OleDb.OleDbException: Login failed for user 'ASPNET'. Reason: Not associated with a trusted SQL Server connection. at System.Data.OleDb.OleDbConnection.ProcessResults(Int32 hr) at System.Data.OleDb.OleDbConnection.InitializeProvider() at System.Data.OleDb.OleDbConnection.Open() at DNNAdditional.SQLGridSelectedView.DisplayGrid(String psSortExpr, Boolean pbExport)"/TIA

View 1 Replies View Related

New To MS SQL And Stumped

Feb 1, 2005

I am migrating from MS Access and MySql to MS SQL 2000. I guess the first step is to load MSDE on my computer. My platform is Win XP Office

I am not sure what to expect, but this sure appears to be one of the most complicated procedures I have ever encountered. So I assume that I some how got off on a tangent.

Basically I just want a simple ability to create databases on Websites and transfer the data from existing databases on another Website.

What am I doing wrong?

What am I missing here?

Here is what I have done.

I downloaded the MSDE file MSDE2000A.exe

When I executed MSDE2000A.exe that installed a files in a directory MSDERelA


When I tried to run setup.exe in the directory MSDERelA, the process was aborted with the following comment

"A strong password is required for security reasons."

Then following the instructions on "How to Chane Your SA Password" I received the following.

'osql' is not recognized as an internal or external command,
operable program or batch file.

View 3 Replies View Related

Stumped

Jan 9, 2007

This one has the expert in SQL Express stumped and he suggested I try posting here. My problem is that I am trying to load SQL Express and can not do so.






Mike Wachal - MSFT wrote:












mnn2501 wrote:







I am having a similar problem, I first used the uninstall program which failed, then went to add remove programs finding nothing, then went to windows explorer and deleted what looked to be obvious choices. I still can't get sql express to install - any idea's?

Here are the logs:

Product "{2AFFFDD7-ED85-4A90-8C52-5DA9EBDC9B8F}" versioned 9.00.1116 is not compatible with current builds of SQL Server.Expected at least version: 9.00.1399.00
The Product Name is "Microsoft SQL Server 2005 Express Edition CTP"


Message displayed to user
SQL Server 2005 Setup has detected incompatible components from beta versions of Visual Studio, .NET Framework, or SQL Server 2005. Use Add or Remove Programs to remove these components, and then run SQL Server 2005 Setup again. For detailed instructions on uninstalling SQL Server 2005, see the SQL Server 2005 Readme.



This error indicates that you have a pre-RTM CTP version of Express on your computer that you did not remove correctly. You will need to remove all pre-release software before you can install the released software. Try to remove components from Add/Remove programs first. If that fails, or if nothing is listed, manually remove the product using the product id listed in the log like this:

msiexec.exe /x {2AFFFDD7-ED85-4A90-8C52-5DA9EBDC9B8F}

Mike














Thank you for your answer, I tried doing the msiexec.exe /x {2AFFFDD7-ED85-4A90-8C52-5DA9EBDC9B8F} but came up with this pop up error message when I did and I am lost.



The setup has encountered an unexpected error in datastore. The action is RestoreSetupParams. The error is" Failed to read property "Installlds" {"MachineConfiguration","","BEAST"} from cache Unable to write property into cache. IsClustered

Unable to write property in cache:"IsClustered":
XmlRW Error: Failure loading xmlre.dll
CheckAllProcedures() returned:2

Any more ideas?












That one has me stumpt. I would suggest that you post this question into the Setup and Upgrade forum so the folks that specialize in the technology can offer suggestions.



Anyone here have any ideas for me?

Thanks

Mike D (mnn2501)

View 1 Replies View Related

Nasty Mirroring Split Brain Situation

Mar 27, 2007

Yesterday I had a nasty mirroring problem.



The principal and the mirror server are both running SQL Server 2005 64-bit Enterprise Edition. Witness is running Workgroup Edition. We are running in high availability mode (SAFETY ON).



3 nights before something strange happened and 1 database failed over (out of the six being mirrored) for some unknown reason. The other 5 didn't. We failed that one back and all seemed ok over the weekend.
We came in Monday and found that the main live OLTP database was showing as the Principal on BOTH servers (in SMO/Management Studio and also in sys.database_mirroring). This is the "split brain" scenario that the presence of the witness is supposed to prevent. Both databases were accessible with a USE statement - clearly not right.



I pondered what to do, eventually I decided to remove mirroring from this database. That was ok until suddenly a few minutes later we realised the (original) Principal was in recovery! uisers of course were kicked out/unable to connect. I tried to force recovery with RESTORE DATABASE dbname WITH RECOVERY but it complained users were connected!



I had to KILL the users then recovery proceeded and the database became available again. I forced the mirror offline to prevent accidental usage.



This is obviously a nasty situation where mirroriing - which is supposed to prevent downtime - actually caused it instead.



I intend to log a call with CSS but I wanted to warn other users if they encounter something similar - it has shaken my confidence in mirroring quite severely.

View 4 Replies View Related

Count Up Based On Unique Value -- Brain Freeze

Apr 17, 2008



Ok... I know this is something that I've seen and probably done before....

I have a value that will show up multiple times in a table. I want to order the table by that value and then count up from 1 to however many items that it shows up as.

The example below shows the results I want. Value1 and Value2 are in the table, LineNumber is what I need to generate.








Value1
Value2
LineNumber

1
Hey
1

1
Can
2

1
Someone
3

1
Help
4

1
With
5

1
This
6

2
Very
1

2
Simple
2

2
Issue
3

2
As
4

2
I
5

3
Have
1

3
A
2

3
Brain
3

3
Freeze
4



--Thanks--

View 4 Replies View Related

Stumped By SQL Challenge

Sep 19, 2005

Here is the table:CREATE TABLE [child]([pk_child_id] [int] NOT NULL ,[fk_parent_id] [int] NOT NULL ,[code] [char] (2)NOT NULL ,[dt] [datetime] NOT NULL ,[newcode] [int] NULL)There is a situation where there will be more than one record with thesame [fk_parent_id] value, but different values for the [code]field.If one of those records has a [code]= 5, but the [dt] is AFTER asimilar record where [code]= 6 or [code]= 7 (but same [fk_parent_id]value), I need to set [newcode] = 10. How can I pull this off? Again,the group of records can have different [code] values, different [dt]values, but a common [fk_parent_id].Help!

View 4 Replies View Related

This Wretched SQL Has Me Stumped!

Jul 20, 2005

SCENARIO:SQL Server 2000 Back End.The customer calls in with a problem and a QUERY is raised. The dateof creation of the record is in the fldDateQuery column.The user responds to the customer and a RESPONSE is raised. Itcontains the ID of the associated QUERY and the date of creation ofthe RESPONSE record is in the fldDateResponse column.The user wishes to know how many queries in the last month wereresponded to on the same day.CANDIDATE SQL:SELECT COUNT(*) AS NumResponsesFROM tblQueryINNER JOIN tblResponses ON tblQuery.fldQueryID =tblResponses.fldQueryIDWHERE (tblQuery.fldDateQuery < CONVERT(DATETIME,'2003-9-8 00:00:00',102))AND (tblQuery.fldDateQuery > CONVERT(DATETIME,'2003-8-8 00:00:00',102))AND (DATEDIFF(Day, tblQuery.fldDateQuery,tblResponses.fldDateResponse) <= 1)PROBLEM:If a query has more than one response raised on it within a day of thequery being logged, it counts all those responses. In other words,the SQL counts the number of matching RESPONSES, and not the number ofQUERIES.TIAEdward

View 3 Replies View Related

Stumped. Totally... (but There Must Be A Way!?)

Jul 20, 2005

Hi there...I am having a whole bunch of trouble trying to design a certain query. Ihave two tables (see a representation of them here:http://www.plankmeister.org.uk/tables.html ) one called menu_data and onecalled page_data.menu_data contains a list of defined menus (menu_group) which may be sortedaccording to the menu_group_display_order column.page_data contains a list of page definitions. Each page belongs to amenu_group. All the pages in a given group may be sorted according to thepage_display_order column. (for instance, a query to order all pages with amenu_group equal to 1 in ascending order would produce:CatsDogsFishSquirrels)What I am trying to do is to design a query that will tell me thepage_user_name of all the pages that sit at the 'top' of their menu group,but ordered by the menu_group_display_order column.So basically, it will order the data in menu_data by themenu_group_display_order colum, then comparing menu_data.menu_group topage_data.menu_group, will return the 'first' row after being ordered bypage_display_order, so that in the case of the data given, the return wouldbe:HorsesCatsBirdsRabbitsI've tried UNION, GROUP BY, TOP 1, INNER JOIN, OUTER JOIN, SLIGHTLY TO THELEFT JOIN, ONLY IF ITS A WEDNESDAY JOIN... etc etc... But I just can't getit to work! It either returns 40 rows, or one. I've spent a total of about10 hours trying to design this query, and am losing what precious littlehair I have left at an alarming rate.Hope someone can provide some insight!Plankmeister.

View 3 Replies View Related

Stumped On An INSERT

Feb 26, 2008

I'm trying to do the following:

INSERT INTO TABLENAME (VAL1, VAL2)

SELECT 'NEW YEAR'S DAY', ...

Because of the single quotation mark in YEAR'S the insert fails. I know this has got be one helluva dumb question. but I'm still learning. How is it done??

View 5 Replies View Related

I Need Help With Cleaning A Phone Number Column, Brain Freeze

Feb 26, 2002

For anyone who can help me resolve this minor data issue. I am trying to clean a phone number column so that all numbers are reflected in the same way. I have phone numbers in my column in this this format:

(123)123-1234
123-123-1234
(123) 123-1234

How can I clean this column so that the numbers are reflected in this way: 1231231234

I'm having brain freez right now. Help me please!!! Thanks in Advance

View 2 Replies View Related

Stumped - LEFT JOIN

Jan 10, 2007

Hi, I'm getting the error Syntax error (missing operator) in query expression 'dbPWork.id = dbPWorkWord.work_id LEFT JOIN words ON dbPWorkWord.word_id = words.id'." on the query below. Everything looks in place to me. Do you see anything that shouldn't work?

Query:

Code:

Code:

SELECT DISTINCT dbPWork.id, description_e as description, w_id , dateStart, dateEnd FROM dbPWork
LEFT JOIN dbPWorkW ON dbWork.id = dbPWorkW.work_id
LEFT JOIN words ON dbPWorkW.word_id = words.id



Everything works fine until I add the second LEFT JOIN statement. Any ideas? I'm stumped.

View 4 Replies View Related

Stumped -- Need A Set Based Solution

Dec 30, 2003

Guys ,

Here's my problem

Table Structure

create table holding (
id1 int,
id2 int,
datefield datetime,
holding int,
quantity int
)
go

insert into holding
select 1,1,'20031210',10,null
union
select 1,1,'20031211',30,null
union
select 1,1,'20031212',70,null
union
select 1,1,'20031213',60,null
union
select 1,2,'20031210',100,null
union
select 1,3,'20031210',100,null
union
select 1,3,'20031210',10,null

go

Quantity is based on Holding for the day - Holding for the previous transaction involving same id1 ,id2.

i.e result should look like this


id1 id2 datefield holding quantity
----------- ----------------------------------------------------------------- ----------- -----------
1 1 2003-12-10 00:00:00.000 10 10
1 1 2003-12-11 00:00:00.000 30 20
1 1 2003-12-12 00:00:00.000 70 40
1 1 2003-12-13 00:00:00.000 60 -10
1 2 2003-12-10 00:00:00.000 100 100
1 3 2003-12-10 00:00:00.000 100 100
1 3 2003-12-11 00:00:00.000 10 -90

View 4 Replies View Related

A Query I've Encounter That Has Me Stumped ... Anybody?

Aug 19, 2007

Hello Everyone,

I was hoping somebody could help me out with a query I've been trying to solve.


My Table Structure:

[UserMessages]

MessageID int
ToUserID int
FromUserID int
Subject varchar(200)
Message varchar(max)
isNew bit


[UserMessageReplies]

ReplyMessageID int
MessageID int
ToUserID int
FromUserID int
Message varchar(max)
isNew bit


Sample Data:

[UserMessages]

MessageID | ToUserID | FromUserID | Subject | Message | isNew
-------------------------------------------------------------------------------------------------------------
1 1 2 test subject Message Body 0
2 2 1 test subject Message Body 0
3 1 4 test subject Message Body 1
4 1 5 test subject Message Body 1


[UserMessageReplies]


ReplyMessageID | MessageID | ToUserID | FromUserID | Message | isNew
---------------------------------------------------------------------------------------------------------------------------
1 1 2 1 re: Message Body 0
2 1 1 2 re: Message Body 0
3 1 2 1 re: Message Body 0
4 1 1 2 re: Message Body 0
5 1 2 1 re: Message Body 1
6 2 1 2 re: Message Body 1


Explanation:

ReplyMessageID = 1-4 signfies that there is a thread response to MessageID 1 but they have been opened (isNew =0).
ReplyMessageID = 5 signfies that there is a new thread response to MessageID 1.
ReplyMessageID = 6 signifies that there is a reply from a message UserID=1 sent out (MessageID 2)

There needs to be a filter to check UserMessages.TOUserID=1 OR UserMessageReplies.ToUserID=1 to ensure that we can capture a msg that UserID=1 had sent out but now there is a reply to the Message by the User (in this example data i've setup MessageID = 2 to handle that possibility)

My Goal:

To select all messages for a ToUserID and order them by UserMessages.isNew or UserMessageReplies.isNew. This must include a message the user has sent but now has received a reply. (This means the first filter; UserMessages.ToUserID, must be overwritten with UserMessageReplies.ToUserID)



Thanks very much!

Chris

View 4 Replies View Related

STUMPED: Why Doesn't This Procedure Work?

Jan 16, 2006

I have been looking at this for over a day now. I cannot see why this procedure does not work, its so simple.
No matter what happens it always returns 0. If it locates a record, it doesnt update it, yet it still returns 0.
It should not be returning 0 if its not updating so I can't figure out why it does.
Why does this always return 0?
[pre]Create Procedure CreateNewCategory @title nvarchar(100), @description nvarchar(1000), @displayOrder intAS DECLARE @Result as int
IF EXISTS(SELECT categoryTitle FROM categories WHERE categoryTitle = @title) BEGIN  SELECT @Result = 1 ENDELSE BEGIN  INSERT INTO categories(categoryTitle, categoryDescription, displayOrder)  VALUES(@title, @description, @displayOrder)   /* If no error was encountered, 0 will be returned. */  SELECT @Result = @@Error ENDGO[/pre]
Thanks!
 

View 2 Replies View Related

Hey I've Got A Homework Problem I'm Working On And Am Stumped.

Aug 10, 2006

It goes like the following:Use AdventureWorks database and HumanResources.Department table.Create a stored procedure called spDepartmentAddUpdate. This procedureaccepts two parameters: Name, and GroupName. The data types areVarChar(50), and VarChar(50) respectively. Define logic in thisprocedure to check for an existing Department record with the same Name.If the department record exists, update the GroupName and ModifiedDate.Otherwise, insert a new department record.A.Execute your stored procedure to show that the insert logic works.B.Execute your stored procedure to show that the update logic works.Any hints from the wizards out there would be greatly appreciated!*** Sent via Developersdex http://www.developersdex.com ***

View 6 Replies View Related

Stumped On How To Set-up Priority So Evaluation Correctly Finishes

Feb 2, 2008

Hello everyone

Here is the situation I'm trying to set-up a package to ftp some files down if that part fails email me but if successful rename the 2 files to something else.


so what I set-up was a FTP tasks with the remote path set as a expresion since I needed to Download todays files.
no problem there have that part working.

so then I set a notifaction event with failure constraint to email me. pretty easy so far.

then I set 2 tasks to rename the 2 files downloaded I'm sure I could do this part with a loop but what seperate tasks so I knew if any failed or could set-up notifaction tasks if I wanted. in the 2 rename tasks I set the sourcepath to an expression so it would know to read todays files and they could change from day to day.

then the destination part is hard coded for now to a file name.

now here is were the issue comes in I go to save it and it says the files don't exist from the rename piece. well of course not they haven't been FTPed yet.

so I tried delayevaluation on both the file system tasks but a no go still errors.

What I need it to do is basically say wait till the ftp is run these files won't be there. any help in the right direction would be appreciated.

thank in advance
Troy

View 1 Replies View Related

Making A (sort Of) Dynamic Pivot Table. I'm Stumped

May 11, 2008

Hello,

I've seem some good posts similair to this, but I haven't been able to find my exact issue.

I have the following table:







ID
Name
Location
Start
End

1
Joe
NY
2000
2001

1
Joe
CA
2002
2004

1
Joe
MA
2005
2008

2
Sue
NJ
2003
2004

2
Sue
FL
2004
2008

3
Bob
CA
1999
2000

3
Bob
WA
2001
2004

3
Bob
OR
2005
2006

3
Bob
MI
2007
2008


As you can see, the Location, Start and End dates can vary for each person and I don't know how many rows a single person might have.


The result I want, is a "pivot like" table.







ID
Name
Location1
Start1
End1
Location2
Start2
End2
Location3
Start3
End3
Location4
Start4
End4

1
Joe
NY
2000
2001
CA
2002
2004
MA
2005
2008




2
Sue
NJ
2003
2004
FL
2004
2008







3
Bob
CA
1999
2000
WA
2001
2004
OR
2005
2006
MI
2007
2008


I assume I can first do a count of the maximum rows for an individual and that is greatest number of columns I would need. But doing that and trying to figure out the rest has really stumped me.


Any thoughts, ideas and suggestions would be greatly appreciated.

Thank you.

-Gumbatman

View 11 Replies View Related

Classic Sales Summary With Royality Logic Has Me Stumped.

Nov 1, 2007

Hello everyone. I'm stuck with what must be a common sql challenge.



I've got this single table that looks like this:



Store, Original Store, Product, Sale type, Method, Amount



There will be two product types (prodA and prodB)


There will be two Sale Types (New and Recharge)


There will be two Method (Cash and Credit)





The tricky part is I also need to report sales activity when a store
was the Original Store for a customer Recharge at another Store.


The report needs to look like this:


Store , Product, Cash New Total, Cash Recharge Total, Credit New
Total, Credit Recharge Total, Outside Recharge Total

Grouping/Totally on Store/Product.



In the above "Outside Recharges" means the Store was the Original store
and another store performed a recharge on it's customer.




Thanks for any help or information

View 3 Replies View Related

Product Key

May 8, 2007

Hello I installed MS SQl 2005 the eval version and it has expired. I have bought a copy now and i need to put the product keys in without having to reinstall the program. Is there anyway i can do this with having to reinstall SQl again..
Any help would be great

Randy Martin

View 1 Replies View Related

How To Buy SQL Server 7 Product

Aug 18, 1999

I want to upgrade 5 SQL Server 6.5 production boxes to SQL Server 7. I got
SQL Server 7.0 pricing and licensing list from
www.microsoft.com/sql/70/gen/pricing.htm and I think I should buy 5 SQL
Server 7.0 Combined Product/Version/Competitive Upgrade (Since I have been using SQL Server 6.5, I don’t need to buy the full product. Is this right?). I am not sure if
the upgrade offer (the price is much lower than the full product offer $699/$1399) includes the SQL Server 7.0 both software and access license.


Thanks for any help in advance.

Stella Liu

View 1 Replies View Related

Product Sub-Typing

Jul 14, 2004

Hi,

I am interested in opinions on the following,

main(product_id, short_text, price, type)
productTypes(type_id, type)
productTables(type_id, tableName)
productA(product_id, field1, field2)
productB(product_id, field1, field2)

To retrieve all products of type 'A', one must know the table name, in this case 'productA'.

Here is one method.

Create a table that contains the table name that corresponds to each product type, thus the stored procedure only needs to recieve the type_id which can be used to obtain the name of the respective table.

View 1 Replies View Related







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