Basically I want to select all of the Products (no duplicates) where EVERY customer(1, 2 & 3) have bought a from a common shop type: i.e 'Trainers' and 'Football' should not be selected as Customer3 has not bought any goods from a sports store.
This is an example of a larger problem where there can be numerous products, customers and shops. Here's a DESCRIBE of the relevent columns in each of the tables:
CUSTOMER:
customerID
PRODUCT:
productID
customerID
shopID
SHOP:
shopID
This looks like it should be easy but my SQL isn't the best ;-)
Hello,I have a (big) table which is not normalized, but for i need at themoment i thinkthat's no problem. Indeed, what i would like to do is to select thename field andthe note. The problem is that i want to display the note in 2different columns.the first columns will show the number (count) of time that a certainnote (e.g note=4)appears for a certain name and in the other column the same thing butfor a different note value.so each column noteX will display the number of time that the notewith the value X appears for each namefor example, to the following table:Name | note | job | city | id |----------------------------------------john | 4 | jb1 | hamb | 1 |john | 5 | jb2 | hamb | 2 |john | 5 | jb3 | hamb | 3 |john | 5 | jb4 | hamb | 4 |Mark | 4 | jb1 | mun | 5 |Mark | 4 | jb2 | mun | 6 |Mark | 4 | jb5 | mun | 7 |Mark | 5 | jb1 | mun | 8 |peter | 5 | jb3 | berl | 9 |peter | 5 | jb5 | berl | 10 |frank | 4 | jb6 | v.form | 11 |frank | 5 | jb3 | v.form | 12 |frank | 5 | jb2 | v.form | 13 |the result should be:Name | note5 | note4 |-------------------------john | 3 | 1 |Mark | 1 | 3 |peter | 2 | 0 |frank | 2 | 1 |How should be the right SQL command to show the data i want?Rui DiasJoin Bytes!Thanks a lot
I know there is some kind of rule against the following SQL statement, but I was wondering what to do to get around this problem (some kind of grouping). Sorry for the stupid question.
SELECT * FROM Table1, Table2 WHERE Table1.ID IS NOT NULL AND Table2.ID IS NOT NULL
Basically I want to select all records from the two tables (they have the same fields, but are just different specialties) and then output them, but there is nothing in common between the two to reference one another, and it ends up in some kind of loop. Thanks. for the help.
What I am trying to do is count persons in buckets "non-recidivists" and "recidevists" based on how many bkg_nbr they have per STATE_NBR. If they have more than 1 bkg_nbr per STATE_NBR then put them in the "recdivists" bucket. If they only have a 1 to 1 then put them in the "non-recidivists" bucket.
Hello, I would like to deploy a per-machine Express database as part of my VS2005 C# desktop application. The deployment must work with both XP and Vista from the same setup files. I'm not using One-Click installation. I don't want my users to have to configure Express with the Surface Area Configuration tool.
Since the database cannot go in C:Program Files because of Vista ACL issues, I am using COMMONAPPDATACompanyNameAppName as the install path for the database and other user writable application files. In XP this expands to C:Documents and SettingsAll UsersApplication DataCompanyNameAppName and in Vista it is C:ProgramDataCompanyNameAppName. Neither of these paths have write privileges for unprivileged users, so the install program needs to change the write permissions at install time. Right now I am using SetACL ( http://setacl.sourceforge.net/ ), to do that and the install goes fine with write permissions on the companyName folder and it's children for all users.
But I can't connect to the mdf file in my COMMONAPPDATACompanyNameAppName folder. If I am the administrator/installer it works fine, but as an unprivileged user I get different errors, but mostly "Could not login user ...". For debugging, I have also tried installing the database in the "AppFolder" directory (which for my app in both Vista and XP is C:Program FilesCompanyNameAppName) and using "User Instance=true" in the connection string, and the connection is made but (at least on XP) the unprivileged user cannot write to the database because the folder lacks write privileges for that user.
I suppose one thing I could do would be to change the folder/file permissions in the AppFolder, but I am reluctant to do that because I have read that Microsoft does not guarantee that the "Compatibility" feature in Vista for the Program Files directory will be available in future releases/service packs.
So is there a way to do a simple installation/db connection for a per-machine database located in a COMMONAPPDATA path?
Hellow Folks. Here is the Original Data in my single SQL 2005 Table: Department: Sells: 1 Meat 1 Rice 1 Orange 2 Orange 2 Apple 3 Pears The Data I would like read separated by Semi-colon: Department: Sells: 1 Meat;Rice;Orange 2 Orange;Apple 3 Pears I would like to read my data via SP or VStudio 2005 Page . Any help will be appreciated. Thanks..
As you all know, in Framework 2.0 on the desktop platform you have the convenient "abstract" Db* classes that can be used to write more generic code. For instance System.Data.SqlClient.SqlConnection inherits from System.Data.Common.DbConnection, and so forth. Now the docs clearly say that this applies to the corresponding classes in the Compact Framework. And i have seen this implied by other web searchs I've done. However this does not seem to be the case -- or, I'm missing something somewhere.
The following simple code on the desktop platform compiles OK:
using System.Data; using System.Data.Common; using System.Data.SqlClient; DbConnection conn = new SqlConnection();
However it doesn't compile in a compact framework project: "Cannot implicitly convert type 'System.Data.SqlClient.SqlConnection' to 'System.Data.Common.DbConnection'".
Reflector also indicates that the Compact Framework class doesn't inherit from DbConnection.
OK, so am I missing something here, or what was the reason that Microsoft did it differently??
1) Production data with column headers: Key, Facility, Line, Time, Output 2) Costs data with column headers: Key, Site, Cost Center, Time, Cost
The tables have a common key named obviously as Key. The data looks like this:
Key Facility Line Time Output Alpha
I would like to have two pivot tables which I can filter with ONE slicer based on the column Key. The first pivot table shows row labels Facility, Line and column labels Time. Value field is Output. The second pivot table shows row labels Site, Cost Center, and column lables Time. Value field is Cost.How can I do this with Power Pivot? I tried by linking both tables above to a table with unique Keys in PowerPivot and then creating a PivotTable where I would have used the Key from the Keys table.
I am unable to the access on table even after providing the SELECT permission on table.
Used Query by me :
Here Test is schema ; Card is table ; User is Satish
To grant select on Table
GRANT SELECT ON TEST.Card TO satish Even after this it is not working, So provided select on schema also. used query : GRANT SELECT ON SCHEMA::TEST TO Satish.
I'm building an exception management system into my application. What are the most common errors when working with a DAL and a SQL server. The biggest problem can be Database connection. My questions: * Are all SQL related errors catched by the SqlExeption class? * Which are the most common sql errors?
I have a stored procedure I use to fill my datagrid..... While doing this is there a way to get the number of records returned... I use a datareader........any help
I just inherited a Java application with a fairly complex data modelthat does not yet have any indexes except those on primary keys. It isstill in development and before I get to do any performance testing Iwant to put some default indexes on it. I realize that this a veryvague request but it's better than nothing so I want to start withthose that are generally a good idea and then tune those areas thatrequire more fine grained approach. By the way, I'm mostly a Javaprogrammer so please forgive my DB ignorance and I thank you for anyhelp.Since the full schema is quite large I will use a simple example (fullycited below my questions). Here is list of indexes that I think wouldbe a good idea. If anyone can add to it or comment on my questions Iwould appreciate it.1. Index on primary keys in all three tables. My understanding thatthis indexing happens automatically just by declaring that a column isa PK.ALTER TABLE employees ADD PRIMARY KEY (emp_id);ALTER TABLE employee_addresses ADD PRIMARY KEY (address_id);ALTER TABLE departments ADD PRIMARY KEY (dept_id);Question: Does index get created automatically because this is a PK?2. Index on foreign keys in the children tables to prevent deadlocksand lock escalations.CREATE INDEX fk_index ON employee_addresses (emp_id)3. Indexes on common queries on all three tables.CREATE INDEX common_query_idx on employees(last_name, first_name,position)CREATE INDEX common_query_idx on departments(last_name, first_name,position)CREATE INDEX common_query_idx on employee_addresses(street, city)Question: Given that the searches can be on any field separately andin any combination should I also put an index on each columnindividually or will the composite index take care of individualsearches as well? For example, will the above indexes be sufficientfor the following SELECT:SELECT e.last_name, e.first_name from employees e, departments d,employee_addresses ea, dept_employees de WHERE e.emp_id = de.emp_id ANDd.dept_id = de.dept_id AND ea.emp_id = e.emp_id AND e.position ='master chief' AND d.dept_name = 'galactic affairs' AND ea.city='LosAngeles'4. Unique index on the association table. Again this is accomplishedusing PKALTER TABLE dept_employees ADD PRIMARY KEY (dept_id, emp_id)Question: Is the index on (dept_id, emp_id) automatic because of PK?5. The association table has to go both ways and PK takes care only ofthe first half. Thus add an index to go the other way.create unique index dept_employee_idx on dept_employee(emp_id,dept_id)Question: should I use INDEX ORGANIZED TABLE?Question: should I have UNIQUE qualifier on the second index given thatPK already takes care of it?Thanks,Robert===== EXAMPLE ======1) An employee can be in many departments and a department can containmany employees.2) Common searches for employees are on last_name, first_name,position, department_name, department_location separately and in anycombination.3) There are common searches for departments that contain certainemployees e.g. find all departments containing John Smith.CREATE TABLE employees(emp_id INTEGER NOT NULL,last_name VARCHAR(50) NOT NULL,first_name VARCHAR(25) NOT NULL,position VARCHAR(10) NOT NULL);CREATE TABLE employee_addresses(address_id INTEGER NOT NULL,emp_id INTEGER NOT NULL,street VARCHAR(50) NOT NULL,city VARCHAR(25) NOT NULL,);CREATE TABLE departments(dept_id INTEGER NOT NULL,dept_name VARCHAR(50) NOT NULL,dept_location VARCHAR(25) NOT NULL,);CREATE TABLE dept_employees(dept_id INTEGER NOT NULL,emp_id INTEGER NOT NULL,);ALTER TABLE employee_addresses ADD FOREIGN KEY (emp_id) REFERENCESemployees(emp_id)ALTER TABLE dept_employees ADD FOREIGN KEY (emp_id) REFERENCESemployees(emp_id)ALTER TABLE dept_employees ADD FOREIGN KEY (dept_id) REFERENCESdepartments(dept_id)
HiI have a query that is performing very strangely.I f I put a top statement in it returns rows,soSelect top 10 * from .......returns 10 rowsbut without it then no data is returnedSelect * from ..........returns 0 rows.
I was studying Common Table expression in Sql server 2005. I have written the code Declare @PictureArray as varchar(200) Set @PictureArray = ''; with UserProfile_CTE(UserPicture) As( select @PictureArray = @PictureArray + '~' + PictureName from UserPicture where UserProfileID = 1102 select @PictureArray ) select * from UserProfile_CTE
But I am getting the error Incorrect syntax near '=' I am getting the error in the lineselect @PictureArray = @PictureArray + '~' + PictureName from UserPicture where UserProfileID = 1102 But I don't know the reason for this, Kindly advice Regards Karan
In my experience of going through plenty of interviews, I have came across a question that I am reminded of by someone's signature.
The common question in this instance is: What is the advantage of a cursor over a stored procedure? Vice Versa?
I could only, in my so few experiences, have answered that stored procedure consumes less system resources than a cursor. The advantage a cursor has is record by record examination and looping capabilities.
Needless to say that whenever asked those questions, I haven't landed the position. So I'm wondering, what is the more appropriate answer?
I try to find the best design for a SQL Server 2005 database structure.
I have the following 'objects':
Facilities Departments - 'dependents' of a Facility Users
Addresses - each of the above can have none or more Addresses.
The basic tables design would be: CREATE TABLE [dbo].[Facility]( [cFacilityID] [nvarchar](5) NOT NULL PRIMARY KEY CLUSTERED , [cFacilityName] [nvarchar](50) NOT NULL ) GO CREATE TABLE [dbo].[Department]( [cFacilityID] [nvarchar](5) NOT NULL FOREIGN KEY REFERENCES [dbo].[Facility] ([cFacilityID]) ON UPDATE CASCADE ON DELETE CASCADE, [cDepartmentID] [nvarchar](3) NOT NULL, [cDepartmentName] [nvarchar](50) NOT NULL, PRIMARY KEY CLUSTERED ( [cFacilityID], [cDepartmentID]) ) GO CREATE TABLE [dbo].[User]( [cUserID] [nvarchar](5) NOT NULL PRIMARY KEY CLUSTERED, [cUserName] [nvarchar](50) NOT NULL ) GO CREATE TABLE [dbo].[Addresses]( [pkAddress] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED, [cAddress] [nvarchar](255) NULL, [cZip] [nvarchar](5) NULL, [cEmail] [nvarchar](255) NULL ) GO
The question regards the Addresses table: How can I design the Addresses table(s) so I can enforce relational integrity and cascade update and delete for each Facility, Department and User tables?
I figured out the following options, but none achives my requirements:
1. An Address table for each 'object': FacilityAddress, DepartmentAddress, UserAddress with the corresponding foreign key in each Address table. This solution duplicates all the addresses fields (which are more than I showed in the example).
2. A common Addresses table with a discriminator field (1=Facility, 2=Department, 3=User). This doesn't allow me to enforce referential integrity with constraint, maybe only with triggers.
3. A common Addresses table with a foreign key for each 'object (fkFacility, fkDepartment, fkUser) allowing nulls. In this case, the 'dependence' between Facility and Department stops me to enforce cascade deletes/updates on both Facility and Department foreign key (circular...).
4. An intermediate (link) table between each 'object' and Addresses table with the foreign keys (Facility, Addresses). Again, no referential integrity.
So, is there a method to design such structure?
PS. Please keep in mind that this is just a simplified example (reduced at the key information) of my real structure.
At the risk of asking a stupid question -Is anyone familiar with either a query against the systables or maybean outside tool that will provide a list of the most common joins thathave been made in user created views? I'm not talking about tablerelationships that are established at the database level, but rather,I'm referring to the ability to find which joins have been utilized inpoorly constructed databases where no relationships were establishedin the first place.Thanks in advance -Cindy T.
What is the SQL Server equivalent of DB2 common table expressions? Forexample,with gry(year,count) as(select floor(sem/10),count(distinct ssn)from gradesgroup by floor(sem/10))select year,sum(count) Head_Count from grygroup by yearhaving year >= 1980;N. ShamsundarUniversity of Houston
I see that part of SP2 is the new CC certification -- can anyone give me some more details. What level is it at? EAL4? I can't seem to find the certificate on the CC Web site but it could be because it's not SP2 yet.
I'm working on an application designed like this: There's a table "DailyTransations" (DT) containing daily transactions... Then there's an archive table "TransationsArchive" (TA) with the exact same structure.
When a record is inserted in DT, it is also in TA (via a trigger) and the reporting is done against TA. Now for performance issues, we delete from DT the records older than 2 days since they are not needed for processing.
First, what do you think of that implementation?
We thought about using partitions based on the transaction date and completely eliminate TA, but it seems once a record is assigned to a partition, it is not moved automatically...
The comapny i work for has a server running the following.
Opteron 246x2
2 Gig memory
320 Gig Sata 2 drives
Windows 2003 Standard Edition
SQL Server 2005 Express Edition. The Free one.
There are approx 10 users that connect to the server.
There are two programs which seem to use sql server. Act 7.0 and service ceo.
When the computer is rebooted its at 0% for sqlserver.exe
Than when all connect it maxes it 50% and its steady there. Seems Service ceo affects it the most.
Told by comapny need to buy full blown sql server to resolve problem. But i dont think this is the problem.
Questions: Is it common for server to be at 50% all the time with sql server running?
And if its not is there a way to reduce the sql cpu usage.
I am new to sql server and have done alot of research and fixes. Ive unsitalled and reinstalled all sql instances and done the tweaks suggested. Any fresh ideas would be great thanks.
I need to get the 5 most common occurences from a table. Not really sure of the SQL statement I would use to do that. Would someone be kind enough to throw out a select statement that would do this? psuedo code would be fine, I just need to know the jest of how to do it. I originally thought Select Top 5 would work, but then I actually started thinking and realized it wasnt it. So now im stuck. Any help would be appreciated.
Thanks, Steve
EDIT: I should add that this will be coming from a view with multiple tables..thanks
I need to display the company logo on 100 odd reports that run from different folders on the report manager. Since the company logo has changed before and we had to change every report, I want the image stored on a server (with SSL on) and want the reports to point to the server. The server is going to be different in development and production environments.
When I try to add the image using "Image Wizard" I get the error "Invalid image.". The wizard wouldn't let me use a function to build the path based on the environment and select the image from the correct server. It doesn't accept anything that doesn't start with "http:" when I select "web" as the image source.
I know its not a good idea to give you a big query...but/...
I have a query (given below) with Common table expressions. It is giving me error : The multi-part identifier "dbo.tmpValidServices_ALL.Service" could not be bound. for all the fields .. Do you have any idea.. I fed up with analysing query.. made me mad.. please help me...
SET @sql = 'WITH Q1 (SiteID,Programme,Complete,PID,COC,NotionalSum,TVMinsSUM,Postcode,Suburb,Qty) AS
(SELECT dbo.tmpValidServices_ALL.SiteID, dbo.tmpValidServices_ALL.Programme, dbo.tmpValidServices_ALL.Complete AS Complete, dbo.tmpValidServices_ALL.RID AS PID, dbo.tmpValidServices_ALL.COC# AS COC, (dbo.lkpService.Notional$) AS NotionalSum, (TVMins) AS TVMinsSUM, dbo.tmpDemographics_ALL.Postcode, dbo.tmpdemographics_ALL.Suburb, count(*) as Qty
FROM lkpService
INNER JOIN dbo.tmpValidServices_ALL vs ON dbo.lkpservice.code = dbo.tmpValidServices_ALL.Service INNER JOIN dbo.tmpDemographics_ALL ON dbo.tmpValidServices_ALL.RID = dbo.tmpDemographics_ALL.RID '
IF @COCGroup IS NOT NULL SELECT @sql = @sql + 'LEFT OUTER JOIN dbo.lkpCOC c ON dbo.tmpValidServices_ALL.COC = c.pvcode '
SELECT @sql = @sql + 'LEFT OUTER JOIN dbo.lkpAgency ag ON vs.SiteID = ag.EXACT# '
SELECT COUNT(DISTINCT PID + CAST(Complete AS varchar(20)) + CAST(COC AS varchar(20)) + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20))) AS Visits, COUNT(DISTINCT PID + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20))) AS Patients, COUNT(DISTINCT CAST(COC AS varchar(20)) + CAST(SiteID AS varchar(20)) + CAST(Programme AS varchar(20)) + CAST(PID AS varchar(20))) AS COCs, SUM(NotionalSum) AS NotionalSum, SUM(TVMinsSUM) AS TVMinsSUM,Postcode,Suburb,sum(Qty) as Qty
FROM Q1
Group by Postcode,Suburb
Order by Postcode,Suburb '
SET @paramlist = '@SiteID as numeric, @COCGroup as varchar(20), @Postcode as varchar(20), @StartDate DateTime, @EndDate DateTime, @Schedule varchar(20), @Provider varchar(20)'
EntityID AnotherColZ AnotherColY AnotherColX 1 a f g 1 f g s 2 t w a 3 j r s 3 l e a
required output ------------------------------------------------------------------------------------- Entity1 (group the data at this level) ColValA ColValB (table for values from dataset 1) 56 78 16 75
AnotherColZ AnotherColY AnotherColx (table for values from dataset 2) a f g f g s ------------------------------------------------------------------------------------ Entity2 (now we move on to the next entity) ColValA ColValB (again one table for values from dataset 1) 12 14
(and another for values from dataset 2) ----------------------------------------------------------------------------------- etc
I have a few stored procs that I use from more than one database. There has to be a place I can put these so I don't have a copy of the proc in each DB, right?
Where do you put them and how do you reference them? Thanks.
I have managed to write my first CTE SQL that handles recursion but I have a problem with distinct - can't get that to work!! My CTE:WITH StudentsHierarchy(SystemID1, GroupID, AccessType, AccessGroupID, StudentID, HierarchyLevel) AS ( --Base Case SELECT SystemID, GroupID, AccessType, AccessGroupID, StudentID, 1 as HierarchyLevel FROM UserGroup a
UNION ALL
--Recursive step SELECT u.SystemID, u.GroupID, u.AccessType, u.AccessGroupID, u.StudentID, uh.HierarchyLevel + 1 as HierarchyLevel FROM UserGroup u INNER JOIN StudentsHierarchy uh ON u.GroupID = uh.AccessGroupID
) Select sh.SystemID1, sh.GroupID, sh.AccessType, sh.AccessGroupID, sh.StudentID, sh.HierarchyLevel, (select StudentName from Student s where sh.StudentID = s.StudentID) AS StudentName from StudentsHierarchy sh WHERE AccessType = 'S'
and I would like to have a distinct on the StudentID like:Select DISTINCT sh.StudentID, sh.SystemID1, sh.GroupID, sh.AccessType, sh.AccessGroupID, sh.StudentID, sh.HierarchyLevel, (select StudentName from Student s where sh.StudentID = s.StudentID) AS StudentName from StudentsHierarchy sh WHERE AccessType = 'S'