How do you write a query where only a select number of rows are returned with either the highest or lowest column value.
i.e. A report with the 5 highest salaried employees?
The problem: we have one application that has a portion which is used by a very small subset of the total users, and that part of the application is running off of a separate database as well. In a perfect world, the schemas of the two databases would be synced up, but such is not the case. Some migrations have been run on the smaller database, most haven't; and furthermore, there is nothing such as revision number to be able to easily identify which have and which haven't. We would like to solve this quandary for future projects. During a discussion we've come up with the following possible plan of action, and I am wondering if anyone knows of any project which has already solved this problem:
What we would like to do is create an empty database from the schema of the large fully-migrated database, and then move all of the data from the smaller non-migrated database into that empty one. If it makes things easier, it can probably be assumed for the sake of this problem specifically that no migrations have ever removed anything, only added.
Else, if there are other known solutions, I'd like to hear them as well.
Hi,
I have an update query like following:
update table TABLE1 set COL1 = 'X' where COL2 = 'Y' ---1
Support the values 'X' and 'Y' are fetched from database now TABLE2. E.g.
select COL1, COL2 from TABLE2. ----2
I want to update table TABLE1 with values from TABLE2.
Just to make it more clear, assume that TABLE2 has following values:
Can you please help me in doing this in a single query!
Pretend I have a cupcake_rating table:
id | cupcake | delicious_rating
--------------------------------------------
1 | Strawberry | Super Delicious
2 | Strawberry | Mouth Heaven
3 | Blueberry | Godly
4 | Blueberry | Super Delicious
I want to find all the cupcakes that have a 'Super Delicious' AND 'Mouth Heaven' rating. I feel like this is easily achievable using a group by clause and maybe a having.
I was thinking:
select distinct(cupcake)
from cupcake_rating
group by cupcake
having delicious_rating in ('Super Delicious', 'Mouth Heaven')
I know I can't have two separate AND statements. I was able to achieve my goal using:
select distinct(cupcake)
from cupcake_rating
where cupcake in ( select cupcake
from cupcake_rating
where delicious_rating = 'Super Delicious' )
and cupcake in ( select cupcake
from cupcake_rating
where delicious_rating = 'Mouth Heaven' )
This will not be satisfactory because once I add a third type of rating I am looking for, the query will take hours (there are a lot of cupcake ratings).
Hi!
I'm wondering if is there a way to force MSSQL Management Studio to produce a script like this:
ALTER TABLE Mytable
ADD MyCol bit NOT NULL
CONSTRAINT MyColDefault
DEFAULT 0 WITH VALUES
ALTER TABLE [dbo].Mytable
ALTER COLUMN MyCol2 int NULL
GO
when I alter a very simple property of a column on a table.
If I do this in the designer and ask for the produced script, the script doesn't do such simple tasks, but instead copies all the data in a tmp table, drops the original table, renames the tmp table with the original table name. And, of course, drops and recreates every constraint and relationships.
Is there any option I can change to change this behaviour? Or, this may be possible, is there some danger I don't see in using the simple ALTER TABLE above?
thanks.
I have a trigger which deals with some data for logging purposes like so:
CREATE TRIGGER trgDataUpdated
ON tblData FOR UPDATE
AS
BEGIN
INSERT INTO tblLog ( ParentID, OldValue, NewValue, UserID )
SELECT deleted.ParentID, deleted.Value, inserted.Value,
@intUserID -- how can I pass this in?
FROM inserted INNER JOIN deleted ON inserted.ID = deleted.ID
END
How can I pass in the variable @intUserID into the above trigger, as in the following code:
DECLARE @intUserID int
SET @intUserID = 10
UPDATE tblData
SET Value = @x
PS: I know I can't literally pass in @intUserID to the trigger, it was just used for illustration purposes.
Hi,
I want to write stored procedure in visual studio that as a parameter recieves the name of project and runs in database TT and copies data from TT.dbo.LCTemp (where the LC is the name of the project recieved as a parameter) table to "TT.dbo.Points" table. both tables have 3 columns:
PT_ID, Projectname and DateCreated
I think I have written it wrong, here it is:
ALTER PROCEDURE dbo.FromTmpToRegular
@project varchar(10)
AS
BEGIN
declare @ptID varchar(20)
declare @table varchar(20)
set @table = 'TT.dbo.' + @project + 'Temp'
set @ptID = @table + '.PT_ID'
Insert into TT.dbo.Points Select * from [@table] where [@ptID] Not in(Select PT_ID from TT.dbo.Points)
END
Any idea what I did wrong?
Thanks! :)
Greg
What I find really powerful in ADO.NET Entities or LINQ to SQL, is the ability to model complex queries. I really don't need the mappings that Entities or LINQ to SQL are doing for me - I just need the ability to model complex expressions that can be translated into T-SQL.
My question is - am I abusing too much? Can I use the Entity Framework for modeling queries and just that? Should I? I know I can write my own custom LINQ to SQL provider, but that is just not possible to handle in the time spans I have.
What is the best approach to model complex T-SQL queries? How do you handle conditional group byes, orders, joins, unions etc in the OOP world? Using StringBuilders for this kind of job feels too ugly and harder to maintain given the possibilities we have with Expression Trees.
When I use StringBuilder to model a complex SQL Query I feel kind of guilty! I feel the same way as when I have to hard code any number into my code that is different than 0 or 1. Feeling that makes you ask yourself if there is a better and cleaner way of doing it...
I must mention that I am using C# 4.0, but I am not specifically looking for an answer in this language, but rather in the domain of CLR 4.
HI, i have two tables
1- name, id, code
2- id, value, concept
One name can have two concepts and two values. i want to retreive this:
Id, name, value1, value2.
How can i do that?
Tanks
Asking a simple question, just want everyone have fun to solve it.
I got 2 tables.
1. Student
2. Course
Student
+----+--------+
| id | name |
+----+--------+
| 1 | User1 |
| 2 | User2 |
+----+--------+
Course
+----+------------+------------+
| id | student_id | course_name|
+----+------------+------------+
| 1 | 1 | English |
| 2 | 1 | Chinese |
| 3 | 2 | English |
| 4 | 2 | Japanese |
+----+------------+------------+
I would like to get the result all student, who have taken English and Chinese, NOT English or Chinese.
Expected result:
+----+------------+------------+
| id | student_id | course_name|
+----+------------+------------+
| 1 | 1 | English |
| 2 | 1 | Chinese |
+----+------------+------------+
What we normally do is
select * from student join course on (student.id = course.student_id) WHERE course_name = 'English' OR course_name = 'Chinese'
but in this result I can get User2 record which is not my expected result. I want the record only display the User take the course English+Chinese only.
Say I have the simple table below:
KeyWordID KeyWord
----------- ----------
1 Blue
3 Yellow
1 Yellow
How would I select the KeyWordID that selects the KeyWordIDs that where both KeyWord is Blue and Yellow.
E.g. it should only return 1, as this is the only KeyWordID that has both Keywords Blue and Yellow
I initially thought GROUPBY - but its not quite working as expected.
So I have a query, can someone let me know if it looks ok content wise?
"INSERT INTO ".TBL_MESSAGES." (NULL, 'Your ranking points have changed',
'Due to your recent activity, your ranking points have increased by $r', '2', '$u',
'0', '0', '0', '0', NULL, NULL, NULL, NULL, now())";
I can add further information if the query doesnt appear to have a problem?
Thanks
Hi
I need to SELECT INTO a temp table multiple times with a loop but I just can't do it, because after the table created by SELECT INTO you can't simply drop the table at the end of the loop, because you can't delete a table and create it again in the same batch.
so how can I delete a table in a stored procedure and create it again?
is it possible to this without using a temp table?
here is a snippet of where I am actualy using the temp table which is supposed to be a pivoting algorithm:
WHILE @offset<@NumDays BEGIN
SELECT
bg.*, j.ID, j.time, j.Status
INTO #TEMP1
FROM #TEMP2 AS bg
left outer join PersonSchedule j on bg.PersonID = j.PersonID and
bg.TimeSlotDateTime = j.TimeSlotDateTime and
j.TimeSlotDateTime = @StartDate + @offset
DROP TABLE #TEMP2;
SELECT * INTO #TEMP2 FROM #TEMP1
DROP TABLE #TEMP1
SET @offset = @offset + 1
END
My MySQL tables structure is like this.
USER
int id
varchar username
FRIEND_LIST
int user_id
int friend_id
For each friend relationship I insert 2 records in FRIEND_LIST.
If user 1 is friend of user 2 then the next rows are inserted into FRIEND_LIST
1,2
2,1
I want to get the friends and friends of friends of an specific user.
The select should return columns a, b, c.
a: user_id
b: friend_id
c: username (username of friend_id )
If 1 is friend of 2 and 3.
2 is friend of 3, 4 and 5
3 is friend of 5,6,7
Then the query to get 1's friends and friends of friends should return:
1 2 two
1 3 three
2 1 one
2 3 three
2 4 four
2 5 five
3 1 one
3 5 five
3 6 six
3 7 seven
Can I get this rows with a single query?
I have a query that returns one row. However, I want to invert the rows and columns, meaning show the rows as columns and columns as rows. I think the best way to do this is to use a pivot table, which I am no expert in.
Here is my simple query:
SELECT Period1, Period2, Period3
FROM GL.Actuals
WHERE Year = 2009 AND Account = '001-4000-50031'
Results (with headers):
Period1, Period2, Period3
612.58, 681.36, 676.42
I would like for the results to look like this:
Desired Results:
Period, Amount
Period1, 612.58
Period2, 681.36
Period3, 676.42
This is a simple example, but what I'm really after is a bit more comlex than this. I realize I could produce theses results by using several SELECT commands instead. I'm just hoping someone can shine some light on how to accomplish this with a Pivot Table or if there is yet a better way.
Hello
I have a server with live databases, and I have a test-server where I sometimes restore databases from the live one, to get fresh data. But this way I have to set up all the users again, I have about 4 different users with different permissions that need set again.
Is there some way to do this a better way without using detach and attach, since I cant take the databases offline on the live-server?
Prefered some thing I could run that "re-fills" the tables with fresh data. No need to redo stored procedures and rights.
/M
Hiya,
I dont know if this can be done but i'd though i'd ask.
What I want to do is have a case statement query and if a 1 begin another action. if 0 dont do anything.
For Example
select CASE WHEN client.deathofdeath = yes THEN 1
do another select in here (which is another table)
Else 0 End AS DeathDate
From Client client
Can this be done?
i have a parent report and it contains a two sub report.
* subreport: item
which get all fields from store procedure named spGetReportItem. like
ItemName ItemQuantity TotalItemCost
ab 4 45
dd 6 98
*subreport: Labour
which get all fields from store procedure named spGetReportLabour. like
labourName labourQuantity TotalLabourCost
ab 44 455
dd 63 986
i want to find the total of totalitemcost and total of totallabourcost and then want grandtotal of totalitemcost and totallabourcost.
i have seen many examples on internet in which shared variable is used in the formula bt the problem is that they have used the table but i m fetching data from stored procedure. so how can i access the stored procedure fields for calculation.
like i have seen that many have used:
shared numbervar total:=sum({tablename.ColumnName});
but i have used stored procedure instead of table so how could i find total of field that resultset returns from stored procedure..
plz give me answer as soon as possible..
i need it urgently.
thanks..
I manage a research database with Ruby on Rails. The data that is entered is primarily used by scientists who prefer to have all the relevant information for a study in one single massive table for use in their statistics software of choice. I'm currently presenting it as CSV, as it's very straightforward to do and compatible with the tools people want to use.
I've written many views (the SQL kind, not the Rails HTML/ERB kind) to make the output they expect a reality. Some of these views are quite large and have a fair amount of complexity behind them. I wrote them in SQL because there are many calculations and comparisons that are more easily done with SQL. They're currently loaded into the database straight from a file named views.sql. To get the requested data, I do a select * from my_view;.
The views.sql file is getting quite large. Part of the problem is that we're still figuring out what the data we collect means, so there's a lot of changes being made to the views all the time -- and a ton of them are being created. Many of them need to be repeatable.
I've recently run into issues organizing and testing these views. Rails works great for user interface stuff and business logic, but I'm not aware of much existing structure for handling the reporting we require.
Some options I've thought of:
Should I move them into the most relevant models somehow? Several of the views interact with each other, which makes this situation more complex than just doing a single find_by_sql, so I don't know if they should only be part of the model.
Perhaps they should be treated as a "view" in the MVC sense? (That is, they could be moved into app/views/ and live alongside the HTML, perhaps as files named something like my_view.csv.sql which return CSV.)
How would you deal with a complex reporting problem like this?
I have a table where each row has a start and stop date-time. These can be arbitrarily short or long spans.
I want to query the sum duration of the intersection of all rows with two start and stop date-times.
How can you do this in MySQL?
Or do you have to select the rows that intersect the query start and stop times, then calculate the actual overlap of each row and sum it client-side?
Hey guys,
so I have two tables. They are pictured below.
I have a master table "all_reports". And a user table "user list". The master table may have users that do not exist in the user list. I need to add them to the user list.
The master table may have duplicates in them (check picture). The master list does not contain all the information that the user list requires (no manager, no HR status, no department.. again check picture).
Hi
I have 2 tables A and B with the following columns
Table A - id,bId,aName,aVal
Table B - id,bName
where A.bId is the same as B.id. I want a result set from a query to get
A.id, A.aName, B.bName where A.bId=B.id OR
A.id, A.aName, "" when A.bId=0.
In both cases, only those records should be considered where A.aVal LIKE "aVal"
Can someone please help me with the query? I can use left join but how do I get the blank string if bId=0 and B.bName otherwise?
Thanks
Hi All,
I have a source column with blank (not "NULL"), and target as numeric. while converting using the data conversion it is not converting due to balnk source value so I used derived column to replace a blank value with NULL or 0 as
(source column == " ") ? "0" : source column
but its not giving the value as 0 in the blank place.
thanks
prav