Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a one to many relationship table. I want to get the lowest other\_id that is shared between multiple id's. ``` id other_id 5 5 5 6 5 7 6 6 6 7 7 7 ``` I can do this by building an SQL statement dynamically with parts added for each additional id I want to query on. For example: ``` select * from ( ...
the lowest other\_id shared between all ids ``` select other_id from SomeTable group by other_id having count(distinct id) = 3 order by other_id limit 1 ``` or dynamically ``` select other_id from SomeTable group by other_id having count(distinct id) = (select count(distinct id) from SomeTable) order by other_id li...
i dont have a mysql server to test it out at the moment, but try a "group by" statement: ``` select other_id from SomeTable group by other_id having count(*) > 1 order by other_id asc limit 1 ```
Get lowest shared value in a one to many relationship table
[ "", "mysql", "sql", "" ]
I'm using SQL Server and I need a query that will change a table I'm working with: From this ``` | Band Name | Guitar1 | Guitar2 | Drums | Bass | Vocals | --------------------------------------------------------------------------------- | LedZep | JimmyPage | NULL | NULL | NULL ...
It may depend on what beckend server software you are using, but the basic idea would be: ``` SELECT BandName, MAX(Guitar1) Guitar1, MAX(Guitar2) Guitar2, MAX(Drums) Drums, MAX(Vocals) Vocals FROM Bands GROUP BY BandName ``` However if a band has two records with a value for `Vocals` (or any colu...
Pretty sparse on details here but something this should work. ``` select BandName , MAX(Guitar1) as Guitar1 , MAX(Guitar2) as Guitar2 , MAX(Drums) as Drums , MAX(Bass) as Bass , MAX(Vocal) as Vocals from SomeTable group by BandName ```
Possible to Combine columns on id in sql?
[ "", "sql", "sql-server", "" ]
I currently have the following code ``` select * FROM list WHERE name LIKE '___' ORDER BY name; ``` I am trying to get it so that it only shows names with three or more words. It only displays names with three characters I cannot seem to work out the correct syntax for this. Any help is appreciated Thankyou
If you assume that there are no double spaces, you can do: ``` WHERE name like '% % %' ``` To get names with three or more words. If you can have double spaces (or other punctuation), then you are likely to want a regular expression. Something like: ``` WHERE name REGEXP '^[^ ]+[ ]+[^ ]+.*$' ```
you can count number of words and then select those who are equal or greater then 3 words. ``` SELECT * FROM list HAVING LENGTH(name) - LENGTH(REPLACE(name, ' ', ''))+1 >= 3 ORDER BY name ``` [**DEMO HERE**](http://www.sqlfiddle.com/#!2/ef6c7/3) \*Even if you have multi spaces it will not affect here che...
MySQL SELECT values with more than three words
[ "", "mysql", "sql", "select", "where-clause", "sql-like", "" ]
I've looked around and cannot find an answer to this. As far as I'm aware I'm using this correctly but I'm obviously missing something as it keeps coming back with 'Incorrect syntax near the keyword 'CASE'' I'm trying to take two values, and depending on what 'word' they are return a value of 1-5. These then get multi...
Since you're reusing that `case`, maybe it makes sense to have those values in a table ([fiddle](http://sqlfiddle.com/#!6/5ed90/2)): ``` create table Ratings ( Value int ,Description varchar(20) ) insert Ratings values (1,'Very Low') ,(2,'Low') ,(3,'Medium') ,(4,'High') ,(5,'Very High') ``` And then assign the...
``` DECLARE @PR int DECLARE @IR int DECLARE @R int DECLARE @ProbabilityRating varchar(max) DECLARE @ImpactRating varchar(max) SET @ProbabilityRating = 'High' SET @ImpactRating = 'Medium' set @PR=(CASE @ProbabilityRating WHEN 'Very Low' THEN 1 WHEN 'Low' THEN 2 WHEN 'Medium' THEN 3 WHEN 'High' THEN ...
SQL CASE statement for if
[ "", "sql", "sql-server", "t-sql", "case", "" ]
I have TableA and TableB which contains identical columns but they have different records. How do I find out which "UniqueID" is not in TableA but in TableB? I have been doing ``` select tc.uniqueid, td.uniqueid from tab1c as tc left join tab2c as td where tc.uniqueid != td.uniqueid; ``` but it doesnt seem to be co...
Use left join: ``` select tc.uniqueid, td.uniqueid from tab1c as tc left join tab2c as td on tc.uniqueid = td.uniqueid where td.uniqueid = NULL; --Will get all uid in tab1c and not in tab2c ``` The same efficient and more readability way is `NOT EXISTS`: ``` select tc.uniqueid from tab1c as tc WHERE NOT EXISTS (SELE...
Maybe not the most efficient way but you can use [EXCEPT](http://msdn.microsoft.com/en-US/library/ms188055.aspx) ``` SELECT UNIQUEID FROM tab1c EXCEPT SELECT UNIQUEID FROM tab2c ```
SQL Query to compare columns in different table
[ "", "sql", "sqlite", "" ]
I'm trying to check if a record exists and then update it if it does Here is what I current have: (Which obviously does not work) ``` CREATE PROCEDURE dbo.update_customer_m @customer_id INT , @firstname VARCHAR(30) , @surname ...
Why both checking first? The update will update no rows if the row doesn't exist: ``` UPDATE dbo.Customer SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender, Address1 = @address_1, Address2 = @address_2, City = @city, Phone = @phone, Mobile = @mobile, Email = ...
if block not needed, first select if has no row, Update block do nothing and no row is affected. just write your update in this procedure. but maybe you want to write else if for this procedure, if it's OK, you can you IF and ELSE. in IF block you can write this Update, and in ELSE block you can do another that want.
Stored procedure if record exists then update
[ "", "sql", "asp.net", "sql-server", "stored-procedures", "" ]
I have a `Table1` like this: ``` ApplicableTo IdApplicable --------------------------- Dept 1 Grade 3 section 1 Designation 2 ``` There other tables like: `tblDept`: ``` ID Name 1 dept1 2 baking 3 other ``` `tblGrade`: ``` ID Name 1 Grd1 2 ...
You can use CASE here, ``` SELECT ApplicableTo, IdApplicable, CASE WHEN ApplicableTo = 'Dept' THEN (SELECT Name FROM tblDept WHERE tblDept.ID = IdApplicable) WHEN ApplicableTo = 'Grade' THEN (SELECT Name FROM tblGrade WHERE tblGrade.ID = IdApplicable) WHEN ApplicableTo = 'Sec...
You could do something like the following so the applicable to becomes part of the JOIN predicate: ``` SELECT t1.ApplicableTo, t1.IdApplicable, n.Name FROM Table1 AS t1 INNER JOIN ( SELECT ID, Name, 'Dept' AS ApplicableTo FROM tblDept UNION ALL SELECT ID, ...
Sql select query based on a column value
[ "", "sql", "select", "join", "" ]
I'm struggling with the following thing: I have a table called custom\_fields. Within it there is a field with values like product\_id, money\_spent. When I do an AND query to get data I get 0 results (even though the conditions are met). This is the query: ``` SELECT DISTINCT `users` . * FROM `users` LEFT JOIN `...
Supposing that `custom_fields` is a [EAV-style table](http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model) (i.e. it has multiple entries per one entity like user, in form of a set [entry type, entry label, entry value]), you need to do multiple `JOIN`s with this table to achieve the desired result...
All you seem to want to do is select users for which a product id exists and also a payment value less than 50 exists. So simply use the word EXISTS (that one uses to formulate the task) in your query as well and there are no longer issues with duplicate results. Plus the query is much easier to read, because you use S...
AND statement on same table on values from same field returns 0 results
[ "", "mysql", "sql", "" ]
Are these 2 queries equivalent in performance ? ``` select a.* from a inner join b on a.bid = b.id inner join c on b.cid = c.id where c.id = 'x' ``` and ``` select a.* from c inner join b on b.cid = c.id join a on a.bid = b.id where c.id = 'x' ``` Does it join all the table first then f...
The Query Optimizer will almost always filter table `c` first before joining `c` to the other two tables. You can verify this by looking into the execution plan and see how many rows are being taken by SQL Server from table `c` to participate in the join. **About join order**: the Query Optimizer will pick a join orde...
Read about <http://www.bennadel.com/blog/70-sql-query-order-of-operations.htm> The execution order is FROM then WHERE, in this case or in any other cases I don't think the WHERE clause is executed before the JOINS .
Does inner join order and where as an impact on performance
[ "", "sql", "sql-server", "" ]
I have a table `process` with the fileds `id`, `fk_object` and `status`. example ``` id| fk_object | status ---------------------- 1 | 3 | true 2 | 3 | true 3 | 9 | false 4 | 9 | true 5 | 9 | true 6 | 8 | false 7 | 8 | false ``` I want to find the `id`s of all...
The stock response is as follows... ``` SELECT ... FROM ... WHERE ... IN ('true','false')... GROUP BY ... HAVING COUNT(DISTINCT status) = 2; ``` where '2' is equal to the number of arguments in IN()
This gets the `fk_object` values with that property: ``` select fk_object from process group by fk_object having min(status) <> max(status); ``` You can get the corresponding rows by using a `join`: ``` select p.* from process p join (select fk_object from process group by fk_object having min...
Find IDs of differing values grouped by foreign key in MySQL
[ "", "mysql", "sql", "group-by", "" ]
I have designed a cursor to run some stats against 6500 inspectors but it is taking too long. There are many other select queries in cursor but they are running okay but the following select is running very very slow. Without cursor select query is running perfectly fine. **Requirements:** Number of visits for each i...
No need for a cursor here -- you can use `INSERT INTO` with `SELECT`, joining on the `Inspector` table. ``` INSERT INTO @Report SELECT s.InspectorID , COUNT(distinct v.visitID) from Visits v inner join InspectionScope s on s.ScopeID = v.ScopeID inner join VisitDocs vd on vd.VisitID = v.VisitID ...
Cursors is not recommended any more. It is better for you to insert the data into a temporary table and add a primary key to it. So in your loop you will have a while loop that loops through your table with a WHERE clause on your Id in the temporay table. That is much much more faster.
select query in Cursor taking too long
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I do not understand why the following Oracle 10g SQL query is not working although each sub-query is working fine and fast on its own: ``` SELECT ref.EWO_ISSUE_ID, ref.EWO_REF_ID, ref.MSN_ID, ref.MSN, ref.HOV, ref.RANK, ref.EWO_WP_ID, ref.EWO_WP, ref.EPAC_TDU, ref.MOD, ref.MP, ref.EWO_REF_DESCRIPTION, ewo.EWO1, ewo....
This may not solve your problem, but it will probably force a different execution plan: ``` with x as ( SELECT /*+ materialize */ ref.EWO_ISSUE_ID, ref.EWO_REF_ID, ref.MSN_ID, ref.MSN, ref.HOV, ref.RANK, ref.EWO_WP_ID, ref.EWO_WP, ref.EPAC_TDU, ref.MOD, ref.MP, ref.EWO_REF_DESCRIPTION, ...
You can use NOT EXISTS or NOT IN and check something like this ``` SELECT ref.EWO_ISSUE_ID, ref.EWO_REF_ID, ref.MSN_ID, ref.MSN, ref.HOV, ref.RANK, ref.EWO_WP_ID, ref.EWO_WP, ref.EPAC_TDU, ref.MOD, ref.MP, ref.EWO_REF_DESCRIPTION, ewo.EWO1, ewo.EWO2, ewo.EWO3, ref.TRS_ISSUE, ref.TRS_UPDATE_ON_SHEET_1, ref.TRS...
Oracle SQL query SELECT MINUS SELECT not working or too slow
[ "", "sql", "oracle", "" ]
I know you can change the default value of an existing column like [this](https://stackoverflow.com/questions/6791675/how-to-set-a-default-value-for-an-existing-column): ``` ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn; ``` But according to [this](http://msdn.microsoft.com/en-us/lib...
I think issue here is with the confusion between `Create Table` and `Alter Table` commands. If we look at `Create table` then we can add a default value and default constraint at same time as: ``` <column_definition> ::= column_name <data_type> [ FILESTREAM ] [ COLLATE collation_name ] [ SPARSE ] [ N...
There is no direct way to change default value of a column in SQL server, but the following parameterized script will do the work: ``` DECLARE @table NVARCHAR(100); DECLARE @column NVARCHAR(100); DECLARE @newDefault NVARCHAR(100); SET @table = N'TableName'; SET @column = N'ColumnName'; SET @newDefault = N'0'; IF EXIS...
Alter column default value
[ "", "sql", "sql-server", "default-value", "notnull", "" ]
I have a table like given bellow, in Oracle: ``` [Products] Product_ID | Product_NME | Product_SUP | Quantity ================================================= 1 Apple USA 100 2 Fish Japan 50 3 Wine Italy 10 4 Apple ...
`DISTINCT` is not the clause you are looking for! `GROUP BY` is. The following query will return with all products and the total quantity for each one. ``` SELECT Product_NME , SUM(Quantity) AS TotalQuantity FROM Products GROUP BY Product_NME ```
You don't need for distinct just group by product name : ``` SELECT Product_NME , SUM(Quantity) AS TotalQTY FROM Products GROUP BY Product_NME ```
How to combine SELECT DISTINCT and SUM()
[ "", "sql", "select", "" ]
Here is my code in sql server I have an error saying"The multi-part identifier "t2.isactive" could not be bound." also, I want to do this update in one command and one command only thanks for help ``` UPDATE tb_active_priority_alert SET priority_alert_guid = t2.priority_alert_guid, priority_alert_title = t2.prio...
you can't make it work. the statement: ``` t2.isactive='true' ``` is trying to update a table that is not the one stated in the first row of your statement. update instruction can update data in a single table/object; what you are trying to do is update data in 2 different tables at once and this is not supported...
You have an error in your join with t1. You have to join the two tables on a specific id/value/whatever. try this instead: ``` from tb_users_priority_alerts t2 left join tb_active_priority_alert t1 on t2.priority_alert_guid = t1.priority_alert_guid ``` instead of t2.priority\_alert\_guid =@priority\_alert\_guid
update in sql server with joined table
[ "", "sql", "sql-server", "" ]
I am using the following script to insert 100,000 records into a table. Basically int from 500,001 to 600,000 are inserted. I am casting the integer into a string and inserting coz thats how i want it in the table (an integer in the form of string). I am using a merge to check if the record already exists or not. ``` ...
I am wondering how much your procedural looping and the `MERGE` (instead of a simple `INSERT`) contributes to bad performance. I would opt for a strictly set-based solution like this: ``` INSERT INTO dbo.Identifiers (Identifier) SELECT n FROM dbo.GetNums(500001, 600000) WHERE n NOT IN (SELECT Identifier FROM dbo.Ident...
Try this one. It uses a tally table. Reference: <http://www.sqlservercentral.com/articles/T-SQL/62867/> ``` create table #temp_table( N int ) declare @first as int set @first = 500001 declare @step as int set @step = 1 declare @last as int set @last = 600000 with e1 as(select 1 as N union all select 1), --...
Fastest way to insert 100000 records into SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two tables, one containing a path and the other containing a filename. Here's an example: ``` t1 - file.mov - myfile.txt - 2file.py t2 - /new/path/file.mov - /path/hello.txt - /path/2file.py ``` I want to build a query to get me all the filenames for which I have a path: ``` - file.mov /new/path/file.mov ...
Using an `INNER JOIN` between to 2 tables will allow you to list either or both the file names and paths ``` SELECT names.name, paths.path FROM names INNER JOIN paths ON names.name = SUBSTRING_INDEX(paths.path, '/', -1) ; ``` However the output will be (from the sample): ``` | NAME | PATH | |----...
``` SELECT name FROM names WHERE name in (SELECT SUBSTRING_INDEX(path, '/', -1) FROM paths); ```
SQL name in list of items
[ "", "mysql", "sql", "" ]
[SQL Fiddle](http://sqlfiddle.com/#!6/e1116/1) I'm trying without success to change an iterative/cursor query (that is working fine) to a relational set query to achieve a better performance. What I have: **table1** ``` | ID | NAME | |----|------| | 1 | A | | 2 | B | | 3 | C | ``` Using a function, I w...
if the question is about how to apply a function in a set oriented way, then `cross apply` (or `outer apply`) is your friend: ``` insert into table2 ( id, name ) select t1.id, t2.output from table1 t1 cross apply fn_myExampleFunction(t1.name) t2 ``` [Example SQLFiddle](http://sqlfiddle.com/#!6/...
A query like this will do what you want: ``` insert into table2(id, name) select id, (case when name = 'A' then 'Alice' when name = 'B' then 'Bob' when name = 'C' then 'Foo' end) from table1 union all select id, 'Bar' from table1 where n...
Change an iterative query to a relational set-based query
[ "", "sql", "sql-server", "t-sql", "" ]
I have a master table and detail table like below **Master Table** ``` Id code Name ------------------- 1 00 qqq ``` **Detail Table** ``` Id code Name ------------------- 1 01 xyz 1 02 pqr 1 03 abc 1 04 aaa ``` now I need the result like below **Result** ``` Id ...
Well, I don't know why you don't want to use Union. But you can use [**FULL OUTER JOIN**](http://www.w3schools.com/sql/sql_join_full.asp) for that, if u don't want to use union. something like this - ``` SELECT COALESCE(Master1.id, Detail.id) AS id ,COALESCE(Master1.code, Detail.code) AS code ,COALESCE(Master...
If table is not large enough you can create a temporary table and insert the data from both master and detail by using insert into temp\_table select \* from detail; insert into temp\_table select \* from master; or if you want you can also use undermentioned query to combine data of the table insert into master se...
Join master and detail tables as one table
[ "", "sql", "sql-server", "" ]
This has probably been covered before, but my skill level with SQL is low enough that I'm not even sure how to properly search for what I want! I think what I want to do is relatively simple, and it seems that using pivoting might be the solution, but I'm really not sure about the syntax for that. I have a SELECT que...
Unfortunately MySQL doesn't support windowing functions to generate a unique value for each of those rows per team. You can create a derived "row number" using variables or you could use a correlated subquery similar to: ``` select max(case when teamid = 1 then playername else '' end) Team1, max(case when teamid ...
you cannot do this with a pivot because there is no common ground to pivot off of.. what you can do is make a row count that you join on for the second team.. try this ``` SELECT t.playername as '1', f.playername as '2' FROM ( SELECT @a := @a + 1 as id, playername FROM players WHERE teamid = 1 )t LEFT JOIN...
SQL query to pivot table on column value
[ "", "mysql", "sql", "pivot", "" ]
I am **trying to install and test a MySQL ODBC Connector** on my machine (Windows 7) to connect to a remote MySQL DB server, but, when I configure and test the connection, I keep getting the following error: ``` Connection Failed [MySQL][ODBC 5.3(w) Driver]Access denied for user 'root'@'(my host)' (using password: YES...
Solved. As it turns out, it was a permissions problem. I ran the following command on the remote server SQL: ``` GRANT ALL PRIVILEGES ON *.* TO 'root'@'(my_host)' IDENTIFIED BY '(my_password)'; ``` I had run the previous command, but without the "IDENTIFIED BY" password. Then, to reset the mysql permissions cache, I...
Worked for me too only with 64bit odbc driver not for mySQL 32 bit.
MySQL - ODBC connect fails, Workbench connect works
[ "", "mysql", "sql", "database", "windows", "odbc", "" ]
I have dates in different format : Date 1 : `30-JAN-14` Date 2 : `2014-01-30 10:06:04.0` I am trying to compare the two dates using the following : ``` to_char(date2,'YYYY-MM-DD HH24:MM:SS') <> to_char(date1,'dd-MON-YY') ``` But it is giving the following error for the date1 part : ``` Lietral does not match form...
Probably easiest to use `substr` and truncate the timestamp from the `date2` column. Then you can use `to_date` to compare: ``` select * from sometable where date1 <> to_date(substr(date2,1,10), 'YYYY-MM-DD') ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!4/8302a2/1)
You should be Date type conversion string is the same format for comparison
Compare Dates in different format oracle sql
[ "", "sql", "oracle", "date", "oracle-sqldeveloper", "" ]
Consider this data from TestTable: ![enter image description here](https://i.stack.imgur.com/Boa5c.jpg) I need a view that will provide that most recent beginning StatusDate where IsAssist is true. For example, the most recent StatusDate where IsAssist is true is 2014-05-25. Since the immediately previous records are...
Ok - I managed to figure this out with the help of JL Peyret's response. I had to reverse the parameters for the between statement (when did MS do this? Has it always been this way?). What it does is determine the low date by getting the StatusDate where IsAssist = 0 and is less than the max StatusDate where IsAssist ...
this should give you a good start ``` Select s.tableid, s.StatusDate, e,TableId, e.StatusDate from testable s -- for start left join testable e -- for end on e.statusdate = (Select Min(StatusDate) From TestTable Where StatusDate > s.StatusDate ...
SQL Server View to Return Consecutive rows with a Specific Value
[ "", "sql", "view", "" ]
To lookup a country for a phone number prefix I running the following query: ``` SELECT country_id FROM phonenumber_prefix WHERE '<myphonnumber>' LIKE prefix ||'%' ORDER BY LENGTH(calling_prefix) DESC LIMIT 1 ``` To query phone numbers from a table I run a query like: ``` SELECT phonenumber FROM phonenumbers ``...
You can do this with a correlated subquery: ``` SELECT phonenumber, (SELECT country_id FROM phonenumber_prefix pp WHERE pn.phonenumber LIKE prefix ||'%' ORDER BY LENGTH(calling_prefix) DESC LIMIT 1 ) as country_id FROM phonenumbers pn; ```
This will give you list of numbers with corresponding country ids for the longest matching prefix: ``` SELECT * FROM ( SELECT p.phonenumber, pc.country_id, ROW_NUMBER() OVER (PARTITION BY phonenumber ORDER BY LENGTH(pc.prefix) DESC) rn FROM phonenumber_prefix pc INNER JOIN phonenumbera p ON p.ph...
Lookup table with best match query
[ "", "sql", "postgresql", "" ]
I'm having an UNION Statement with different datatypes and want to sort them. ``` SELECT * FROM (SELECT name, 'P' as 'type', to_char(order_number) as order_type FROM abc UNION ALL SELECT name, 'T' as 'type', to_char(name) as order_type FROM def ) ORDER BY CASE type WHEN 'P' THEN order_type ELSE ord...
Using the constant `'4'` or `4` in the order by doesn't achieve anything; that won't be translated to the column position. Whatever the original data types, the union will present the data from both branches as the same type (determined by the first branch). You've got `to_char(c)` which means `order_type` is a string...
Your column ORDER\_TYPE is a string and will sort as a string, so 11 comes before 2. You want to order those strings coming from table ABC as numbers and those strings coming from table DEF alphabetically. One way could be: ``` ORDER BY CASE type WHEN 'P' THEN lpad(order_type,20,'0') ELSE order_type END ``` That ord...
CAST with different datatypes from UNION Select
[ "", "sql", "oracle", "plsql", "" ]
I am getting the following error when I try and run my package. I am new to ssis. Any suggestions. Tahnks =================================== Package Validation Error (Package Validation Error) =================================== Error at Data Flow Task [SSIS.Pipeline]: "OLE DB Source" failed validation and returne...
VS\_NEEDSNEWMETADATA shows up when the underlying data behind one of the tasks changes. The fastest solution will probably be to just delete and re-create each element which is throwing an error.
How about disabling validation checks? Like if you right click on source or destination component and select properties then you will have the property named validateExternalMetadata put that as false and try. This Solution is working for me.
ssis Package validation error ole db source failed
[ "", "sql", "ssis-2012", "" ]
Here's my associations: ``` class User < ActiveRecord::Base has_many :tickets end class Ticket < ActiveRecord::Base belongs_to :user end ``` Pretty straightforward. I want a scope on the `User` model which returns all users having exactly ZERO associated tickets. Presently I'm using Ruby to do it for the most p...
Maybe something like: `User.includes(:tickets).where(tickets: {user_id: nil})` in a scope it would be like `:without_tickets, -> { includes(:tickets).where(tickets: {user_id: nil}) }`
A SQL subquery could be used, which might be more efficient than using `includes()`: ``` User.where('id not in (select user_id from tickets)') ```
Rails: get parent records having ZERO has_many associations
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "ruby-on-rails-4", "" ]
I am trying to do a simple exercise for slq where i have to get as much info as i can about poeple who work in japan in my database. However i just started learning so i don't even know what to google to answer my problem. So here it is: My Code: ``` SELECT * FROM Employees WHERE DEPARTMENT_ID = (SELECT * FR...
You are using `select *` in your nested selects. You need to select a particular column instead. Something like this: ``` SELECT * FROM Employees WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM Departments WHERE LOCATION_ID IN (SELECT LOCATION_ID FROM Locations WHERE Country_ID...
You cannot use "SELECT \* " inside IN statements. Change your query to this: ``` SELECT * FROM Employees WHERE DEPARTMENT_ID IN (SELECT DEPARTMENT_ID FROM Departments WHERE LOCATION_ID = (SELECT LOCATION_ID FROM Locations WHERE Country_ID = (SELECT Country_ID ...
Error when using nested selects in sql
[ "", "sql", "" ]
I'm newbie in SQL Server and I need some help with SQL Server and JOIN method. My code is: ``` SELECT TOP 1000 p.value AS userposition, p2.value AS usercell, t.id FROM [es] t JOIN [user] u ON t.user_uid = u.uid JOIN [user] su ON u.superior_uid = su.uid JOIN [user_params] up ON t.u...
How about ``` SELECT DISTINCT TOP 1000 p.value AS userposition, p2.value AS usercell, t.id FROM [es] t JOIN [user] u ON t.user_uid = u.uid JOIN [user] su ON u.superior_uid = su.uid JOIN [user_params] up ON t.user_uid = up.user_uid LEFT JOIN [params] p ON up.param_id = p.id AND p.name_id = 1 JOIN [user_para...
all of your columns need to be in the group by, or part of an aggregate function ``` p.value AS userposition, #group by or agg func p2.value AS usercell, #group by or agg func t.id #group by ``` Wouldnt be certain without knowing what p.value and p2.value actually mean
SQL Server : JOIN query
[ "", "sql", "sql-server", "join", "" ]
If I have these tables: ``` Thing id | name ---+--------- 1 | thing 1 2 | thing 2 3 | thing 3 Photos id | thing_id | src ---+----------+--------- 1 | 1 | thing-i1.jpg 2 | 1 | thing-i2.jpg 3 | 2 | thing2.jpg Ratings id | thing_id | rating ---+----------+--------- 1 | 1 | 6 2 | 2 ...
You can get the results you want with a union, which seems the most obvious, since you return a field from either ranking or photo. Your additional case (have none of either), is solved by making the joins `left join` instead of `inner joins`. You will get a duplicate record with `NULL, NULL` in ranking, photo. You ca...
Here's what I came up with: ``` SELECT Thing.*, rp.src, rp.rating FROM Thing LEFT JOIN ( ( SELECT Photo.src, Photo.thing_id AS ptid, Rating.rating, Rating.thing_id AS rtid FROM Photo LEFT JOIN Rating ON 1 = 0 ) UNION ( ...
SQL left join two tables independently
[ "", "sql", "left-join", "" ]
I have a database which I didn't make and now I have to work on that database. I have to insert some information, but some information must be saved in not one table but several tables. I can use the program which have made the database and insert information with that. While I am doing that, I want to see that which ...
I agree with @Lmu92. SQL Server Profiler is what you want. From SQL Server Management Studio, click on the "Tools" menu option, and then select to use "SQL SErver Profiler" to launch the tool. The profier will allow you to see statements executed against the database in real time, along with statistics on these statem...
Although you describe in your question what you want, you don't explain ***why*** you want it. This would be helpful to properly answer your question. [ExpressProfiler](https://expressprofiler.codeplex.com/) is a free profiler that might meet your needs. If you're looking to track DDL changes to your database, rather...
How can I see which tables are changed in SQL Server?
[ "", "sql", "sql-server", "database", "" ]
I was wondering can I change product status to 0 if product\_id has't assigned any category\_id in other table. ``` +------------+----------+ +------------+-------------+ | Product_id | Status | | Product_id | cateogry_id | +------------+----------+ +------------+-------------+ | 1 | 1 | | 1 ...
Simple first you need to get the rows that arent in the table.. table1 is the table with the status table2 is the table with the category id ``` table1 table2 +------------+----------+ +------------+-------------+ | Product_id | Status | | Product_id | cateogry_id | +------------+...
You can use left join in update with is null ``` update product p left join product_relation pr on (p.Product_id = pr.Product_id) set p.Status = 0 where pr.Product_id is null ``` [**Demo**](http://sqlfiddle.com/#!2/006a0/1)
MYSQL update join is null
[ "", "mysql", "sql", "" ]
I have a table like this - ``` C1 C2 C3 A 20130101 10 A 20130102 10 A 20130103 20 A 20130104 10 ``` I want to set row no like this - ``` C1 C2 C3 RowNo A 20130101 10 1 A 20130102 10 2 A 20130103 20 1 A 20130104 10 1 ``` How can I make by query? o...
I am updated answer with recursive CTE. It build hierarchy tree starting with records with new C3's value and display level as RowNo. ``` with t as (select t.*, row_number () over (order by c2) rn from table1 t) ,temp (c2,c3,rn,lvl) AS (SELECT c2,c3,rn,1 lvl from t t1 where not exists( ...
ROW\_NUMBER() function can help you to set numbers of rows: ``` SELECT ROW_NUMBER() over(order by [some field]), * FROM [your table] ```
How to set row number()
[ "", "sql", "sql-server-2008", "" ]
Having the following tables: * "TypeSomething (ID, NAME) -- 2 Entries - Id 1 and 2" * "OtherThings (ID, NAME) - 3 entries - Id 10,20,30" What is the easiest way to retrieve the following SQL result: TypeId, OtherThingId: (1, 10)(1, 20)(1, 30)(2, 10)(2, 20)(2, 30) Thanks...
It's a *cartesian join*: ``` select t.id TypeId, o.id OtherThingId from TypeSomething t cross join OtherThings o ``` I've added `cross join` which is not required by *SQL 92 standard*, in order to stress out that the query is not a *typical error* when *join is just left*.
Looks like you just want a cross join (also called a cartesian product): ``` SELECT t.ID TypeId, o.ID OtherThingId FROM TypeSomething, OtherThings ```
How to "project" 2 tables
[ "", "sql", "" ]
I have some fields in the table, need to average those fields. Then I run this syntax, because I don't want to calculate 0 (zero) value. ``` SELECT myDate, AVG(CASE myField1 WHEN 0 THEN NULL ELSE myField1 END) AS avgmyField1 FROM myTable WHERE myDate = '2014-06-01' ``` On my syntax, the average calculation means.. M...
Then you get NULL. If you want zero instead, use COALESCE: ``` COALESCE( AVG(CASE myField1 WHEN 0 THEN NULL ELSE myField1 END) , 0) ```
Average will not use nullvalues to calculate an average value IsNull or Coalesce can be used to change null values to different values. This script will change 0 to null and take the average value: ``` SELECT IsNull(AVG(NullIf(val,0)), 0) FROM (Values(5),(7),(0)) tbl(val) ``` Since 0 is excluded the result is 6
Average without calculate zero
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have 2 strings , let's suppose stringA and stringB . I want to know if stringA contains stringB. Since I am new to SQL Server and T SQL. I am not sure what prebuild function can I use . It should be something like this. ``` If (contains(stringA,stringB)) ``` then Print `'It Contains it'`
``` DECLARE @StringA VARCHAR(100) DECLARE @StringB VARCHAR(100) SET @StringA = 'ABCDEF' SET @StringB= 'CD' IF @StringA LIKE '%' + @StringB + '%' Print 'It Contains it' ELSE PRINT 'It doesn''t' SET @StringA = 'ABCDEF' SET @StringB= 'WU' IF @StringA LIKE '%' + @StringB + '%' Print 'It Contains it' ELS...
You can use [`LIKE`](http://msdn.microsoft.com/en-us/library/ms179859.aspx): ``` SELECT t.* FROM dbo.Table t WHERE stringA LIKE '%' + @stringB + '%' ``` or with an `IF`: ``` IF @stringA LIKE '%' + @stringB + '%' PRINT 'It contains it' ELSE PRINT 'It does not contain it'; ```
How to check if string A "contains" B in TSQL?
[ "", "sql", "sql-server", "t-sql", "" ]
How to check if a stored procedure or query is still running in SQL Server? **Ideas** 1. I've thought of having a log where to write when the procedure starts and delete when it ends. *Flaws:* * it leaves open the case when the server restarts or some kind of failure inside the procedure. * this method nee...
You might query `sys.dm_exec_requests` which will provide sesion\_ID, waittime and futher rows of interest and CROSS APPLY `sys.dm_exec_sql_text` filtering your query with the SQL for your procedure. ``` Select * from ( SELECT * FROM sys.dm_exec_requests where sql_handle is not null ) a CROSS APPLY sys.dm_exec_sql_...
**Update:** The answer given by John Clayton references the [outdated SQL Server 2000 system table](https://learn.microsoft.com/en-us/sql/relational-databases/system-tables/mapping-system-tables-to-system-views-transact-sql?view=sql-server-2017) (sys.sysprocesses). The updated SQL is: ``` SELECT object_name(st.objec...
Check if stored procedure is running
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have simple categories table. Category can have parent category (`par_cat` column) or null if it is main category and with the same parent category there shouldn't be 2 or more categories with the same name or url. Code for this table: ``` CREATE TABLE IF NOT EXISTS `categories` ( `id` int(10) unsigned NOT NULL, ...
This works as defined by the SQL standard. NULL means unknown. If you have two records of par\_cat = NULL and name = 'X', then the two NULLs are not regarded to hold the same value. Thus they don't violate the unique key constraint. (Well, one could argue that the NULLs still *might* mean the same value, but applying t...
I see that this was asked in 2014. However it is often requested from MySQL: <https://bugs.mysql.com/bug.php?id=8173> and <https://bugs.mysql.com/bug.php?id=17825> for example. People can click on affects me to try and get attention from MySQL. Since MySQL 5.7 we can now use the following workaround: ``` ALTER TABLE ...
Unique (multiple columns) and null in one column
[ "", "mysql", "sql", "database", "unique-constraint", "" ]
I have string "this is my test string" and I want to remove only word "my". The problem is word "my" will select from another query as ``` select word from table ``` I tried this if I know the word ``` set string = REPLACE(string,'my',''); ``` So, any help I want to do something like ``` set string = REPLACE(st...
`select replace(@test,word,'') from test`; ... ``` select @test:=replace(@test,word,'') from test; ``` However keep in mind that you have multiple entries in the test table, @test will end up with all the words in table test replaced with ''. If that is what you want then all okay. If you want a list output with @...
Maybe there's a better way but try this procedure ``` CREATE PROCEDURE myProc(IN teststring VARCHAR(255), OUT teststring_new varchar(255)) BEGIN DECLARE n INT DEFAULT 0; DECLARE i INT DEFAULT 0; SELECT COUNT(*) FROM test INTO n; SET teststring_new = teststring; SET i=0; ...
How to delete specific word from string in mysql?
[ "", "mysql", "sql", "mysql-workbench", "" ]
I'm working the Oracle Developer days demo VM (virtualBox ), and I can't seem to find the password for the SQL\*plus, so I go ahead and log into it like so ``` sqlplus sys/sys_password as sysdba ``` I need to run some oracle memory management tests (REDO logs and creating archive logs, etc). Is this a risky plan tho...
If you're just on a virtualbox vm I can't imagine any risk at all but it isn't best practice to operate as sysdba in a production environment (or any environment that you really care about). Also all passwords for dev days are usually oracle. You could always change them by going in as sysdba and executing: `alte...
The default password for all accounts in oracle developer day vm is 'oracle'. Best practice is , you can create dba account and use that account to do your oracle memory management tests. To create dba follow step 5 in following link <http://praitheesh.blogspot.com.au/2013/10/oracle-developer-day-vm-how-to-use-pre.h...
Regarding logging into SQL*PLUS as sysdba versus regular user?
[ "", "sql", "oracle", "virtualbox", "sqlplus", "" ]
I have two tables Like A and B. Each have one column (ID) in **ascending order**. I want to join tables LIKE C Table. Datas are not statical but in A and B the row counts are always equal. I've tried join statements but couldn't find out. Thanks for your help. ``` A (ID) -- 2 3 4 6 8 B (ID) -- 11 12 13 14 15 C ( IDA...
If you're using a database that supports row\_number() such as Oracle, postgresql, sql sql server: ``` select a_id, b_id from (select row_number() over(order by id) as a_rn, id as a_id from a) x join (select row_number() over(order by id) as b_rn, id as b_id from b) y on x.a_rn = y.b_rn ``` **Fiddle:** <http:...
Try this: ``` select a.id ida,b.id idb from ( select a.*, row_number() over (order by id) rn from a) a join (select b.*, row_number() over (order by id) rn from b) b on a.rn=b.rn ```
Join Two Non Related Tables
[ "", "sql", "t-sql", "" ]
Suppose I want to find, for two tables A and B, the counts of all records that are in A but not B, all records that are in A and B, and all records that are in B but not in A. I don't want the actual records, just the counts of all 3 components (think of a Venn diagram). When I say, for example, records in A and B, I ...
For all that are in A and B, it's a simple JOIN: ``` SELECT COUNT(*) FROM A JOIN B ON A.ID = B.ID AND A.Year = B.Year AND A.Month = B.Month AND A.Day = B.Day ``` Note that this assumes that the combination `(ID, Year, Month, Day)` is unique in each table; if there are duplicates, it will count all the cross-products ...
You can use `union` (which automatically removes duplicates) to get a master table of all unique rows and left join that table to tables a and b to get your counts. This assumes that tables a and b don't contain duplicates within the table (otherwise the left joins will produce inflated counts). ``` select count...
How to get counts for all 3 components of two tables using SQL?
[ "", "mysql", "sql", "" ]
I have the following two tables: **CashRegister** ``` Date PaymentId CustId VenId Debit Credit Date ========================================================= 2/2/12 Pay_1 Cus_1 444 3/2/2012 4/2/12 Pay_2 Ven_1 555 ``` **SalesOrder** ``` SaleOrderId CustId Debit Cre...
It seems like you want to use either CustId or VenId from the CashRegister table, and if so I think this is what you want: ``` SELECT Date, PaymentId AS TrId, COALESCE(CustId, VenId) AS AccountId, -- COALESCE returns the first Debit, -- non null value as AccountId ...
To correct *your query* you have to add *stub columns* (`null` is usual stub value), e.g. ``` select * from (select Date, PaymentId TrId, CustId AccountId, VenId, Debit, Credit from CashRegister ...
How do I select columns from two tables with differing layouts
[ "", "sql", "sql-server", "union", "" ]
Is there any way to find the largest value for any column or any data type in a table? Let me eleaborate on this a bit more. If i have a table with 10 columns and some columns have datatype int, and some have decimal data type. Is there any sql function to get the largest 'numerical' value from that table? ``` P_ID ...
Try this, unfortunately you have to list all the columns. Would be easier if they were same type: ``` SELECT max(val) FROM (SELECT CAST(p_id as decimal(11,2)) p_id, CAST(Price as decimal(11,2)) Price, CAST(Quantity as decimal(11,2)) Quantity FROM yourtable) as p UNPIVOT (val FOR Seq IN ([p_id]...
Well, you could use a combination of selecting from syscolumns and systypes. Systypes gives you a length and precision which could be used to give the information you want ?
Is there any way to find the largest value for any numeric column over all in a table?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table with five years worth of data. It has, among other values, `JulianDate`, `RefETo`, and `Precipitation`. I need to get the average of RefETo over that five years and the average of the last year, plus the sum of precipitation over the last year. At the same time the averages and sums have to be for a pe...
I agree with [PM 77-1](https://stackoverflow.com/users/2055998/pm-77-1) in the comments. Conditional aggregation is the way to go. Try this: ``` Declare @Stn INT, @Yr INT, @Period INT Select @Stn = 80, @Yr=2014, @Period=28 SELECT Period, RefETo/RefEToDays AS RefETo, RefETo1/RefETo1Days AS RefETo1, Precipitation FRO...
> I need to get the average of RefETo over that five years and the > average of the last year, plus the sum of precipitation over the last > year. From where I sit, this is a perfect example of a requirement that should be implemented in the report writer, not in the dbms. I would not do this in a single SQL statemen...
A way to get averages over a period of days
[ "", "sql", "sql-server", "" ]
The site produces results, but with SELECT COUNT and SELECT query with GROUP BY having two different result counts. This is likely due to the error that is displaying in phpmyadmin but not on the site. **The Queries:** ``` SELECT count(DISTINCT `name`) as `numrows` FROM `users` WHERE `verified` = '1' SELECT `name`, ...
You need to have a full group by: ``` SELECT `name`, `type`, `language`, `code` FROM `users` WHERE `verified` = '1' GROUP BY `name`, `type`, `language`, `code` ORDER BY `count` DESC LIMIT 0, 25 ``` SQL92 requires that all columns (except aggregates) in the select clause is part of the group by clause. SQL99 loose...
The best solution to this problem is, of course, using a complete `GROUP BY` expression. But there's another solution that works around the `ONLY_FULL_GROUP_BY` blocking of the old MySQL extension to `GROUP BY`. ``` SELECT name, ANY_VALUE(type) type, ANY_VALUE(language) language, ANY_VALUE(code)...
MySQL : isn't in GROUP BY
[ "", "mysql", "sql", "phpmyadmin", "mysql-error-1055", "" ]
I have created a database in SQL Server 2012 with mdf and ldf pointing to a external hard drive attached to my machine. I created tables, stored procedures, populated tables, etc. etc. I removed the hard drive at the end of the day. Today, when I attached the hard drive and tried to access the DB in Management Studio,...
When you removed the drive, you forcefully disconnected the database from the SQL Server service. SQL Server does not like that. SQL Server is designed by default so that any database created is automatically kept open until either the computer shuts down, or the SQL Server service is stopped. Prior to removing the dr...
What worked for me was to take the database offline\*, then back online - *no RESTORE DATABASE was necessary* in this case, so far as I can tell. In SQL Server Management Studio: 1. right-click on the database 2. select Tasks / Take Offline ... breathe deeply, cross fingers... 3. right-click on the database again 4. ...
MSSQL database on external hard drive shows Recovery Pending
[ "", "sql", "sql-server", "" ]
So I'm trying to insert 3 rows into 2 different tables by doing this: ``` INSERT INTO GAMES.ATHLETE (ATHLETE_NO, ATHLETE_NAME, ATHLETE_BIRTHDATE, ATHLETE_BIRTHPLACE, ATHLETE_BORN_COUNTRY, ATHLETE_GENDER, ATHLETE_HEIGHT, ATHLETE_WEIGHT, ATHLETE__TEAM_COUNTRY) VALUES ('12345', 'Saif Haseeb', '08-NOV-1995', 'Clayton', 'A...
These are three Statements, but you forgot to end each with a semicolon.
Oracle doesn't let you type `insert into ... values (...),(...)` like PostgreSQL does you need to split it into several inserts: ``` INSERT INTO GAMES.ATHLETE (ATHLETE_NO, ATHLETE_NAME, ATHLETE_BIRTHDATE, ATHLETE_BIRTHPLACE, ATHLETE_BORN_COUNTRY, ATHLETE_GENDER, ATHLETE_HEIGHT, ATHLETE_WEIGHT, ATHLETE__TEAM_COUNTRY) V...
"SQL command not properly ended" (Oracle SQL)
[ "", "sql", "oracle", "" ]
I have following data in MySQL table named info: ``` chapter | section 3 | 0 3 | 1 3 | 2 3 | 3 4 | 0 5 | 0 ``` I would like to delete a row for chapter = n, but only when there is no section>0 for same chapter. So chapter 3 can't be deleted while chapter 4 and 5 can. I know the fo...
You've got the idea right. Here is the syntax: ``` DELETE FROM mytable WHERE chapter NOT IN ( SELECT * FROM ( select tt.chapter from mytable tt where tt.section <> 0 group by tt.chapter ) tmp ) ``` The nested select is a workaround a bug in MySQL. [Demo.](http://sqlfiddle.com/...
**You can run a sub query to return the rows that have sections of more then one and then delete the rows returned from the sub query.** --- `DELETE FROM table1 WHERE table1.chapter Not IN (select chapter from (SELECT table1.chapter FROM table1 WHERE Table1.section >=1 ) Results);` --- [Example Fiddle based on your...
How to delete a row where there are only one of the kind in MySql?
[ "", "mysql", "sql", "" ]
How can I get result like below with mysql? ``` > +--------+------+------------+ > | code | qty | total | > +--------+------+------------+ > | aaa | 30 | 75 | > | bbb | 20 | 45 | > | ccc | 25 | 25 | > +--------+------+------------+ ``` **total** is value of the rows and ...
You can do this with a correlated subquery -- assuming that the ordering is alphabetical: ``` select code, qty, (select sum(t2.qty) from mytable t2 where t2.code >= t.code ) as total from mytable t; ``` SQL tables represent unordered sets. So, a table, by itself, has no notion of rows co...
I would use join, imho usually fits better. Data: ``` create table tab ( code varchar(10), qty int ); insert into tab (code, qty) select * from ( select 'aaa' as code, 30 as qty union select 'bbb', 20 union select 'ccc', 25 ) t ``` Query: ``` select t.code, t.qty, sum(t1.qty) as total from tab t join tab...
Mysql each row sum
[ "", "mysql", "sql", "" ]
I have a History table (like a log) that records changes to parts: ``` TransactionID Part ID Description Last Updated 1 1 Fixed O-ring 2006-03-14 20:00:04.700 2 2 Replaced coil 2009-01-02 20:00:04.700 3 1 ...
``` SELECT TransactionID ,PartID ,[Description] ,[Last Updated] FROM ( SELECT TransactionID ,PartID ,[Description] ,[Last Updated] ,ROW_NUMBER() OVER (PARTITION BY [PartID] ORDER BY [Last Updated] DESC) RN FROM TableName )A WHERE A.RN = 1 ``` Or yo...
``` select TransactionID, PartID, Description, LastUpdated from History H where LastUpdated = ( select max(LastUpdated) from History where PartID = H.PartID ) ```
Get the latest date for each record
[ "", "sql", "sql-server", "stored-procedures", "greatest-n-per-group", "" ]
Facing issue to find the Min and Max pricing status on the column YearMonth, Below is my table data ``` YearMonth STATE ProductGroup LocaProdname Price 201407 MH AIRTEL AIRTEL-3G 10,000 201208 GJ IDEA IDEA-3G 1,200 201406 WB AIR...
Please use Row\_number with partition BY and remove unwanted code as per your need, ``` SELECT yearmonth,state,productgroup,locaprodname,price,operation FROM ( SELECT * FROM (SELECT p.yearmonth,p.state,p.productgroup,p.locaprodname,p.price,'MAX' AS Operation, Row_number() OVER( p...
If I understand correctly, you can do this with `row_number()`: ``` select YearMonth, STATE, ProductGroup, LocaProdname, Price, (case when seqnum_asc = 1 then 'MIN' else 'MAX' end) as Indicator from (select d.*, row_number() over (partition by state, productgroup, localprodname ...
SQL query for Pricing analysis
[ "", "sql", "sql-server-2008", "aggregate-functions", "greatest-n-per-group", "" ]
What would be the suggested way (if even possible) to call MSSQL SP from Node.js. The documentation <https://www.npmjs.org/package/mssql> is great but there is no mention of SP (stored procedure) anywhere.
The [linked document](https://www.npmjs.org/package/mssql) does actually mention stored procedures: ``` var request = new sql.Request(connection); request.input('input_parameter', sql.Int, 10); request.output('output_parameter', sql.VarChar(50)); request.execute('procedure_name', function(err, recordsets, ...
It's getting better with ES6/7 additions to JS. This is how you can do it with [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function): ``` async function getDataFromProcedure(dbConfig, procedureName) { try { await sql.connect(dbConfig); const request = n...
Node.js and MSSQL stored procedures
[ "", "sql", "sql-server", "node.js", "" ]
I have a 24-hour store and I have a bunch of data points for customer entry and exit timestamps. I want to know how many customers were in the store at any given time. My data looks like: ``` CREATE TABLE Events (CustomerID INT, EventDTS DATETIME2, Delta INT); ``` Delta is always either 1 or -1 and represents the ch...
You are using SQL Server 2012, so you can use cumulative sum. That makes this easy: ``` select ewp.*, sum(Delta) over (order by EventDTS) as Population from EventsWithPopulation ewp; ``` This will give you the population at the instant after any event occurred. EDIT: The above looks a bit strange when there ...
Gordon's answer will list the population for each event. If you want to give it a time and get the population, just sum the delta between midnight and now. ``` declare @mydate DateTime set @mydate = GetDate() Select sum(delta) + 1 from EventsWithPopulation where EventDTS between DateAdd(Day, Datediff(Day,0,@myd...
Calculate a running count (store population) in SQL using entry and exit timestamps
[ "", "sql", "sql-server", "" ]
I am using SQL Server. I want to select multiple columns with only one distinct column. For example, TABLE 1: ``` ID NAME ...(other columns) 1 A 2 B 3 C ``` Table 2 (ID and number together is the unique key): ``` ID Number Year...(other columns) 1 111 2011 2 123456...
You can use `not exists` to only select the latest rows per id (where another row with the same id and a greater year does not exist). ``` select * from table1 t1 where not exists ( select 1 from table1 t2 where t2.id = t1.id and t2.year > t1.year ) ``` using analytic functions (this should be faster than...
``` WITH CTE AS ( SELECT t1.ID, t1.NAME, t2.NUMBER, t3.COMPANY, t2.Year, Row_number() OVER(partition BY t1.ID, t1.NAME, t2.NUMBER, t3.COMPANY ORDER BY t2.Year DESC) AS rn FROM table1 t1 LEFT JOIN table2 t2 ON t1.ID = t2.ID LEFT JOIN table3 t3 ON t1.name = t3.name ) SELECT ID, NAME, NUMBER, COMPANY...
sql - how to select multiple columns with only one distinct column from joining multiple tables
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm using Oracle SQL. I have column with values of `String` type, that actually supposed to be a currency. The strings values are in the following format: ``` 103,2 % ``` I need to convert it to: ``` 103.2 ``` Aldo i need to convert the values type to `Float`. Is there's a good conversation functions that can hel...
How about something like this? ``` select cast(translate(col, ', %', '.') as float) ```
You can use `replace` to strip out the fixed `%` part, which changed `103,2 %` to `103,2`; and pass the result of that into `to_number()`. Since you seem to have a comma decimal separtator in the value and period in the databse you can specify the NLS\_NUMERIC\_CHARACTERS: ``` select to_number(replace('103,2 %', ' %')...
Converting string to currency value
[ "", "sql", "oracle", "" ]
I have these tables, Orders Table: ``` Name Null? Type ORDER_ID NOT NULL NUMBER(5) CUSTOMER_ID NUMBER(8) SHIPMENT_METHOD_ID NUMBER(2) ``` and Shipment\_method Table: ``` Name Null? Type SHIPMENT_METHOD_ID NOT NULL NUMBER(2) SHIPMENT_DESCRIPTION VARCHAR2(80)...
This is another approach: ``` select shipment_method_id, shipment_description, count(*) as num_orders from orders join shipment_method using (shipment_method_id) group by shipment_method_id, shipment_description having count(*) = (select max(count(order_id)) from orders g...
Here is a method that allows for more than one Shipment Method having the same maximum number of Orders. ``` SELECT shipment_method_id ,shipment_description ,orders FROM (SELECT shipment_method_id ,shipment_description ,orders ,rank() OVER (ORDER BY orders DESC) orders_rank...
Max value of count in oracle
[ "", "sql", "oracle", "" ]
> I have the following table. ![enter image description here](https://i.stack.imgur.com/4GH2L.jpg) I need to select SemesterID,AcadamiYear,AcademicSemester of the record with highest Academic year and Academic semester of the year 2015 Expected output is > 2013 1 2 I tried the following query but it returns both o...
Since you are searching for a single record you might use TOP 1, ordered by your intend ``` select TOP 1 * from tblSemesterRegistration where [IntakeYear]='2015' Order by AcadamiYear DESC, AcadamicSemester DESC ```
This is the query you're looking for: ``` SELECT SR.* FROM tblSemesterRegistration SR INNER JOIN (SELECT MAX(SR2.AcadamiYear) AS [AcadamiYear] ,MAX(SR2.AcadamicSemester) AS [AcadamicSemester] ,IntakeYear FROM tblSemesterRegistration SR2 GROUP BY SR2.IntageYea...
Select Max with groupby
[ "", "sql", "sql-server", "" ]
I have a table called calendar with only one column Date\_I (type Date). Now the requirement is to create a plsql function insert\_data which takes start\_date and end\_date. This function will now check if each and every date between start\_date and end\_date is presented in the table calendar. If not then insert that...
As a more concrete example of the `MERGE` approach already suggested: ``` PROCEDURE Insert_Data(Start_Date DATE, End_Date DATE) IS BEGIN MERGE INTO calendar ca USING ( SELECT Insert_Data.Start_Date + level - 1 as cal_date FROM dual CONNECT BY level <= Insert_Data.End_Date - Insert_Data.Start_Date + 1 ...
Try inserting values in to your table using [MERGE](http://www.oracle-base.com/articles/9i/merge-statement.php) ``` MERGE INTO calendar ca USING (SELECT * FROM calendar WHERE < your sql condition> )qry ON (ca.<your_primary_key> = qry.<your_primary_key>) WHEN NOT MATCHED THEN INSERT IN...
Loop through date range and insert when no data found
[ "", "sql", "database", "oracle", "plsql", "" ]
I have attached my code below for your review. My error is coming with the 4th CASE statement where I am using math functions to calculate information. Does anyone know what is causing the error and how to get around it? I'm guessing that the issue is in my ORDER BY function at the end. ``` SELECT H.DATE AS "DATE" ,TR...
The issue is that you are trying to reference both individual and aggregated `Q.AMOUNT` values in the SELECT. If I understand your intention correctly, you probably meant to do this with your fourth CASE: ``` Y.CHGS - (COALESCE(SUM(Q.AMOUNT), 0) + Z.AMOUNT) AS "LL" ``` If every `Q.AMOUNT` in a group is NULL, `SUM(Q...
In fourth case there is no use of using an extra `SUM` function. Try somthing like this:- ``` CASE WHEN Q.AMOUNT IS NULL THEN (Y.CHGS - Z.AMOUNT) WHEN Q.AMOUNT IS NOT NULL THEN (Y.CHGS - Q.AMOUNT + Z.AMOUNT) ELSE '' END AS "LL" ``` Hope this is helpful to you.
"INVALID USE OF AN AGGREGATE FUNCTION OR OLAP FUNCTION" ERROR IN DB2
[ "", "sql", "db2", "" ]
I have a customer database which include LMD(Last Modified Date) data type is date and LMT(Last Modified Time) data type is int. I need to create a datetime from this LMD and LMT column. Here are the rows, ``` LMD LMT 2014-09-03 172351 ```
You might use divsion and modulo to extract the needed parts for DATEADD ``` declare @datefield date declare @timefield int set @datefield='20140910' set @timefield=121314 Select CAST(@datefield AS DATETIME) + DATEADD(HOUR,@timefield/10000,0) + DATEADD(MINUTE,@timefield/100 % 100,0)+ DATEADD(SECOND,@timefield % 100,...
This works using `TIMEFROMPARTS` and adding it to the date. **[SQL Fiddle Demo](http://sqlfiddle.com/#!6/3dc52/1)** ``` select cast(LMD as datetime) + cast(timefromparts(substring(cast(lmt as varchar), 1, 2), substring(cast(lmt as varchar), 3, 2), substring(cast(lmt as varchar), 5, 2),0,0) as datetime) from yourTable...
How to combine separate Date and Time columns into DateTime?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I want to add a column to my table with a random number using seed. If I use RAND: ``` select *, RAND(5) as random_id from myTable ``` I get an equal value(0.943597390424144 for example) for all the rows, in the random\_id column. I want this value to be different for every row - and that for every time I will pass i...
So, in case it would someone someday, here's what I eventually did. I'm generating the random seeded values in the server side(Java in my case), and then create a table with two columns: the id and the generated random\_id. Now I create the view as an `inner join` between the table and the original data. The generate...
I think the simplest way to get a repeatable random id in a table is to use `row_number()` or a fixed `id` on each row. Let me assume that you have a column called `id` with a different value on each row. The idea is just to use this as a seed: ``` select rand(id*1), as random_id from mytable; ``` Note that the seed...
SQL Server random using seed
[ "", "sql", "sql-server", "random", "random-seed", "" ]
I work on a MySQL database table that has a column containing timestamps (Ex. 2014-09-16 09:08:05) of the time I ping different hosts. My question is how could I calculate in minutes the difference between the first ping and the last one for specific hosts? Also how could I specify different timestamps for the start an...
You could use the native [TIMESTAMPDIFF](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff) function : ``` SELECT TIMESTAMPDIFF(<INTERVAL>,<timestampFrom>,<timestampTo>); ``` If you want to find the difference between the first and the last timestamp of a given host ID, here y...
If you want to use in SQL syntax: ``` SELECT DATEDIFF(minute,'2008-11-30','2008-11-29') AS DiffDate ``` In addition to minute, you can use day as well.
Calculate the time difference between two timestamps in mysql
[ "", "mysql", "sql", "database", "time", "" ]
Heres what i have **Query** ``` with temp as ( select 11 as x from dual union select 222 as x from dual ) select x from temp t,(SELECT 1 FROM DUAL CONNECT BY ROWNUM <= 3) ``` **Output** ``` X -- 11 222 11 222 11 222 ``` **Output i desire** ``` X -- 11 11 222 222 222 ``` basically i woul...
This works: ``` with temp as ( select '11' as x from dual union select '222' as x from dual ) SELECT x, LEVEL from temp t CONNECT BY LEVEL <= LENGTH(t.x) and prior x = x and prior sys_guid() is not null; ``` Last line does the trick. Same can be achieved with other reference to PRIOR: ``` with temp as ( s...
Since you're on 11g you can use [recursive subquery factoring](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm#sthref6730) to achieve this: ``` with t as ( select 11 as x from dual union all select 222 as x from dual ), r (x, idx, len) as ( select x, 1, length(x) from t union a...
Repeat rows dynamically in Oracle based on a condition
[ "", "sql", "oracle", "oracle11g", "connect-by", "" ]
I have table with following structure: ![enter image description here](https://i.stack.imgur.com/2LUHU.png) And I'm trying to get grouped values between two dates, problem is, that i would like to have also retuned rows for dates which are not in select, for example i have range for ``` WHERE m.date BETWEEN "2014-09...
Try this: ``` SELECT d.date AS DATE, IFNULL(NUMBER_OF_ALL_CALLS, 0) AS NUMBER_OF_ALL_CALLS, IFNULL(RESULT_DONE, 0) AS RESULT_DONE, IFNULL(RESULT_NOT_INTERESTED, 0) AS RESULT_NOT_INTERESTED, IFNULL(RESULT_NO_APP, 0) AS RESULT_NO_APP FROM (SELECT DATE('1970-01-01', '+' || (t4.i*10000 + t3.i*1000 + t2.i*...
This is a good case for joining to a Calendar table. <http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html> Note this is a SQL server link, but you can adapt this to SQLlite. You could do your calculations, and then right join...
How to get missing values in date range?
[ "", "sql", "date", "range", "between", "" ]
Simplified I have two tables in MySQL: One holding a sort of person entity and one relation table which associates multiple rights two the person entity. The tables look like: person ``` person_id | person_name 1 | Michael 2 | Kevin ``` person2right ``` person_id | right_id 1 | 1 1 |...
This will only select persons (and all their associated rights) who have both rights 1 and 4. Note that it's different from your query in that your query selects all persons (regardless of their rights) and only selects their associated rights if they have rights 1 and 4. ``` SELECT person_name, GROUP_CONCAT(`person2r...
Let's see if additional joins can do the trick: ``` select person_name, group_concat(distinct p2r.right_id) as all_rights from person as p inner join person2right as p2r using (person_id) -- You don't need LEFT JOIN, because you'll only return persons with rights -- The new stuff starts here: Two new LEFT JO...
Most efficient way in MySQL to get all associated values from a relation table while filtering after the same values
[ "", "mysql", "sql", "" ]
I'm trying to execute a query who generates inserts statements, like that : ``` select 'insert into MYTABLE ( ID, COLUMN_A, COLUMN_B) values (' + ID + ',' + COLUMN_A + ',' + COLUMN_B as INSERTGENERATOR from MYTABLE; ``` But I have this error : ``` ORA-01722: invalid number 01722. 00...
Don't put end of lines within quotes. And `||` is used to concatenate. ``` select 'insert into MYTABLE (ID, COLUMN_A, COLUMN_B) values (' || ID || ',' || COLUMN_A || ',' || COLUMN_B || ');' as INSERTGENERATOR from MYTABLE; ```
This works: ``` SELECT 'INSERT INTO MYTABLE (ID, COLUMN_A, COLUMN_B) VALUES (' || ID || ',' || COLUMN_A || ','|| COLUMN_B || ');' AS INSERTGENERATOR FROM MYTABLE; ``` [Sample SQL Fiddle](http://www.sqlfiddle.com/#!4/be2cc/4)
Query who generates insert statements : invalid number
[ "", "sql", "oracle", "" ]
I'm new to SQL and trying to find the correct join to use in this situation. Table A contains a series of unique (i.e. no repeats) IDs. Table B contains multiple measurements for each ID, including IDs that don't exist in table A. I need a combined table that contains all the data in table B for the IDs that are in tab...
``` SELECT A.ID ,B.[Count] ,B.[Date] FROM TableA A INNER JOIN TableB B ON A.ID = B.ID ``` **INNER JOIN** will give you the matching rows between Two tables. **RIGHT JOIN** will give you matching rows from the table on left side of join key word and all rows from the table on right side of the join key w...
Inner join is the one you are looking for As for your questions. If I understood it correctly, then the answer is no. Left join would be an inner join + anything that LHS table has but not in the RHS, it will fill in the blank with null, similarly for Right join.
SQL join to retrieve multiple lines in right table
[ "", "sql", "join", "left-join", "right-join", "" ]
Being new with SQL and SSRS and can do many things already, but I think I must be missing some basics and therefore bang my head on the wall all the time. A **report** that is almost working, **needs to have more results** in it, based on conditions. My working query so far is like this: ``` SELECT projects.project_...
There is a core problem with your query in that you are left joining to two tables, implying that rows may not exist, but then putting conditions on those tables, which will eliminate NULLs. That means your query is internally inconsistent as is. The next problem is that you're joining two tables to `project_phases` t...
You need an extra parentheses in your where clause in order to get the logic right. ``` WHERE ( projects.project_number = @iProjectNumber ) AND ( (project_phase_expensegroups.projectphase_expense_total > 0) OR (invoicerows.invoicerow_total > 0) ) ``` Also, you're using a c...
SSRS query and WHERE with multiple
[ "", "sql", "t-sql", "reporting-services", "" ]
I need to pull values from one table that are only 24 hours from the date in another table in sybase ase 15.5. Here is my wrong code: ``` SELECT p_generaldata.admissiontime,* FROM Patient.dbo.P_MonVals P_MonVals INNER JOIN Patient.dbo.P_GeneralData P_GeneralData ON P_MonVals.Patient...
Take a look a the [`DateAdd`](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1530/doc/html/san1278453012069.html) function, and add a day to the `entertime` Example from docs: Adds one day to a date: ``` declare @a date select @a = "apr 12, 9999" select dateadd(dd, 1, @a) ``` In yo...
Use function `dateadd` to sum 1 day in your date time: ``` dateadd(dd, 1, P_MonVals.entertime) ``` Reference: [Sybase dateadd function](http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1570/html/blocks/X10609.htm).
select results from one date field compared to another + 24 hours
[ "", "sql", "datetime", "sap-ase", "" ]
I'm using SQLite3 (version 3.8.6) and I have a list of transactions in a database. I want to `DELETE` the records for ids which have fewer than 10 associated transactions. I can use this to list the ids and their count values: ``` SELECT id,count(id) AS cnt FROM purchases GROUP BY id HAVING cnt < 10; ``` I tried to ...
Try this: ``` DELETE FROM purchases WHERE id IN (SELECT id FROM purchases GROUP BY id HAVING count(*) < 10); ```
What's SQLite supposed to do with this? ``` id in (select id, count(id) from ...) ``` The `IN` operator expects a list, not a rowset. Omit the named `count(id)` column and use `count(*)` directly in the `having` clause: ``` id in (select id from purchases group by id having count(*) < 10) ```
deleting records based on aggregate function criteria
[ "", "sql", "sqlite", "aggregate-functions", "sql-delete", "" ]
The link is <http://sqlzoo.net/wiki/The_JOIN_operation>. Question No.13. Now I can list all the matches as long as there is at least one goal with the code: ``` SELECT mdate, team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1, team2, SUM(CASE WHEN teamid = team2 THEN 1 ELS...
``` SELECT mdate, team1, SUM(CASE WHEN teamid = team1 THEN 1 ELSE 0 END) AS score1, team2, SUM(CASE WHEN teamid = team2 THEN 1 ELSE 0 END) AS score2 FROM game LEFT JOIN goal ON (id = matchid) GROUP BY mdate,team1,team2 ORDER BY mdate, matchid, team1, team2 ``` You want to GR...
Try `LEFT JOIN` insted of `JOIN`. Because you need to show all games even if there are no goals.
Solution to #13 of SQL Join in SQLZoo
[ "", "mysql", "sql", "join", "" ]
I have 3 tables: ``` Meeting_t : Meeting_id (PK), create_date (Date) Prog_call : prog_call_id (PK) and Meeting_id (FK) Lock_t : lock_id (PK) and prog_call_id (FK) ``` There could be multiple records corresponding to each Meeting\_id in Prog\_call and similarly multiple records in Lock\_t corresponding to each prog...
You could three straight deletes e.g. ``` PROCEDURE cleanBefore( delete_before DATE ) IS DELETE FROM lock_t l WHERE l.prog_call_id IN (SELECT p.prog_call_id FROM meeting_t m INNER JOIN prog_call p ON (p.meeting_id = m.meeting_id) WHERE trunc(m.logoff_datum) <= trunc(cleanBefore...
Simply use **`ON DELETE CASCADE`** option : ``` SQL> drop table comm; SQL> DROP TABLE EMPLOYEE; SQL> SQL> CREATE TABLE employee 2 (employee_id NUMBER(10) NOT NULL 3 ,employee_name VARCHAR2(500) NOT NULL 4 ,salary NUMBER(20) NOT NULL 5 ,department VARCHAR2(300) NOT NULL 6 ,CONST...
Deleting data with multiple referential integrities
[ "", "sql", "oracle", "plsql", "cursor", "" ]
i have a table location that has thousands of data my sql query is ``` select * from location_table where country = "PH" and (province = "NCR" OR province = "") and (city = "makati" or city="") limit 10 ``` location\_table ``` ID | country | province | city 1 | PH | NCR | makati 2 | PH | NCR...
Use `ORDER BY` to put the non-empty values first: ``` select * from location_table where country = "PH" and (province = "NCR" OR province = "") and (city = "makati" or city="") order by province = "", city = "" ``` `columnname = ""` will be `1` when the column is empty, otherwise it will be `0`. [DEMO](http://ww...
``` select * from location_table where country = "PH" and (province = "NCR" OR province = "") and (city = "makati" or city="") order by province, city ``` Order By will work on your problem.
mysql selecting a values with priority
[ "", "mysql", "sql", "" ]
I want to run the first query on the data list and then the second on the data that is selected by the first query. Needless to say this is not working out. How do I go about doing this? ``` SELECT * FROM data_list WHERE USAGE_TIME > 1530 AND USAGE_TIME < 2030 SELECT * FROM data_list WHERE USAGE_DATE = #12/07/2013#; `...
No need to write 2 different select statements. Instead you can have multiple filters (conditions) in you `WHERE` clause. I hope you want this: ``` SELECT * FROM data_list WHERE USAGE_DATE = #12/07/2013# AND USAGE_TIME > 1530 AND USAGE_TIME < 2030; ```
It seems you're complicating the situation. You can simply combine the conditions in the `WHERE` clause. Here is the query you're looking for: ``` SELECT * FROM data_list D WHERE D.USAGE_TIME > 1530 AND D.USAGE_TIME < 2030 AND D.USAGE_DATE = #12/07/2013# ``` Hope this will help you.
SQL: Run one SELECT query and then another SELECT query on the last query?
[ "", "sql", "database", "ms-access", "" ]
i have the following table with different prices in every week and need a numbering like in the last column. consecutive rows with same prices should have the same number like in weeks 11/12 or 18/19. but on the other side weeks 2 and 16 have the same prices but are not consecutive so they should get a different number...
Simulating your table first: ``` SQL> create table mytable (w,price,r1) 2 as 3 select 1 , 167.93, 1 from dual union all 4 select 2 , 180 , 1 from dual union all 5 select 3 , 164.72, 1 from dual union all 6 select 4 , 147.42, 1 from dual union all 7 select 5 , 133.46, 1 from dual union all 8 sele...
You can nest your analytic functions using inline views, so you first group the consecutive weeks with same prices and then dense\_rank using those groups: ``` select w , price , r1 , dense_rank() over ( order by first_w_same_price ) drank from ( select w , price , ...
oracle sql - numbering group of rows
[ "", "sql", "oracle", "analytic-functions", "" ]
Can you tell me what I am doing wrong here? ``` CREATE PROC [dbo].[GetUserEULASelection] (@username VARCHAR(150)) AS BEGIN DECLARE @result VARCHAR(250); SELECT @result = a.NAME FROM licmn_license_users_accounts_c ua JOIN accounts a ON a.id = ua.licmn_license_users_accountsaccounts_ida JOIN licmn_l...
Your problem (as noted in other answers) is that you cannot use a case statement like this, an if would be more appropriate. However, you could get rid of that conditional statement altogether, along with the local variable: ``` CREATE PROC [dbo].[GetUserEULASelection] (@username VARCHAR(150)) AS BEGIN SELECT CO...
What's wrong is you're using CASE incorrectly. You're mixing it up with an IF in that context So you should properly do: ``` IF @result IS NOT NULL SELECT @result AS name ELSE SELECT '0' AS name ``` If you want to use CASE you should do it in the query: ``` SELECT CASE WHEN a.NAME IS NULL THEN '0' ...
T-SQL Stored procedure CASE issue
[ "", "mysql", "sql", "sql-server", "" ]
I am designing a database for use with a Ruby on Rails application. For a given object, I need to access the date of an event in both the [Gregorian](http://en.wikipedia.org/wiki/Gregorian_calendar) format and the [Hebrew calendar](http://en.wikipedia.org/wiki/Hebrew_calendar) equivalent. I can easily convert between t...
With an after\_sunset flag you store a Gregorian date and add all the additional information needed to know the Hebrew date. With two dates you would store the two dates explicitely. However, to have data consistent you would install a check constraint to ensure that the dates match. This is because the two dates shar...
Unless you are going back to the dawn of time, I think I would simply have a many-year lookup table of UTC datetimes and Hebrew dates where the UTC column is the first second of the Hebrew day in a specific time zone (Greenwich?). Conversions are a quick binary search, ``` SELECT hebrew_date FROM hebrew_gregorian_lo...
Store Hebrew Dates in a SQL Database
[ "", "sql", "ruby-on-rails", "date", "database-design", "" ]
I have a table with only 1 column that contains a string. I am trying to only get the email address. How can I do that? I looked at Substring/Ltrim, etc, but I haven't been able to piece together how to extract only part of the string. I am fairly new to SQL. Thank you for your help! ``` Column1: John Smith Email...
Assuming the email is prefixed by `Email:` and does not contain spaces, you can just take all characters after `Email:` and before the next space (or end of string); ``` SELECT CASE WHEN CHARINDEX(' ', a.em) <> 0 THEN SUBSTRING(a.em, 1, CHARINDEX(' ', a.em) - 1) ELSE a.em END email FROM ( SE...
I'm making a few assumptions about your data, namely that the characters 'Name:' don't appear before the name and that each line includes the substring 'Terminate:' In SQL Server, use a combination of PATINDEX, CHARINDEX and SUBSTRING to parse the address from the string in each row. The cursor lets you loop through y...
How do I only return part of a string with varying lengths in SQL?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table which looks roughly like this: ``` +---------------------+----------+ | date | item | +---------------------+----------+ | 2008-11-30 11:15:59 | Plums | | 2012-11-08 19:42:37 | Lemons | | 2013-01-30 18:58:07 | Apples | | 2013-02-12 13:44:45 | Pears | | 2014-06-08 11:46:48 | ...
How about ([**SQL Fiddle**](http://sqlfiddle.com/#!2/6d915/9/0)) for **NEW** items: ``` SELECT DISTINCT m1.item FROM MyTable m1 LEFT JOIN MyTable m2 ON m1.item = m2.item AND YEAR(m2.date) < 2014 WHERE YEAR(m1.date) = 2014 AND m2.date IS NULL ``` And ([**SQL Fiddle**](http://sqlfiddle.com/#!2/6d915/10)) for **RETU...
1 - This solution can use an index ``` SELECT DISTINCT x.item FROM my_table x LEFT JOIN my_table y ON y.item = x.item AND y.date < x.date WHERE x.date BETWEEN '2014-01-01' AND '2014-12-31' AND y.date IS NULL; ``` 2 - And so can this... ``` SELECT DISTINCT x.item FROM my_table x JOIN my_tabl...
Select new or returning items for a specified year
[ "", "mysql", "sql", "union", "self-join", "" ]
Suppose there are three tables `T1`, `T2` and `T3`. * `T1` has columns `Ordernum` and `bizdate` * `T2` has columns `Ordernum` and `Orderitem` * `T3` has columns `Orderitem` and `Catid` FYI: there are multiple orderitems under each ordernum; each ordertiem has multiple catids. I want to eliminate ordernums where any i...
You can use a subquery that picks out the orders with that category and use to filter out those orders: ``` select OrderNum from T1 as t where not exists( select * from T1 inner join T2 on T2.Ordernum = T1.Ordernum inner join T3 on T3.Orderitem = T2.Orderitem and T3.Catid = 100 where T1.Order...
You can to use EXISTS clause: ``` SELECT T1.OrderNum FROM T1 WHERE NOT EXISTS (SELECT * FROM T2 INNER JOIN T3 ON T2.Orderitem = T3.Orderitem WHERE T1.OrderNum = T2.OrderNum AND T3.Catid != 100) ```
Multiple tables, eliminate data
[ "", "sql", "" ]
How would you advise to find out in Sql Server 2010/2012 if a query contains a substring equal to a 6 digits number? e.g. "`agh123456 dfsdfdf`" matches the requirements "`x123 ddd456`" doesn't match the requirements because the 6 digits are not consecutive "`lm123`" doesn't match the requirements because only 3 digi...
You can use the [LIKE](http://msdn.microsoft.com/en-GB/library/ms179859.aspx) operator: ``` SELECT * FROM MyTable WHERE Mycolumn LIKE '%[0-9][0-9][0-9][0-9][0-9][0-9]%' ```
Even this should work.. considering you don't have a string like this > abc123 abc123456 Try this ``` DECLARE @str varchar(max) = 'abcxyz123456' SELECT ISNUMERIC(SUBSTRING(@str,(SELECT PATINDEX('%[0-9]%',@str)),6)) ```
find if there is a 6 digit number within a string
[ "", "sql", "sql-server", "" ]
I have these MySQL tables: table1: ``` id | writer 1 | Bob 2 | Marley 3 | Michael ``` table2: ``` user_one | user_two 1 | 2 ``` And this query: ``` SELECT table1.id FROM table1 LEFT JOIN table2 ON table1.id = table2.user_one ``` This query will return all rows of table1 which are 1,2,3 I want to se...
You could use the following query: ``` SELECT table1.id FROM table1 LEFT JOIN table2 ON table1.id IN (table2.user_one, table2.user_two) WHERE table2.user_one IS NULL; ``` Although, depending on your indexes on `table2` you may find that two joins performs better: ``` SELECT table1.id F...
One of the best approach if you do not want to return any columns from `table2` is to use the [`NOT EXISTS`](http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html) ``` SELECT table1.id FROM table1 T1 WHERE NOT EXISTS (SELECT * FROM table2 T2 WHERE T1.id = T2.us...
MySQL select rows where left join is null
[ "", "mysql", "sql", "join", "left-join", "" ]
I am trying to get the sum of 2 values in my inner select but get an error about the aggregate function. I am just trying to understand how I need to format this differently to get it working. Is there a different order I need to do this in? ``` (SELECT CONVERT(VARCHAR,D.[booksCost],1) AS booksCost, C...
[`SUM`](http://msdn.microsoft.com/en-us/library/ms187810.aspx) is an aggregate function that is applied over the specified column in a query. What you are trying to do is simply add the first two columns in every row, so you need to modify the query to drop the `SUM` keyword. ``` (SELECT CONVERT(VARCHAR,D.[booksCost...
Try use SUM() OVER(PARTITION BY..) ``` (SELECT CONVERT(VARCHAR,D.[booksCost],1) AS booksCost, CONVERT(VARCHAR,D.[tuitionCost],1) AS tuitionCost, SUM (D.[booksCost] + D.[tuitionCost]) OVER (PARTITON BY applicationID) AS totalCost, D.[className] FROM tuitionApplicationClasses AS D...
TSQL Inner Select with SUM
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
Table `airports`: ``` id | from | to | price | photo | notes _______________________________________ 1 | LON | JFK| 1000 | | test 2 | LON | JFK| 2000 | | test2 ``` I want to retrieve the bestprice entry of all `from-to` combinations inside the database. I want to fetch the whole record that is m...
You can order the results and use distinct on to take the first result from each grouping ``` select distinct on (from,to) * from airports order by from,to,price asc; ``` the above query should work
This is typically done using window functions: ``` select id, "from", "to", price, photo, notes from ( select id, "from", "to", price, photo, notes min(price) over (partition by "from", "to") as min_price from the_table ) t where price = min_price order by id; ``` `from` is a reserved word and it's...
How to retrieve specific columns in a GROUP BY sql statement?
[ "", "sql", "database", "postgresql", "greatest-n-per-group", "" ]
I have not seen any clear, concise examples of this anywhere online. With an existing table, how do I add a foreign key which references this table? For example: ``` CREATE TABLE dbo.Projects( ProjectsID INT IDENTITY(1,1) PRIMARY KEY, Name varchar(50) ); ``` How would I write a command to add a foreign key ...
I'll show you several equivalent ways of declaring such a foreign key constraint. (This answer is intentionally repetitive to help you recognise the simple patterns for declaring constraints.) **Example:** This is what we would like to end up with: ![Employee table](https://i.stack.imgur.com/r7A8k.png) --- **Case 1...
You can add the column and constraint in one operation ``` ALTER TABLE dbo.Projects ADD parentId INT NULL, CONSTRAINT FK FOREIGN KEY(parentid) REFERENCES dbo.Projects ``` Optionally you could specify the PK column in brackets after the referenced table name but it is not needed here.
How to add a foreign key referring to itself in SQL Server 2008?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a rather complex query that returns a single row, and I'd like to extend it to return multiple rows, one for each region. Right now, I can use the following query to get stats for one region at a time (in the example, the 'West' region): ``` SELECT Count(id) totalcustomers, Sum(ordertotal) totaldol...
You just need to `JOIN` to the `stateregions` table, and then `GROUP BY` the region: ``` SELECT region, count(id) totalcustomers,sum(ordertotal) totaldollars FROM customers c JOIN customeraddresses ca ON c.id = ca.customerid JOIN stateregions s on ca.state = s.state GROUP BY s.region ``` * [Updated Fid...
turn each subquery into an inner join ``` SELECT Count(id) totalcustomers, Sum(ordertotal) totaldollars FROM customers c JOIN customeraddresses ca ON c.id = ca.customerid inner join stateregions sr on sr.state = ca.state ``` where sr.region ="WEST"
Untangling subqueries
[ "", "mysql", "sql", "subquery", "" ]
Could someone point me toward general principals for speeding up my query below? I have a working query which aggregates a count of "property" values grouped across five columns. But it takes over twenty minutes to run. The count is aggregated across three related "Case" data tables which each have about 500,000 rows...
Indices. Check the query plan for all necessary indices. If the are in place, it is too slow and you need this t o be faster, find the bottleneck and buy the proper hardware to fix it, OR find another way o get the data (caching in memory etc.) though I think that wont work for this query. So, at one point there is a...
Given some assumptions: * The query hits (aggregates) across virtually every row in every table, and * The tables are truly large (joins over three tables with 500k rows in each qualify), and * The query gets run frequently OR if the query has to run quickly when it is called Then you might be looking at a data wareh...
How to speed up a COUNT of values grouped across an INNER JOIN of three large tables?
[ "", "sql", "sql-server", "performance", "join", "" ]
Let's say I have 2 tables: ``` tOrder tOrderLine ------ ---------- OrderID OrderID Other Fields ProductID Other Fields ``` I want to get back all orders that have a certain 2 products on the same order. Currently, I'm doing: ``` select o.OrderID f...
There are 2 simple ways I can think to do it: 1. Inner join to `tOrderLine` twice. Exactly how you did it. I actually would have never thought of that. It was an interesting solution when I saw it. 2. `EXISTS` clauses. For each tOrder row, check if there exists a row in `tOrderLine` corresponding to it and one of the ...
You could try to solve it using a distinct count on a `having`: ``` select t.OrderId , count(*) from tOrder t join tOrderLine o on t.OrderID = o.OrderID where o.ProductId in (67, 68) group by t.OrderId having count(distinct o.ProductId) = 2 ```
SQL Query Multiple Products on One Order
[ "", "sql", "sql-server", "" ]
I have a table in database as "EXPERIENCE RANGE" with rows as (I can also edit this table according to my need) ``` 0 0.5 1 2 3 5 10 20 ``` I have total experience as integer. I need to display the range in which it lies. Example - for experience of 8, Range will be 5 - 10 I need to write a sql query. Any ideas wil...
Assuming that you are using Oracle, the following query works fine with your existing table: ``` SELECT ( SELECT MAX( value ) FROM experience_range WHERE value <= :search_value ) AS range_start, ( SELECT MIN( value ) FROM experience_range WHERE value > :search_value ) AS range_end FROM dual; ``` No need to hardc...
you can do it with [CASE](http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm) Expression, the syntax is: ``` SELECT CASE WHEN experience >= 0 and experience <= 4 THEN '0-4' WHEN experience >= 5 and experience <= 10 THEN '5-10' ..... ELSE 'No Range' END as Range FROM Table_Name ``...
finding range by comparing two tables
[ "", "sql", "oracle", "" ]
I have a table that contains values per user per month. What I need to find is the average value for the sum of users in each month. I can't do this: ## **QUERY** ``` SELECT AVG(SUM(TACMargin)) FROM report_sales_month WHERE YEAR(date) = 2013 GROUP BY userId ``` Which I don't think would get me what I want anywa...
I think you can do what you want with a subquery: ``` SELECT AVG(sumtc) FROM (SELECT SUM(TACMargin) as sumtc FROM report_sales_month WHERE YEAR(date) = 2013 GROUP BY month(date) ) t; ``` You can also express this without the subquery: ``` SELECT SUM(TACMrgin) / count(distinct month(date)) FROM...
I'm not sure about what result you're looking for. It may be the query that you want: ``` SELECT AVG(M.totalTACMargin) FROM (SELECT R.userId ,MONTH(R.date) AS month ,SUM(R.TACMargin) AS totalTACMargin FROM report_sales_month R WHERE YEAR(R.date) = 2013 GROUP BY R.userId, MONTH(R.d...
Average of the Sum of X in MySQL
[ "", "mysql", "sql", "" ]
i need autoincrement. for start like abc\_1,abc\_2. like this format? below shown code is for auto increment. but i need format like abc\_ is constatanct then auto increment, format like abc\_1,abc\_2.. ## **CODE** ``` sql = "CREATE TABLE MY_TABLE ( table_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(table_id), ...
You have 2 options - both include keeping the autoincrement field exactly as it is. 1st Option is to add a short char type field, which simply stores your Alpha part. When you want to retrieve the whole key, then you can `SELECT (alpha_part + table_id) as ID`. As you can see this generates smaller storage, but require...
You could add another column to derive this value, then have a trigger that automatically updates this column to add the derived value whenever a row is inserted. However, it is not clear why this would be needed. It is likely better to just store the number and derive the form `abc_123` where that value needs to be u...
Auto Increment in sql with specific name
[ "", "mysql", "sql", "" ]
I have been trying to code up a stored procedure that will grab the top tenant for each property ID and Contract Number for the user logged in. I have been able to get SQL to grab able to do most of it but not the bit where i only grab the top one for each group wich i need it to do. It is a little hard to exsplain a...
Here is a way to this. ``` with MyCTE as ( SELECT pt.Id , pt.PropertyId , pt.Name + ', ' + pt.Address1 as tenantinfo , pt.contractNumber , ROW_NUMBER() over (PARTITION BY PropertyID, contractnumber order by id asc) as RowNum FROM PropertyTenant pt WHERE pt.PropertyId IN ...
Try this:- ``` SELECT Min(Id), PropertyId, Name + ', ' + Address1, contractNumber FROM PropertyTenant WHERE PropertyId IN (SELECT PropertyId FROM UserProperty WHERE UserId = '5E541037-747C-43B9-BB9F-97C8728083B7') ...
How to show only top result for each feild group in SQL
[ "", "sql", "sql-server", "" ]
Basically I have just two tables. The first is "Objects" and the second is "Properties". Now I want objects with specified properties. Objects Table: ``` +-----------+ | Column | +-----------+ | object_id | +-----------+ ``` Properties Table: ``` +-------------+ | Columns | +-------------+ | property_id | | ...
If I understand correctly it is something like ``` Select object_id from objects where object_id in (select object_id from properties where gender="male") and object_id in (select object_id from properties where married="yes") ; ``` An alternative using only properties: ``` (select object_id from propert...
This cannot be done efficiently in a RDBMS. However, you can achieve it along the lines of: ``` SELECT object_id FROM your_table t1 INNER JOIN your_table t2 ON ( t1.object_id = t2.object_id AND t2.property_id = 4 AND t2.value = 'yes') WHERE t1.property_id = 6 and t1.value = 'male'; ```
Select row depending on what is linked to it in other table MySQL
[ "", "mysql", "sql", "" ]
I'm trying to implement this SQL code in PL/SQL SQL Code: ``` select SUM(SUM(distinct inv_total) - SUM(distinct credit_total) ) as TOTAL from invoice where cus_id =95 group by inv_total, credit_total ``` PL/SQL Code: ``` Declare total invoice.inv_total%TYPE; cust_id NUMBER := 95; BEGIN select SUM(SUM(distinct...
You seem to have several problems: 1. I find it highly unlikely that you actually want `distinct` inv\_total or credit\_total. If two invoices have the same total, you only want to count one of them? 2. Without the distinct, the `sum` can be written 'SUM(inv\_total - credit\_total)'. This is much more straightforward ...
Try this:- ``` DECLARE total invoice.inv_total%TYPE; cust_id NUMBER := 95; BEGIN select SUM( inv_total - credit_total) INTO total from invoice where cus_id= cust_id; dbms_output.put_line('Total is ' || total); END; / ```
PL/SQL SUM Difference Example
[ "", "sql", "oracle", "plsql", "" ]
I'm trying to find the following statistic: `How many users have made at least one order` (yeah, sounds like homework .. but this is a simplistic example of my real query). Here's the made up query ``` SELECT COUNT(UserId) FROM USERS a WHERE EXISTS( SELECT OrderId FROM ORDERS b WHERE a.UserId = b.UserId ...
It sounds like you just could use [`COUNT DISTINCT`](http://msdn.microsoft.com/en-us/library/ms175997.aspx): ``` SELECT COUNT(DISTINCT UserId) FROM ORDERS ``` This will return the number of distinct values of `UserId` appear in the table `OrderId`. In response to [*sgeddes*'s comment](https://stackoverflow.com/users...
``` Select count(distinct u.userid) From USERS u Inner join ORDERS o On o.userid = u.userid ```
Is this SQL query with an EXISTS the most performant way of returning my result?
[ "", "sql", "t-sql", "" ]
I have a question. I have two tables employees and salary and I want to display the full name and salary grade of all employee who’s grade\_ID is 2 or 3 sort by employee\_ID. Here are the tables: ``` Salary_ID LOW_SALARY High Salary 1 1 250000 2 250001 500...
It may be the query you're looking for: ``` SELECT E.EMPLOYEE_ID ,E.FIRST_NAME ,E.LAST_NAME ,E.SALARY FROM employees E INNER JOIN salary S ON S.LOW_SALARY <= E.SALARY AND S.HIGH_SALARY >= E.SALARY AND S.SALARY_ID IN (2,3) ORDER BY E.EMPLOYEE_ID ``` Hope this wil...
``` SELECT employees2.FIRST_NAME, employees2.LAST_NAME, employees2.SALARY, salary_grades.SALARY_GRADE_ID FROM employees2, salary_grades WHERE employees2.SALARY BETWEEN salary_grades.LOW_SALARY AND salary_grades.HIGH_SALARY ORDER BY salary_grades.SALARY_GRADE_ID ``` So I tried using this script, it works but do i use...
Joining two tables SQL
[ "", "mysql", "sql", "oracle", "" ]
First, I'll claim no extreme expertise in SQL. What I am trying to do is pull down some incident counts from a SQL Server database based on a couple of varying criteria and put them into SSRS in a line chart that shows monthly counts on top of each other. Both of the queries that I had initially created pull down the ...
Your queries are quite similar. It looks like you have a total count, and then a partial count of some records that have specific work log types. Here is a query that returns date, BaseCount, and 'WorkLogFilteredCount' SSRS should be able to consume the date as an axis and the other two columns as separate series very ...
Based on what I am thinking you want I am going to use a [UNION](http://msdn.microsoft.com/en-us/library/ms180026.aspx) and treat the unioned queries as a [subquery](http://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx). ``` SELECT * FROM ((SELECT DISTINCT v_Incident.ReportedDate, COUNT(...
TSQL 2 Queries in 1
[ "", "sql", "sql-server", "t-sql", "reporting-services", "" ]
I'm using PostgreSQL and am an SQL beginner. I'm trying to create a table from a query, and if I run: ``` CREATE TABLE table_name AS (....query...) ``` it works just fine. But then if I add 'if not exists' and run: ``` CREATE TABLE IF NOT EXISTS table_name AS (....query...) ``` using exactly the same query, I...
[CREATE TABLE AS](http://www.postgresql.org/docs/current/static/sql-createtableas.html) is considered a separate statement from a normal [CREATE TABLE](http://www.postgresql.org/docs/current/static/sql-createtable.html), and *until Postgres version 9.5* (see [changelog entry](https://www.postgresql.org/docs/9.5/static/...
`CREATE TABLE IF NOT EXISTS ...` was added in Postgres 9.1. See: * [PostgreSQL create table if not exists](https://stackoverflow.com/questions/1766046/postgresql-create-table-if-not-exists/7438222#7438222) ### Postgres 9.0 or older If you are going to write a function for this, base it on [system catalog table **`pg...
PostgreSQL: Create table if not exists AS
[ "", "sql", "postgresql", "create-table", "" ]
I have a table variable which i use to collect records from several tables, which have to be processed later on in my query. It look a bit like this: ``` DECLARE @Prices TABLE ( ProductId INT, Price MONEY, Fee INT, Discount INT, IsSpecialPrice BIT ) ``` Now, after gathering price related records from se...
what about a join? ``` DELETE P1 FROM @Prices P1 join ( SELECT DISTINCT ProductId FROM @Prices WHERE IsSpecialPrice = 1 ) P2 on P1.ProductId = P2.ProductId WHERE P1.IsSpecialPrice = 0 ``` i made a test on a table with 500k rows and completed in 2sec deleting 90k rows that's a huge improvement compared to the n...
This is your query: ``` DELETE P1 FROM @Prices P1 WHERE P1.IsSpecialPrice = 0 AND EXISTS (SELECT 1 FROM @Prices P2 WHERE P2.ProductId = P1.ProductId AND P2.IsSpecialPrice = 1 ); ``` The normal way to speed this up would be to add indexes: `@Prices...
Faster SQL DELETE WHERE IN/EXISTS needed
[ "", "sql", "sql-server", "t-sql", "" ]