SQLITE Replace Column IDs with NAMES from SEPERATE TABLE in same DB - database

I have a sqlite database avalible here => https://www.dropbox.com/s/9cn093ns3ot2cik/drinks.db?dl=0
I'm trying to show ( or replace?) the drinks.glass_id with its proper name from glasses.name
I have tried
select drinks._id DID,
drinks.glass_id GID,
glasses.name GNAME,
glasses._id GIDD
from drinks DRNKS
join glasses GLS
on drinks.glass_id = glasses._id
What is wrong??
I have spent several hours looking this up.
I have read these links and still cant figure it out.
http://community.spiceworks.com/topic/242166-sql-query-help-convert-category-id-to-the-text-name
Replacing a pulled SQL ID value with its name from another table
How to replace fetched values with another column while querying with SQL Server 2008 R2
how to get name from another table with matching id in another table?

If you specify an alias for your tables then you have to use it everywhere
select d._id DID,
d.glass_id GID,
g.name GNAME,
g._id GIDD
from drinks d
join glasses g on d.glass_id = g._id

Related

SQL loop for updating rows

I'm new to SQL Server. The scenario is the following:
I have a csv with a bunch of Serial N0, which are unique.
Example:
Serial No
-----------
01561
21654
156416
89489
I also have a SQL Server database table, where are several rows which can be identified with the serial no. For example I have 6 rows in the SQL Server table with the serial no. 01561. Now I want to update a field in all these rows with "Yes". If it is only about this number, I know the solution it's
UPDATE dbo.Table1
SET DeleteFlag = 'Yes'
WHERE Serial No. = 01561;
Unfortunately I have more than 10,000 Serial No in the csv for what I have to do that. Can you help me to find a solution for that?
First you should use the TASK feature to import the CSV. You right click to do this on the database and select "TASK" and import data. Its a UI which is pretty self explanatory, so itll help you get the job done quickly and easily. Make note of the name you give the table, SQL Server will try and give it a defualt name with a "$" in the name. Change that to something like "MyTableImport". If the data is already in SQL Server, go to the next step.
Step 2 - You can do the UPDATE for the entire table via a join. All youre doing is matching the ID's to another table, right? Looping would be a bad idea here especially since itll take a minute to loop through 10000+ and run an update FOR EACH ONE. Thats against an idea known as "Set based approach" which to sum it up nicely is to do things all at once (google it though because im horribly over simplifying the idea for you). Here is a sample update join query for you:
UPDATE x
SET x.DeleteFlag='Yes'
FROM yourimportable y
INNER JOIN yourLocal x ON y.SerialNo=x.SerialNo
Assuming that you have created a temp table to load CSV with a bunch of serial number. Now you can update your permanent table with the temp table data using update join like this:
UPDATE t1
SET t1.DeleteFlag = 'Yes'
FROM dbo.Table1 AS t1
INNER JOIN #TempTable2 AS t2
ON t1.Serial_No = t2.Serial_No

A challenge for you SQL lovers out there

I'm new to the working world an am fresh out of varsity. i started working an am creating a few reports via SQL reporting services as part of my training.
Here is quite a challenge that I am stuck at. Please help me finish this query. Here is how it goes!
There are several employees in the employee_table that each have unique identifier known as the emp_id
There is a time_sheet table that consists of several activities AND THE HOURS FOR EACH ONE for the employees and references them via emp_id. Each activity has a TIMESHEET_DATE that corresponds to the day all the activities were submitted(once a month). There are several activities with the same date because all those activities were submitted on the same day.
And there is a leave table that references the employees via emp_id. In the leave table, there is a column for the amount of days they took off and the starting day (Leave_FROM) of the leave.
I must create a parameter where the user inputs the month (easy peasy)...
Now in the report, column 1 must have their name (easy), column 2 must have their totals hours for the specified month (HOURS) and column 3 must show how many days they took leave for that month specified.
It can be tricky, not everybody has a entry in the leavetable, but everybody has got activities in the Time_Sheet table.
Here is what I have gotten so far from a query, but its not really helping me.
Unfortunately, I cannot upload pictures, so here is a link
http://imageshack.com/a/img822/8611/5czv.jpg
Oh yea, my flavor of SQL is SQL Server
You have a few different things you need to attack here.
First is getting information from the employee_table, regardless of what is in the other two tables. To do this, I would left join on both of the tables.
Your second battle is, now since you have multiple rows in your time_sheet table, you are going to get a record for every time_sheet record. That is not what you want. You can fix this by using a SUM Aggregate and a GROUP BY clause.
Next is the issue that you are going to have when nothing exists in leave table and it is returning NULL. If you add an ISNULL(value,0) around your leave table field, it will return 0 when no records exist on that table (for that employee).
Here is what your query should look like (not exactly sure on table/column naming):
I changed the query to use temp tables, so totals are stored separately. Since the temp tables will hold 0 for employees that don't have time/leave, you can do an inner join on your final query. Check this out for more information on temp tables.
SELECT e.emp_id, ISNULL(SUM(ts.Hours),0)[Time]
INTO #TotalTime
FROM employee e
LEFT JOIN time_sheet ts ON e.emp_id = ts.emp_id
GROUP BY e.emp_id
SELECT e.emp_id, ISNULL(SUM(l.days),0) [LeaveTime]
INTO #TotalLeave
FROM employee e
LEFT JOIN leaveTable l ON e.emp_id=l.emp_id
GROUP BY e.emp_id
SELECT e.Emp_Id,Time,LeaveTime FROM Employee e
INNER JOIN #TotalTime t ON e.Emp_Id=t.Emp_Id
INNER JOIN #TotalLeave l ON e.Emp_Id=l.Emp_Id
DROP TABLE #TotalLeave,#TotalTime
Here is the SQL Fiddle
Left join the leave table, if nobody took leave you won't get any results.

Selectively dumping and inserting into new database with a new primary key

I have a database has been running on a server. I also have a database running for about a month on a new server which has data based on the old server. Since these both have been running this past month, the data on them are not equal.
We want to move selective data from two tables in the old database to the new one. This is the select I want to move, one month of data:
select * from table1 left join table2 on table1.keyID = table2.keyID
where table2.updated between '2013-08-01' and '2013-08-31';
From my understanding I would probably need to dump each table on its own. However when inserting this data into the new database, I would need to give these entries new keyID (this is autogenerated). How can I do this while keeping the connection between these two tables?
Take a dump of table1 & table2 from the old server and restore it in the new server under the database name oldDB
I Assume your database name in new server is newdb
Insert into newdb.table1 (Field1,Field2,field3)
select Field1,Field2,field3
from olddb.table1
left join olddb.table2
on (olddb.table1.keyID = olddb.table2.keyID)
Where olddb.table2.updated between '2013-08-01' and '2013-08-31';
Please note that you have to specify all the fields in select statement except your KeyID field. KeyID number will be autogenerated by the database
I am assuming that the KeyID Field is Auto Increment field other wise this solution will not work

Merge query using two tables in SQL server 2012

I am very new to SQL and SQL server, would appreciate any help with the following problem.
I am trying to update a share price table with new prices.
The table has three columns: share code, date, price.
The share code + date = PK
As you can imagine, if you have thousands of share codes and 10 years' data for each, the table can get very big. So I have created a separate table called a share ID table, and use a share ID instead in the first table (I was reliably informed this would speed up the query, as searching by integer is faster than string).
So, to summarise, I have two tables as follows:
Table 1 = Share_code_ID (int), Date, Price
Table 2 = Share_code_ID (int), Share_name (string)
So let's say I want to update the table/s with today's price for share ZZZ. I need to:
Look for the Share_code_ID corresponding to 'ZZZ' in table 2
If it is found, update table 1 with the new price for that date, using the Share_code_ID I just found
If the Share_code_ID is not found, update both tables
Let's ignore for now how the Share_code_ID is generated for a new code, I'll worry about that later.
I'm trying to use a merge query loosely based on the following structure, but have no idea what I am doing:
MERGE INTO [Table 1]
USING (VALUES (1,23-May-2013,1000)) AS SOURCE (Share_code_ID,Date,Price)
{ SEEMS LIKE THERE SHOULD BE AN INNER JOIN HERE OR SOMETHING }
ON Table 2 = 'ZZZ'
WHEN MATCHED THEN UPDATE SET Table 1.Price = 1000
WHEN NOT MATCHED THEN INSERT { TO BOTH TABLES }
Any help would be appreciated.
http://msdn.microsoft.com/library/bb510625(v=sql.100).aspx
You use Table1 for target table and Table2 for source table
You want to do action, when given ID is not found in Table2 - in the source table
In the documentation, that you had read already, that corresponds to the clause
WHEN NOT MATCHED BY SOURCE ... THEN <merge_matched>
and the latter corresponds to
<merge_matched>::=
{ UPDATE SET <set_clause> | DELETE }
Ergo, you cannot insert into source-table there.
You could use triggers for auto-insertion, when you insert something in Table1, but that will not be able to insert proper Shared_Name - trigger just won't know it.
So you have two options i guess.
1) make T-SQL code block - look for Stored Procedures. I think there also is a construct to execute anonymous code block in MS SQ, like EXECUTE BLOCK command in Firebird SQL Server, but i don't know it for sure.
2) create updatable SQL VIEW, joining Table1 and Table2 to show last most current date, so that when you insert a row in this view the view's on-insert trigger would actually insert rows to both tables. And when you would update the data in the view, the on-update trigger would modify the data.

Detecting multiple records associated with a table

I have a SQL Server 2008 database that has two tables. These two tables are CoreGroup and CoreGroupMember. Please note, I did not setup these tables. Regardless, the table structure is:
CoreGroup
---------
ID
GroupMember1MemberName
GroupMember2MemberName
GroupMember3MemberName
GroupMember4MemberName
CoreGroupMember
---------------
ID
CoreGroupID
MemberName
I need to determine how many CoreGroup records are associated with a CoreGroupMember with a specific MemberName. There is one catch that is really throwing me for a loop though. Some CoreGroup records only have one member associated with them. I need to retrieve the CoreGroup records that have multiple CoreGroupMember records where at least one of the records has the specific MemberName. I can't seem to figure out the multiple record part. Can someone please help me?
Thank you!
I'll take a stab at it hoping I've understood the requirements correctly. First, I use a cte to find all groups with multiple members, then use that result set to find groups with your specific member.
with cteMultipleMembers as (
select cg.ID, COUNT(*) as MemberCount
from CoreGroup cg
inner join CoreGroupMember cgm
on cg.ID = cgm.CoreGroupID
group by cg.ID
having COUNT(*) > 1
)
select mm.ID
from cteMultipleMembers mm
inner join CoreGroupMember cgm
on mm.ID = cgm.CoreGroupID
and cgm.MemberName = #YourMemberName

Resources