Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I just cannot seem to find an answer for this deceptively simple question. Most every solution either deletes all the duplicates, selects all the duplicates, or selects all the records except the duplicates. How can I select all rows such that, in this example, the "name" column values are unique, while selecting the f...
Here is a query that that returns what you're looking for: ``` SELECT F.* FROM foo F INNER JOIN ( SELECT MIN(F2.pk) AS `pk` ,F2.name FROM foo F2 GROUP BY F2.name ) T ON T.pk = F.pk; ``` Hope this will help you.
I think you are looking for this : ``` select * from table group by name; ``` Which can be written using distinct keyword as : ``` select distinct on name * from table; ```
How to select all records based on non-duplication of one column
[ "", "mysql", "sql", "database", "duplicates", "" ]
I have a query that produces a table like this: ``` BN System amount 13098 System1 860.05 16722 System1 63360 16722 System2 1544713.19000001 01292 System2 3260 17133 System2 6240 33851 System2 155340.03 24638 System2 11364.54 89936 System1 3719.85 57522 System2 50153558.7400001 84197 System2 ...
``` select t.bn, t.system, sum(t.amount) from tbl1 t join (select bn from tbl1 group by bn having count(distinct system) > 1) x on t.bn = x.bn group by t.bn, t.system ``` I think by 'duplicate' you mean the same BN value is associated with 2+ unique systems? The above should work if that is the case.
I think the best approach is using window functions: ``` select t.* from (select t.*, count(*) over (partition by system)) as cnt from tbl t ) t where cnt > 1; ``` This is particularly useful if you really are using a subquery. This formulation only runs the subquery once.
SQL Select only duplicates from one column
[ "", "sql", "t-sql", "sql-server-2012", "duplicates", "" ]
I have two tables that have no relationship. I want to select a value from each of them and divide one from the other. I'm essentially looking for something like this (although I know this is not correct): SELECT ( SELECT MAX(row) FROM TableA / SELECT max(row) from TableB)) How can I do this in a single SQL statement...
``` SELECT (cast((SELECT MAX(row) FROM TableA) as decimal) / cast((SELECT max(row) from Table2) as decimal)) ```
This works in Sql Server, not sure about other implementations of SQL. `select (tableA.Value/tableB.Value) from (select MAX(row) Value FROM TableA) tableA, (select MAX(row) Value FROM TableB) tableB`
How to select a single value from two different tables and divide them
[ "", "sql", "" ]
Here is my question I have this `SQL` Query: ``` SELECT * FROM leftTable JOIN rightTable ON leftTable.match = rightTable.match ``` is `JOIN` a left join, a right join or an inner Join?
`JOIN` is short for `INNER JOIN`. `LEFT JOIN`, `RIGHT JOIN` and `FULL JOIN` are technically short for `LEFT OUTER JOIN`, `RIGHT OUTER JOIN` and `FULL OUTER JOIN` respectively. Standard compliant SQL parsers aren't required to accept the long versions.
`JOIN` keyword used alone refers to `INNER JOIN`, otherwhise you have to explecity define which join you want to use e.g ``` LEFT JOIN FULL JOIN e.t.c ```
About the JOIN keyword
[ "", "sql", "join", "" ]
I am using MS access. I tried write SQL code that refer to the tables EMPLOYEE, PROJECT and JOB and return the results as shown in the figure below: ``` PROJ_NAME PROJ_VALUE PROJ_BALANCE EMP-LNAME EMP_FNAME EMP_INITIAL JOB_CODE JOB_DESCRIPTION JOB_CHG_HOUR iCEBUTT 800.00 12000 SMITH ANNE E ...
You are missing the condition for the joins. Now both `employee` and `job` give all records. You have to tell how they relate to the `project` table. Something like this: ``` SELECT p.PROJ_NAME, p.PROJ_VALUE, p.PROJ_BALANCE, p.EMP_LNAME, p.EMP_FNAME, p.EMP_INITIAL, p.JOB_CODE, p.JOB_DESCRIPTION, p.JOB_CHG...
You have created a Cartesian product (or cross join). The valus obtained are not only duplicates but also wrong. To avoid this, you need to use joins in your query. ``` SELECT * FROM EMPLOYEE JOIN JOB ON EMPLOYEE.JOB_ID = JOB.ID JOIN PROJECT ON EMPLOYEE.PROJ_ID = PROJECT.ID WHERE PROJECT.PROJ_VALUE >= 805000.00; ``` ...
I keep getting duplicate data in my record
[ "", "sql", "list", "ms-access", "" ]
I have an `Adventure` model, which is a join table between a `Destination` and a `User` (and has additional attributes such as `zipcode` and `time_limit`). I want to create a `query` that will return me all the `Destinations` where an `Adventure` between that `Destination` and the `User` currently trying to create an `...
The below should return all destinations that user has not yet visited in any of his adventures: ``` destinations = Destination.where('id NOT IN (SELECT destination_id FROM adventures WHERE user_id = ?)', user.id) ``` To select a random one append one of: ``` .all.sample # or .pluck(:id).sample ``` Depending on whe...
No need for joins, this should do: ``` Destination.where(['id not in ?', user.adventures.pluck(:destination_id)]) ```
Rails ActiveRecord query where relationship does not exist based on third attribute
[ "", "sql", "ruby-on-rails", "activerecord", "active-record-query", "" ]
I need an update statement to resolve some issues with duplicates in a table on SQL Server 2000. The table structure is shown below. There is no primary key in this table. I need a SQL statement that will update the values in cases where there are duplicates by adding 5 to the value until there are no more duplicates. ...
The script might fail in case I have sequence like: ('Doc001',900), ('Doc001',900), ('Doc001',900), ('Doc001',903), ('Doc001',904), ('Doc001',905), ('Doc001',905), ('Doc001',905), ('Doc001',910), ('Doc001',910), ('Doc001',915), ('Doc001',915) The script will give error as below: *Msg 512, Level 16, State 1, Line 1 Sub...
``` ;with tb1(id, seqNUm, docNum) as ( SELECT ROW_NUMBER() OVER (ORDER BY SeQNumber), DocNumber, SeQNumber From table1 ) update tb1 set docnum=201 where id=2 ``` * set id whatever row you want to update
Update Duplicates in SQL Server without a primary key
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I have a query that outputs a list of percentages based on a total number, the only part I cant figure out is an efficient method to filter the 'usid' equal to a value on another table. The query is not failing but is taking a very long time to complete. ``` SELECT badge, count(usid)*100 / (SELECT COUNT(DISTINCT...
You should be able to use explicit JOIN notation instead of the IN clause: ``` SELECT a.badge, COUNT(a.usid)*100 / (SELECT COUNT(DISTINCT usid) from Table1) FROM Table1 AS a JOIN (SELECT DISTINCT usid FROM Table2 WHERE msid = 1) AS b ON a.usid = b.usid GROUP BY a.badge ``` However, I'm not confident that will fi...
This is not such a simple query. Depending on the database you are using, the `in` might be quite inefficient and each output row is calculating the `count(distinct)`. Try rewriting the query as: ``` SELECT badge, count(usid)*100 / x.cnt FROM Table1 t1 cross join (SELECT COUNT(DISTINCT usid) as cnt from Table1) x...
Simple SQL query is taking 20 minutes to run?
[ "", "sql", "" ]
I'm trying to get the **total number of rows** using this SQL query, the result should be = **1** ``` SELECT COUNT(id) FROM offer_process WHERE uid = 103 AND date = '2014-08-20' ``` I don't know exactly how to get the total number of rows from a date (2014-08-20) in this case. ![enter image description here](https:/...
You have a `datetime` column. To check only `date` part, use [DATE() MySQL function](http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date "DATE() MySQL function") ``` SELECT COUNT(id) FROM offer_process WHERE uid = 103 AND DATE(date) = '2014-08-20' ``` Also, if you have an **index** on ...
You may try this: ``` SELECT COUNT(id) FROM offer_process WHERE uid = 103 AND DATE_FORMAT(`date`, "%Y-%m-%d") = '2014-08-20' ``` or you may try using date ``` SELECT COUNT(id) FROM offer_process WHERE uid = 103 AND date(`date`) = '2014-08-20' ```
Simple SELECT COUNT SQL query error
[ "", "mysql", "sql", "" ]
I have a list with values in it. I want to insert these values in a SQL table using a single `INSERT` statement. Example: Say, there is a list with names (the size of the list is not constant). There is a `STUDENTS` table with `NAME` column. I want to insert in the `STUDENTS` table the names from the list using a sing...
In MySql you can do it like this ``` INSERT INTO tbl (f1,f2) VALUES(1,2),(3,4),(5,6)...(55,77); ``` For mssql dialect all the same
If your list was in a temporary table, you could use the following syntax: ``` insert into tblname (columnlist) select name from temptable; ```
Insert values from a list in a single SQL statement
[ "", "sql", "vb6", "sql-insert", "" ]
I've this database: ``` ╔═════════╦══════╦══════════╦═══════════╦════╦═════════╗ ║ ID_Elab ║ Step ║ ID_Progr ║ ID_Causal ║ GI ║ Minutes ║ ╠═════════╬══════╬══════════╬═══════════╬════╬═════════╣ ║ 8 ║ 1 ║ 8 ║ 19 ║ 0 ║ 480 ║ ║ 8 ║ 2 ║ 1391 ║ 19 ║ 0 ║ 480 ║ ║ 8 ...
``` create table #test_table( ID_Elab int, Step int, ID_Progr int, ID_Casusal int, GI int, Minutes int ) insert into #test_table select 8, 1, 8, 19, 0, 480 union all select 8, 2, 1391, 19, 0, 480 union all select 8, 3, 1781, 19, 0, 480 union all select 10, 1, 10, 50, 0, 480 union all select 1...
``` mysql> select * FROM tst where step = (select max(step) from tst as B where tst.ID_Elab = B.ID_Elab); +---------+------+----------+-----------+----+---------+ | ID_Elab | Step | ID_Progr | ID_Causal | GI | Minutes | +---------+------+----------+-----------+----+---------+ | 8 | 3 | 1781 | 19 | ...
Check greater value of row and then take every row with same value grouping by ID
[ "", "sql", "sql-server", "" ]
I have a table called `Users` that has a growing list of preferences. These preferences could includes ReligionId (which would key off to another table that contains the list of religions). The list of preferences is growing. I want to split it off the `Users` table into 2 tables. The strategy that I think would work ...
At a minimum you could just have Users and Preferences. There should be a one to many relationship between users and preferences. One user can have many preferences. You could also split out the email addresses into another table - so that one user could have multiple email addresses - you can have a flag to denote the...
Some folks are recommending to store the preferences one per row. This is called an Entity-Attribute-Value table, and it is *not* normalized. Some people say EAV is "more normalized," but they're mistaken. There is no rule of normalization that encourages EAV as a design in a relational database. One practical way you...
Users table to Users and User Preferences. Is this normalized?
[ "", "sql", "sql-server", "normalization", "" ]
i am using this T-SQL to repair my TFS suspected database ``` EXEC sp_resetstatus [TFS_Projects]; ALTER DATABASE [TFS_Projects] SET EMERGENCY DBCC checkdb([TFS_Projects]) ALTER DATABASE [TFS_Projects] SET SINGLE_USER WITH ROLLBACK IMMEDIATE DBCC CheckDB ([TFS_Projects], REPAIR_ALLOW_DATA_LOSS) ALTER DATABASE [TFS_Proj...
i update my answer becuase old answer is dangerous and will damage TFS database! this answer is from microsoft : <http://msdn.microsoft.com/en-us/library/jj620932.aspx> > **To back up your databases** > > > Launch TFSBackup.exe. > > The TFSBackup.exe tool is in the Tools folder where you installed Team Foundation Serv...
1) If possible add more hard drive space either by removing of unnecessary files from hard drive or add new hard drive with larger size. 2) Check if the database is set to Autogrow on. 3) Check if the account which is trying to access the database has enough permission to perform operation. 4) Make sure that .mdf an...
Repair Suspected TFS database
[ "", "sql", "sql-server", "t-sql", "tfs", "" ]
I want to create trigger that fires every time any column is changed - whether it is freshly updated or new insert. I created something like this: ``` CREATE TRIGGER textsearch BEFORE INSERT OR UPDATE ON table FOR EACH ROW EXECUTE PROCEDURE trigger(); ``` and body of trigger() function is: ``` BEGIN NEW.t...
you need to use the `NEW` record directly: ``` BEGIN NEW.ts := concat_ws(' ', NEW.a::text, NEW.b::TEXT, NEW.c::TEXT); RETURN NEW; END; ``` The advantage of `concat_ws` over `||` is that `concat_ws` will treat `NULL` values differently. The result of `'foo'||NULL` will yield `NULL` which is most probably not wha...
It doesn't work because you're calling SELECT inside the function. When it runs `BEFORE INSERT` then there isn't a row to select, is there? Actually, `BEFORE UPDATE` you'll see the "old" version of the row anyway, won't it? Just directly use the fields: `NEW.a` etc rather than selecting. --- As an edit - here is a...
Trigger on every update or insert
[ "", "sql", "postgresql", "" ]
Hi I have below query in an SP @CrmContactId is a parameter to the SP. ``` Select distinct A.PolicyBusinessId, A.PolicyDetailId from TPolicyBusiness A inner join TPolicyOwner B on a.PolicyDetailId=b.PolicyDetailId Left Join TAdditionalOwner C on c.PolicyBusinessId=A.PolicyBusinessId where (b.CRMContactId = @CRMConta...
Using `UNION ALL` to replace `OR` is actually one of the well known optimization tricks. The best reference and explanation is in this article: [Index Union](http://blogs.msdn.com/b/craigfr/archive/2006/10/18/index-union.aspx). The gist of it is that `OR` predicates that *could* be be satisfied by two index seeks cann...
The JOIN to TAdditionalOwner is using ``` TPolicyBusiness.PolicyBusinessId = TAdditionalOwner.PolicyBusinessId ``` where the JOIN to TPolicyOwner is using the ``` TPolicyBusiness.PolicyDetailId = TPolicyOwner.PolicyDetailId ``` Check that there is a corresponding index for the PolicyBusinessId. In the 2-way JOIN, ...
Why using OR condition instead of Union caused a performance Issue
[ "", "sql", "sql-server", "union-all", "" ]
Having this table: ``` +----+-------+---------+-----+ | id | group | name | age | +----+-------+---------+-----+ | 1 | a | John | 11 | +----+-------+---------+-----+ | 2 | a | Rachel | 12 | +----+-------+---------+-----+ | 3 | a | Sarah | 11 | +----+-------+---------+-----+ | 4 | a | Jo...
You would do a query like this: ``` select tt.* from thistable tt where tt.id < (select min(tt2.id) from thistable tt2 where tt2.`group` = 'b'); ``` Note that `group` is a lousy name for a column name because it is a reserved word.
If you don't know the group values and want to get the first one you can use user defined variables or in simple words you can use rank query ``` select `id`, `group`, `name`, `age` from ( select t.* , @r:= case when @g = t.`group` then @r else @r+1 end `row`, @g:=t.`group` from t cross join(select @g:='',@r:=0) t1 o...
MySQL Select from beginning until row = string
[ "", "mysql", "sql", "" ]
I am not good with complex sql query so I am posting this question and I will happy If you help me. I have 2 tables. First is `idea_box` and second is `idea_box_voting`. Now first I want to join two table and then I want to count total 0 and 1 numbers of there id. Here is my two tables. ``` idea_box -------- Idea_id...
``` SELECT ib.*, ( SELECT COUNT(*) FROM idea_box_voting ibv WHERE ibv.idea_id = ib.idea_id AND ibv.thumbs = 1 ) AS one_count, ( SELECT COUNT(*) FROM idea_box_voting ibv WHERE ibv.idea_id = ib.idea_id AND ibv.thumbs = 0 ) AS zero_count FROM idea_box ib ```
Try this ``` Select Count(CASE WHEN vote.thumbs = 0 THEN 1 END) AS Zero_Count Count(CASE WHEN vote.thumbs = 1 THEN 1 END) AS One_Count FROM idea_box as ib left Join idea_box_voting as vote On vote.idea_id = ib.idea_id Group by vote.idea_id ```
How to use join table and count with select query
[ "", "mysql", "sql", "" ]
I have two select statements which is returning duplicated data. What I'm trying to accomplish is to remove a duplicated leg. But I'm having hard times to get to the second row programmatically. ``` select i.InvID, i.UID, i.StartDate, i.EndDate, i.Minutes,i.ABID from inv_v i, InvoiceLines_v i2 where i.Period = '2014/...
You can use `exists` to delete all duplicates except the one with the highest `InvID` by deleting those rows where another row exists with the same values but with a higher `InvID` ``` delete from inv_v where exists ( select 1 from inv_v i2 where i2.InvID > inv_v.InvID and i2.minutes = inv_v.minutes a...
I have faced similar problems regarding duplicate data and some one told me to use partition by and other methods but those were causing performance issues However , I had a primary key in my table through which I was able to select one row from the duplicate data and then delete it. For example in the first select st...
Remove duplicate row based on select statement
[ "", "sql", "sql-server-2008", "" ]
I have a page audit table that records which pages a user has accessed. Given an specific page, I need to find what previous page the user has accessed and what was the most accessed. For example, the FAQ Page\_ID is 3. I want to know if it is more frequently accessed from the First Access page (ID 1) or Home page (ID...
You can use window functions as one way to figure this out: ``` with UserPage as ( select User_ID, Page_ID, row_number() over (partition by User_ID order by ID) as rn from PageAudit ) select p1.Page_ID, count(*) from UserPage p1 inner join UserPage p2 on p1.User_ID = p2.User_ID and ...
``` select prev_page, count(*) from (select id, page_id, user_id, lag(page_id, 1) over(partition by user_id order by id) as prev_page from page_audit_table) x where page_id = 3 and prev_page <> page_id group by prev_page ``` **Fiddle:** <http://sqlfiddle.co...
How do I query previous rows?
[ "", "sql", "sql-server", "" ]
Considering the following query: ``` SELECT 1 AS a, '100' AS b UNION SELECT 1 AS a, '50' AS b ORDER BY a, b; ``` which results in: ``` a b 1 '100' 1 '50' ``` What I really want is to sort column b by number and not text. One possible solution could be: ``` SELECT 1 AS a, '100' AS b, '100'::int AS c UNION SEL...
you can do this with a subquery (think the union is part of the problem). ``` select a, b from ( SELECT 1 AS a, '100' AS b UNION SELECT 1 AS a, '50' AS b)s order by cast(b as int)-- or b::int ``` see [SqlFiddle](http://sqlfiddle.com/#!15/d41d8/3102) with difference But if it's just a sample, and b ...
Dealing with strings is best handled by strings, if any value in that column isnt convertible to integer it will fail. ``` SELECT a, b FROM ( SELECT 1 AS a, '100' AS b UNION ALL SELECT 1 AS a, '50' AS b UNION ALL SELECT 1 AS a, 'badvalue' AS b ) s ORDER BY a, right(concat...
Converting values within ORDER BY clause
[ "", "sql", "postgresql", "type-conversion", "sql-order-by", "" ]
I have a problem with sorting sql tables. I have this: ``` +------+------+ | col1 | col2 | +------+------+ | a | 1 | | b | 3 | | c | 4 | | d | 3 | | e | 2 | | f | 2 | | g | 2 | | h | 1 | +------+------+ ``` And i need to have this: ``` +------+------+ | col1 | col2 | ...
If database supports OVER clause then it is quite simple: ``` SELECT t.id, t.value FROM t ORDER BY count(*) over (partition by value) DESC ``` See SQL Fiddle - <http://sqlfiddle.com/#!6/ce805/3>
I see. You want to sort by the frequency of the values. Most dialects of SQL support window functions, so this does what you want: ``` select t.col1, t.col2 from (select t.*, count(*) over (partition by col2) as cnt from table t ) t order by cnt desc, col2; ``` Another way of writing this uses a `join` and...
Frequency based sort in sql
[ "", "sql", "sorting", "frequency", "" ]
I am trying to convert this Query from Microsoft access to **SQL Server 2012**. ``` SELECT IIF(IsNull(Letter), '', CalculationType) AS [BF NI Calculation Basis] FROM NICs ``` I converted it to the follwing, But I keep getting the error: > Msg 245, Level 16, State 1, Line 1 Conversion failed when converting > the va...
If you want to check if Letter is NULL than write: ``` SELECT IIF(Letter IS NULL, '', CalculationType) AS [BF NI Calculation Basis] FROM NICs ``` If you want to check Letter for the Value 0 ``` SELECT IIF(Letter ='0', '', CalculationType) AS [BF NI Calculation Basis] FROM NICs ```
According to this [MSDN link for IIF](http://msdn.microsoft.com/en-IN/library/hh213574.aspx) Returns the data type with the highest precedence from the types in **true\_value** and **false\_value**. it means in your query true\_value is ''(string) and false\_value is CalculationType(which is int) and that's the reason...
Converting access SQL to SQL server
[ "", "sql", "sql-server", "sql-server-2012", "" ]
In SQL Server 2005 or later you can use following syntax to return a a variable number of rows: ``` Declare @Limit Int Set @Limit=5 Select Top(@Limit) * From TableName ``` Is there some magic value, that you can use to let it return all rows? (Thinking of parametrized stored procedure here). Setting limit as `0` will...
To avoid rewriting the query, which I'm assuming is more complicated than the SQL in the question, you could return the row count to replace the variable in a certain case, for example, if the variable = 0, then return all: ``` declare @Limit Int set @Limit = 0 if @Limit = 0 // get the row count from the table yo...
The simple answer would be to convert to `bigint` and use its maximum possible value (9223372036854775807). Since that many rows cannot possibly be part of any table, you can be sure you won't miss anything.
Can you specify 'unlimited' when using "Select TOP (@variable) * From"?
[ "", "sql", "sql-server", "" ]
Can anyone help me with this issue I tried many times but still haven't found the solution Here is the original View that I have in my database but now I made changes in the database and the view need to be changed also. Here is the view as it was: ``` SELECT [tableN].*, [tabB].[att1] AS tabB_email, [tabB]....
``` SELECT [TableN].*, Bd.[email] AS bd_email, Bd.[showname] AS bd_name, Pc.[showname] AS pc_name FROM [TABLE_X] AS Pc INNER JOIN ([TableN] INNER JOIN [TABLE_X] AS Bd ON [TableN].[sender_id] = Bd.[ID] AND Bd.roleID = 1) ON Pc.[ID] = [TableN].[recipient_id] AND ...
``` SELECT [tableN].*, [Tabx] .[att1] AS tabB_email, [Tabx] .[name] AS tabB_name FROM [Tabx] A INNER JOIN [TABLEN] B ON A.ROLEID=B.RECIPIENT_ID ```
SQL View statement with 2 INNER JOINS
[ "", "sql", "sql-server", "view", "" ]
I have a database that handles Employment Date Hired and Date Left (the company) ``` EID |Name |Status1 |Hired |LefttheCOmpany 11 |Kid |Hired |2014-01-01 |2014-01-01 12 |Suzi |Hired |2014-03-01 |2014-03-01 13 |Mac |Fired |2014-04-01 |2014-07-17 ``...
There is a `getdate()` function which is used to get the present date but other than that I dont think anything is there in SQL Server which will represent PRESENT My suggestion is to keep those rows set as null and when you are querying the table then you can set the `getdate()` in that column. Something like this: ...
Please use the `ISNULL()` function, if the value is null it will replace it with 'Present'. ``` SELECT ISNULL(LeftTheCompany,'Present') ```
SQL Date value that means "PRESENT" (as of today's date)
[ "", "sql", "sql-server", "" ]
I know how to get the column names from a table ``` SELECT Column_name from Information_schema.columns where Table_name like 'summary' ``` And I know how to get the data like below ``` SELECT * FROM [summary] where Id='12345"; ``` but how do I combine these so that I **atleast** get column names of a table even if...
IF you want to column names of a table when there is no data then you used like this ``` IF EXISTS(SELECT * FROM [summary] where Id='12345') BEGIN SELECT * FROM [summary] where Id='12345' END ELSE BEGIN SELECT Column_name FROM Information_schema.columns WHERE Table_name like 'summary' END ```
I think using simple `CASE` here would be enough: ``` SELECT case when id is null then '' else id end , case when name is null then '' else name end FROM [summary] where Id='hello'; ```
Get both data and column name from sql table
[ "", "sql", "sql-server", "" ]
I am creating a query that ensures some constraints are met. Here's a semi-working version right now: ``` SELECT CASE WHEN TaskId IS NULL THEN 0 ELSE 1 END AS TaskExists, CASE WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1 WHEN IsDownTask = 1 THEN 1 ...
If you want to return those values just wrap each column with a `SUM` and an `ISNULL`: ``` SELECT ISNULL(SUM(CASE WHEN TaskId IS NULL THEN 0 ELSE 1 END), 0) AS TaskExists, ISNULL(SUM(CASE WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1 WHEN IsDownTask = 1 THEN 1 ELSE 0...
You can try something like this: ``` DECLARE @task INT SET @task = 555555 SELECT CASE WHEN TaskId IS NULL THEN 0 ELSE 1 END AS TaskExists, CASE WHEN IsDownTask = 0 AND TaskStatus = 63 THEN 1 WHEN IsDownTask = 1 THEN 1 ELSE 0 END AS...
Return result from query even if WHERE clause not met
[ "", "sql", "sql-server", "ibatis.net", "" ]
i need paginate a posts from my data base, i write the next query: ``` SELECT posts.ID, posts.date, comments.name, comments.value FROM posts INNER JOIN comments ON comments.ID = posts.ID INNER JOIN relations ON relations.ID = posts.ID WHERE type_rel=1 AND status_post=1 AND LIMIT 0,10 ``` The problem is...
You can use a subquery to limit the result set and then join: ``` SELECT posts.ID, posts.date, comments.name, comments.value FROM (SELECT * FROM posts WHERE status_post = 1 LIMIT 0,10) posts LEFT JOIN comments ON comments.ID = posts.ID LEFT JOIN relations ON relations.ID = posts.ID AND rela...
You can limit only the rows returned from the posts table ``` SELECT posts.ID, posts.date, comments.name, comments.value FROM (select * from posts limit 0,10) posts INNER JOIN comments ON comments.ID = posts.ID INNER JOIN relations ON relations.ID = posts.ID WHERE type_rel=1 AND status_post=1 ```
MySQL Select with Inner Join, Limit only first
[ "", "mysql", "sql", "inner-join", "limit", "" ]
Have a situation when table can be created from different places. So, I have ~10 working applications, that can simultaneously try to create a same table. Question. How can I synchronize them ? So I don't have any exceptions or errors ? All instances of the application are trying to create a new table when the day end...
You can use [`sp_getapplock`](http://msdn.microsoft.com/en-us/library/ms189823.aspx) to take arbitrary locks. You could make your app take such a lock before creating the table. Like that: ``` exec sp_getapplock if tabledoesnotexist create table ... ```
As alluded to in the comments, your first step is to perform an existence check. Then, on the off chance that there are two simultaneous creations you can use [TRY...CATCH](http://msdn.microsoft.com/en-us/library/ms175976.aspx). ``` IF Object_ID('test', 'U') IS NULL BEGIN BEGIN TRY CREATE TABLE test ( a in...
Concurrent table creation
[ "", "sql", "sql-server", "" ]
My school book [Database Systems](https://rads.stackoverflow.com/amzn/click/com/0321523067) defines cardinality as follows: > The cardinality of a relation is the number of tuples it contains. By contrast, the number of tuples is called the cardinality of the relation and this changes as tuples are added or deleted. H...
They are speaking the same thing and it has to do with tuples (`relational algebra`) or rows (layman's term). When it says high-cardinality are possible values of particular attribute (or field) that are unique and therefore the number of rows or tuples are higher: **Example**: ``` StudentID Lastname Firstname G...
Both definitions are trying to say that cardinality is the "number of rows". The difference is whether the comparison is "in the table" or "in a particular column". The version in your database text book focuses on relational algebra and the structure of tables ("relations" in that lingo). The Wikipedia entry is more...
What is the definition of cardinality in SQL
[ "", "mysql", "sql", "statements", "cardinality", "" ]
I have a column "Time" with Time as its Datatype. I need to get 25% of the value in that column. Please help. I've been banging my head on the wall for the solution.
You need to convert `TIME` to float value. According to [Data type conversion table](http://i.msdn.microsoft.com/dynimg/IC170617.gif) you can do it through `DATETIME`, so: ``` DECLARE @d time = '03:00:00'; SELECT CONVERT(float, CONVERT(datetime, @d)) * 0.25 -- this will be 25% of the value in float ``` And then do r...
``` declare @time NUMERIC set @TIME=(select cast(replace(replace(cast(cast(getdate() as time) as varchar),':',''),'.','') as NUMERIC)*.25) IF LEN(@TIME)=12 BEGIN SELECT '0'+SUBSTRING(CAST(@TIME AS VARCHAR(20)),0,2)+':'+SUBSTRING(CAST(@TIME AS VARCHAR(20)),3,2)+':'+SUBSTRING(CAST(@TIME AS VARCHAR(20)),5,2)+'.'+SUBSTRI...
arithmetic operation on time datatype sql server?
[ "", "sql", "sql-server", "" ]
I have a table with 3 fields: * fullname (Nvarchar(100)) * account (Nvarchar(50)) * birthdate (DateTime) What I need is to create a query where I get all the persons that had their 25th birthday in a selected year. > For example, to know all the persons that had their 25th birthday in the year 2003. Right now I hav...
Do your best to avoid doing calculations or functions on columns used in a `WHERE` clause. instead, change the expression so the column is by itself one one side of the conditional expression, like below: ``` DECLARE @BirthYear int = 2003 - 25; SELECT * FROM dbo.Persons P WHERE P.BirthDate >= DateAdd(year, @BirthY...
You should simply be able to query the year part of the date in question, as you just want to know if the persons 25th birthday fell into that year. ``` DECLARE @Year AS INT SET @Year = 2003 SELECT * FROM Persons P WHERE ((@Year - DATEPART(yy, birthdate)) = 25) ``` This SQLFiddle Demonstrates <http://sqlfiddle.com/...
SQL Server - Get all persons that turned 25 years old in a selected year
[ "", "sql", "sql-server", "" ]
I have this query ``` SELECT DISTINCT [CtrlNo] ,[RefNo] ,[DealNoCat] ,[tCustomer].[CustomerName] ,[tBank].BankName ,[tFIManagers].[FIName] ,[DaysOut] ,[FundDate] ,[Comment] FROM [tContractsInTransit] INNER JOIN tFIManagers ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID INNER JOIN tBank ON tBank.BankID = ...
Assuming a recently new sqlserver you can use a window function like row\_number() as in: ``` SELECT ... FROM ( SELECT [CtrlNo] ,[RefNo] ,[DealNoCat] ,[tCustomer].[CustomerName] ,[tBank].BankName ,[tFIManagers].[FIName] ,[DaysOut] ,[FundDate] ,[Comment] , row_number() over (part...
You want to leave off the DISTINCT keyword and use Aggregate functions. In this case, MIN. Notice that 'DaysOut' is also removed from the GroupBy clause ``` SELECT [CtrlNo] ,[RefNo] ,[DealNoCat] ,[tCustomer].[CustomerName] ,[tBank].BankName ,[tFIManagers].[FIName] ,MIN([DaysOut]) as Min_DaysOut ,[FundDate] ,[Comment] ...
Select only 1 'control number' without using distinct
[ "", "sql", "sql-server", "" ]
I try to join 3 tables like this: table 1 : country ``` Id | Country ------------------- 1 | UK 2 | USA 3 | France ``` table 2 : Dates ``` Id | Date ----------------- 20000101 | 2000-01-01 20000102 | 2000-01-02 ... 20140901 | 2014-09-01 ``` table 3 : Customer ``` Id | Customer | Da...
``` SELECT D.Id,C.Country,COUNT(CU.Id) [number of creation] FROM Country C CROSS JOIN [Date] D LEFT JOIN customer CU on D.Dates.Id = CU.Date_Creation_Id And C.Country.Id = CU.Country_Id GROUP BY D.Id,C.Country ORDER BY D.Id,C.Id ```
You need to generate the list of all countries and dates first, using `cross join`, and then `left join` your data: ``` select d.id as date_id, c.id as country_id, count(cu.id) as cnt from dates d cross join country c left join customers cu on cu.date_creation_id = d.id and cu.country_id = c.id group by...
Join 3 tables with query sql
[ "", "sql", "sql-server", "t-sql", "" ]
I have two tables: TABLE:cities ``` city_id, lat, lon, name, country_id ``` TABLE:countries ``` country_id, name ``` I want a SQL query that returns: ``` cities.lat, cities.lon, cities.name, countries.name(for the corresponding cities.country_id) ``` I swear this must be easy. But I can't get to make it ...
You can use join for this. Also always use alias of table name to understand easy and standard rule too. ``` select ci.lat, ci.lon, ci.name, cn.name from city ci inner join countries cn on ci.country_id = cn.country_id ```
If I got your point, this is the query. ``` SELECT cities.lat, cities.lon, cities.name, countries.name FROM cities INNER JOIN countries ON cities.country_id = countries.country_id ``` By the way, thought it is evident from the name that `cities.country_id` is referencing `countries.country_id`, you should have stated...
SQL query in two tables
[ "", "sql", "" ]
I have Four tables, DiscountCode which describes a discount. Bundles which is basically sold as a product so it contains a productcode Products which are sold as products so it also contains a productcode ProductDiscount code meant to be used to describe the fact that a Bundle/Product can have multiple discount codes...
If you're going to use a Foreign Key then every value must exist as a key on the other table so you can't constrain your column Product Keys if it's got Bundle Keys in it and vice versa. If you need to ensure referential integrity then you'll need to have two Nullable columns. You should probably also have a Check Co...
OK, it is never a good idea to try to constrain to two differnt FKs for the same field, that is a sign of incorrect design. Why is bundle a separate table if it is not using the product codes from the product table? WHy not add a column to the product table to identify if the line item is a bundle or an individual pro...
SQL Server Table Design with Table having foreign key to two other tables
[ "", "sql", "sql-server", "" ]
Given this table: ``` +----+-----------+--------+ | id | condition | values | +----+-----------+--------+ | 1 | a | 1 | +----+-----------+--------+ | 2 | a | 2 | +----+-----------+--------+ | 3 | a | 3 | +----+-----------+--------+ | 4 | a | 4 | +----+-----------...
Something like this: ``` select t.* from table t where id >= 3 and id < (select min(t2.id) from table t2 where t2.condition = 'b'); ``` EDIT: This query works fine on the SQL Fiddle: ``` select t.* from t where id >= 3 and id < (select min(t2.id) from t t2 where t2.condition = 'b'); ```
You need to stop thinking of SQL data as having any order. Think of SQL data in sets; you have to search by *values*, not by positions. ``` SELECT t1.* FROM t AS t1 JOIN ( SELECT MIN(id) AS id FROM t WHERE id >= 3 AND `condition` = 'b' ) AS t2 WHERE t1.id >= 3 AND t1.id < t2.id ORDER BY t1.id ```
MySQL select from specific ID until match condition
[ "", "mysql", "sql", "" ]
We've been using MS Access, with the following syntax for MTD Data that works for us: ``` Between DateSerial(Year(Date()),Month(Date()),1) And DateSerial(Year(Date()),Month(Date())+1,0) ``` We need to transition the above logic to SQL/SSRS for automatic emailed reports, but I cannot get this DateSerial logic to ...
This has been resolved. The ODBC driver does not apparently play well with SSRS. The DateSerial command would not work within the query itself. The workaround was to add the filter to the Dataset. This syntax is what works, but again only in the Dataset filter: [expression] Between [first value box] =DateSerial(Year(No...
You can use the function CONVERT: <http://msdn.microsoft.com/en-us/library/ms187928.aspx> Or the function DATEFROMPARTS if you are using SQL Server 2012: <http://msdn.microsoft.com/en-us/library/hh213228.aspx> Or DATEADD: ``` select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0); -- first day of current month se...
SQL automatic date range using DateSerial function
[ "", "sql", "sql-server", "date", "reporting-services", "" ]
I have two tables, a word frequency table and a word weight table. I need to write a t-sql script or scripts to calculate a weighted score of the word frequency table based on the words and weights given in the word weight table. For example: Word frequency table ``` Word Frequency ,,,,,,,,,,,,,,,, Fat 3 Ugl...
It should be ``` select sum (w.Weight * f.Frequency) from WeightTable w join FreqTable f on f.Word = w.Word ```
Just to prove @wraith answer, here is the code: ``` declare @WordFreq table (Word varchar(max), Frequency int ); declare @WordWeight table (Word varchar(max), Weight int ); insert into @WordFreq( Word, Frequency ) values ( 'Fat', 3) , ( 'Ugly', 2) , ( 'dumb', 2) , ( 'stupid', 3) insert into @WordWeight( Word, Weig...
Multiplying common values between 2 tables
[ "", "sql", "sql-server", "t-sql", "" ]
My question: once I receive the parameter value, I want to modify the contents. E.g. a string parameter value is: `FullName,Address,Category` I want to change `FullName` to `l.FullName` and `Category` to `c.Category` and keep the rest same. ``` ALTER PROCEDURE [dbo].[TableA] @ColNames VARCHAR(1000) AS BEGIN //I ...
How about this? ``` select @ColNames = replace(@ColNames, 'FullName', 'l.FullName'); select @ColNames = replace(@ColNames, 'Category', 'c.Category'); ```
Yes, you can do that - @ColNames is a variable - you can manipulate the contents of it. ``` ALTER PROCEDURE [dbo].[TableA] @ColNames VARCHAR(1000) AS BEGIN -- I want to modify the contents of @ColNames here SET @ColNames = REPLACE(@ColNames, "FullName", "l.FullName") SET @ColNames = REPLACE(@ColNames, "Category", ...
TSQL replace my Stored procedure string parameter
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I'm mainly a presentation/logic tier developer and don't mess around with SQL all that much but I have a problem and am wondering if it's impossible within SQL as it's not a full programming language. * I have a field ContactID which has an CompanyID attached to it * In another table, the CompanyID is attached to Comp...
You want a correlated subquery: ``` SELECT ct.ContactID, stuff((SELECT ', ' + co.CompanyName AS [text()] FROM TblContactCompany cc INNER JOIN TblCompany co ON cc.CompanyID = co.CompanyID WHERE cc.ContactID = ct.ContactId ...
You could use a table variable to store the required `x.ContactID` and in your main query in the `WHERE` clause use `IN` clause like below ``` WHERE ... x.ContactID IN (SELECT ContactID FROM @YourTableVariable) ```
SQL Server dynamically change WHERE clause in a SELECT based on returned data
[ "", "sql", "sql-server", "dynamic", "" ]
I'm trying to import a flat file into an oledb target sql server database. here's the field that's giving me trouble: ![enter image description here](https://i.stack.imgur.com/CBYws.png) here are the properties of that flat file connection, specifically the field: ![enter image description here](https://i.stack.img...
After failing by increasing the length or even changing to data type text, I solved this by creating an XLSX file and importing. It accurately detected the data type instead of setting all columns as `varchar(50)`. Turns out `nvarchar(255)` for that column would have done it too.
Here is what fixed the problem for me. I did not have to convert to Excel. Just modified the DataType when choosing the data source to "text stream" (Figure 1). You can also check the "Edit Mappings" dialog to verify the change to the size (Figure 2). **Figure 1** [![enter image description here](https://i.stack.imgu...
Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot
[ "", "sql", "sql-server", "t-sql", "ssis", "" ]
I am working on a project with lots of large `SQL` requests, I want to know: what provides a better performance in term of speed between: * Join Queries * Sub-Queries For example ``` SELECT artistName FROM artist JOIN group On group.location = artist.location AND group.available = 'true' ``` --- ``` SELECT artis...
As you have not mentioned that you need to know the answer for any specific query, I am assuming that you asked the question in general whether `join` queries are faster than `subqueries` or not. The answer is in most cases `join` queries are faster than `subqueries`. I too didn't know the answer, so after I saw your q...
I'm not quite sure your second query is valid SQL, but the answer to your question fortunately isn't related to this. Performance is dependant on many, many factors, so the best answer you can get for this kind of question is "It depends". First, make sure you need to optimize your queries. If the current runtime is ...
SQL sub-queries and Join Queries
[ "", "sql", "join", "optimization", "subquery", "query-optimization", "" ]
How to add compare select statement in `if()` condition in Oracle pl-sql ``` IF( (v_c1.int_rate = '0') AND (local_type_advances in (SELECT DISTINCT(REF_CODE) FROM XYZ WHERE REF_REC_TYPE = '39' AND DEL_FLG = 'N' ...
What I have done is, I have stored result of that select statment in localvariable as varchar2. And added this local varchar in that if condition's in clause as result instead of that select statment ``` select '''' || listagg(REF_CODE, ''',''' ) within group (order by REF_CODE) || '''' as type_advances into local_typ...
Since you can't have a select statement in an IN clause, break it into two pieces. Select the range you need to search into a variable, then search that variable to see if the value is in there. Here is a working example using LISTAGG() to return a comma-separated list into a variable and REGEXP\_LIKE to test the list ...
How to add compare select statement in if() condition oracle pl-sql
[ "", "sql", "oracle", "plsql", "" ]
I have a problem and I can't figure out the solution. With a previously asked question ([SELECT rows with time 30 minutes or less?](https://stackoverflow.com/questions/10459608/select-rows-with-time-30-minutes-or-less)) I tried to make my COUNT(\*) function work but I can't make it work. Anybody an idea? ``` SELECT CO...
The MySQL syntax is: ``` WHERE ad_view_time >= now() - interval 30 minute ```
DateAdd is missspelled: It must be DATE\_ADD (with underscore). See the [documentation](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html)
How to use DATEADD in MySQL?
[ "", "mysql", "sql", "" ]
I want to clean some contact numbers in a sql server database table name is ronnie\_list and column name is "Name Phone#" numbers can be in format example formats are ``` T: (985)-124-5601 (985)124-5601 985)-124-5601 985.124.5601 9851245601 985124-5601 EX 1432 985-(124)-5601 ``` I want them in this format 985-124-5...
## Create a Function ``` ALTER FUNCTION dbo.udf_GetNumeric (@strAlphaNumeric VARCHAR(1000)) RETURNS VARCHAR(1000) AS BEGIN DECLARE @intAlpha INT SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric) BEGIN WHILE @intAlpha > 0 BEGIN SET @strAlphaNumeric = STUFF(@strAlphaNumeric, ...
1. Write `REPLACE()` around the column untill you remove all your unwanted symbols. like this. `REPLACE(REPLACE([COLUMN],')',''),'(','') --Only Brackets are removed here.` ``` (985)124-5601 becomes 985124-5601 985124-5601 EX 1432 becomes 9851245601 1432 ``` 2. Once symbols are removed, Remove space as well, you can ...
need help in cleaning contact number format
[ "", "sql", "sql-server", "" ]
I have the following table COUNTRY\_PEOPLE: ``` COUNTRY - CITY - YEAR - PEOPLE ENGLAND - LONDON 1980 - 7834020 ENGLAND - LONDON 2010 - 8308369 ENGLAND - DERBY 1980 - 231483 ENGLAND - DERBY 2010 - 233700 FRANCE - PARIS 1980 - 2174654 FRANCE - PARIS 2010 - 2274880 FRANCE - NANTES 1980 - 279321 FRANCE - NANTES 2...
Try: ``` SELECT Country, City, AVG(CASE WHEN Year=2010 THEN People END)-AVG(CASE WHEN Year=1980 THEN People END) as AvgPeople FROM COUNTRY_PEOPLE GROUP BY Country, City ``` See `Demo` **Result**: ![enter image description here](https://i.stack.imgur.com/jVPED.png)
Please Check below query ``` SELECT a.COUNTRY,a.CITY,(ISNULL(a.PEOPLE,0) - ISNULL(b.PEOPLE,0)) AS PEOPLE FROM (SELECT COUNTRY ,CITY , SUM(ISNULL(PEOPLE,0)) AS PEOPLE FROM COUNTRY_PEOPLE WHERE [YEAR] = 2010 GROUP BY COUNTRY ,CITY) a LEFT OUTER JOIN (SELECT COUNTRY ,CITY , SUM(ISNULL(PEOPLE,0)) AS PEOPLE FROM ...
SQL - difference and average between more records
[ "", "sql", "h2", "" ]
I am struggling to get this query to work . I have three tables and I want to do a query to get the red area. Each circle is a table with different structure. I have managed a lot of combinations of inner joins but i specially cant get all the red areas. A Payments : idPayment , idInvoice , Amount , date. B Invoice :...
You were pretty close -- another `OUTER JOIN` and some `WHERE` criteria will do the trick: ``` SELECT B.idInvoice, A.idPayment, C.idNote FROM Invoice b LEFT JOIN payments a ON a.idInvoice=b.idInvoice LEFT JOIN PromissoryNotes c ON c.idInvoice=b.idInvoice WHERE a.idInvoice IS NOT NULL OR c.idInvoice IS ...
You could do this two ways: 1) Create a set A that is the inner join of B and A, create a set C that is the inner join of B and C, then union A and C. 2) Create a sub query that inner joins A and B, then full outer join to a sub query that inner joins C and B. Example of 1) ``` SELECT b.idInvoice FROM Invoice B J...
Joining three tables - Mysq-l an inner and outer join perhaps?
[ "", "mysql", "sql", "join", "" ]
I'm using postgreSQL 9.2. Let I've the following table: ``` id name definition serial varchar(128) text 1 name1 definition1 .......................................... ``` I need to write a query that remove all rows with the same name such that every row will have unique...
Use row\_number() function on name and remove all rows that have row\_number() > 1 Here is an example query: [Deleting duplicates](http://wiki.postgresql.org/wiki/Deleting_duplicates)
``` DELETE FROM mytable dd WHERE EXISTS ( SELECT * FROM mytable ex WHERE ex.name = dd.name AND ex.id < dd.id ); ```
SQL query for removing non-unique row
[ "", "sql", "postgresql", "" ]
\*\*Edit: RESOLVED - Thank you all! I can't 'vote up' any of your replies due to my low rep, but I appreciate them all! Edit 2: Rep high enough now, vote up's to all!\*\* ok, I have a sproc that runs a few inserts, assigning the new record identity to a variable, then inserting those into another table. The issue is ...
After you insert, save `scope_identity()` in a variable if `@@rowcount` is greater than 0. EX: ``` DECLARE @MY_NEW_ID INT INSERT INTO TABLE2 (COL1) SELECT VAL1 FROM TABLE1 WHERE X=Y IF @@ROWCOUNT>0 BEGIN SET @MY_NEW_ID = SCOPE_IDENTITY() END /* DO MORE INSERTS HERE ... */ IF @MY_NEW_ID IS NOT NULL BEGIN IN...
You can try this: ``` IF @@ROWCOUNT<>0 SET @NewId2 = SCOPE_IDENTITY(); ```
SCOPE_IDENTITY, multiple inserts, carries value from previous insert if current insert doesn't insert
[ "", "sql", "sql-server", "" ]
I want to run sql commands directly in my rails application. Is there any gem to do this? For example: I want to delete a user , who is having id 2 using below sql command ``` delete from users where id=2 ```
Yes. We can do that by using [query\_exec](https://rubygems.org/gems/query_exec)
``` ActiveRecord::Base.connection.execute("delete from users where id=2") ```
Ruby gem to run sql commands
[ "", "sql", "ruby", "ruby-on-rails-3", "rubygems", "" ]
I have a table with a field datatype of NVarchar2(4000) I am moving data from a SQL Server to an Oracle Server. The SQL Server datatype is also nvarchar(4000). I have checked the MAX Size of this field on the SQL Server side, and the MAX is 3996, which is 4 characters short of the 4000 limit. When I try to insert this...
There is a limit of 4000 bytes not 4000 characters. So NVARCHAR2(4000) with an AL16UTF16 national character set would occupy the maximum 4000 bytes. From the [oracle docs of MAX\_STRING SIZE](http://docs.oracle.com/database/121/REFRN/refrn10321.htm#REFRN10321): > Tables with virtual columns will be updated with new d...
First, as others have pointed out, unless you're using 12.1, both `varchar2` and `nvarchar2` data types are limited in SQL to 4000 bytes. In PL/SQL, they're limited to 32767. In 12.1, you can increase the SQL limit to 32767 using the [`MAX_STRING_SIZE` parameter](http://docs.oracle.com/database/121/REFRN/refrn10321.htm...
Oracle Insert Into NVarchar2(4000) does not allow 4000 characters?
[ "", "sql", "sql-server", "oracle", "insert", "" ]
Let's say a patient makes many visits. I want to write a query that returns distinct patient rows based on their earliest visit. For example, consider the following rows. ``` patients ------------- id name 1 Bob 2 Jim 3 Mary visits ------------- id patient_id visit_date reference_number 1 ...
Use `distinct on` ``` select distinct on (p.id) p.id, p.name, v.visit_date as first_visit_date, v.reference_number from patients p inner join visits v on p.id = v.patient_id order by p.id, v.visit_date ``` <http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT>
Avoiding the `DISTINCT ON(p.id)`, but using a plain old `NOT EXISTS(...)` instead ``` SELECT p.id, p.name , v.first_visit_date, v.reference_number FROM patients p JOIN visits v ON p.id = v.patient_id -- exclude all join-products that are not the first for a patient. WHERE NOT EXISTS ( SELECT * FROM visi...
In one to many relationship, return distinct rows based on MIN value
[ "", "sql", "postgresql", "one-to-many", "greatest-n-per-group", "" ]
``` INSERT INTO `table` VALUES ('val1','val2','val3') INSERT INTO `table` SET a='val1',b='val2',c='val3' ``` Both are used for the same purpose.but which i should use? in which case? and why?
They are identical, but the first one is [standard SQL](http://en.wikipedia.org/wiki/Insert_(SQL)#Basic_form). As the SQL parser treats them as synonyms there is no difference in performance, usage or anything. As always, prefer using the standardized form, the first syntax in this case, for portability and compatibili...
As far as I can tell, both syntaxes are equivalent. ``` The first is SQL standard, the second is MySQL's extension. ``` So they should be exactly equivalent performance wise. <http://dev.mysql.com/doc/refman/5.6/en/insert.html> says: ``` INSERT inserts new rows into an existing table. The INSERT ... VALUES and INS...
Insert Set or Insert Values
[ "", "mysql", "sql", "" ]
i asking your help to write an query for checking the availability of an room inside MySql. Currently i have this kind of table: ``` ROOM | FROM | TO ----------------------------- 101 | 2014-08-09 | 2014-08-14 102 | 2014-08-09 | 2014-08-14 ... ... ... ``` So i have the room 101 b...
First, let's generalize an algorithm for how to check for an overlap between intervals `[a,b]` and `[c,d]`. Note the square braces on those intervals, which means an inclusive interval. We can use this logic to check for an interval overlap: ``` a <= d and b >= c ``` If that condition is true, then we have an overlap...
If you want to check whether room is available for the whole period, look for existing bookings that overlap with period in question: ``` SELECT order_id FROM booking WHERE `ROOM` = '101' AND `FROM` <= '2014-08-20' AND `TO` >= 2014-08-08' ``` If query returns rows, you have a reservation conflict and room is not...
Find booking overlaps to check dates availability
[ "", "mysql", "sql", "" ]
Let's say I have the following table. ![enter image description here](https://i.stack.imgur.com/cKw4S.jpg) Given 3 user names and one company name, I need to check if user1 with the given company name, user2 with the same given company name and user3 with the same given company name all are in the table. If they are ...
You can use `MIN()` and `CASE` to do this: ``` SELECT MIN(CASE WHEN company = 'walmart' THEN 'True' ELSE 'False' END) FROM Table1 WHERE users IN ('a','b','e') --False SELECT MIN(CASE WHEN company = 'google' THEN 'True' ELSE 'False' END) FROM Table1 WHERE users IN ('c','d','e') --True ``` If the values for comparis...
You should use a case: ``` select CASE when user = '[given user1]' and company = '[given company name]' then "true" end as [company name], CASE when user = '[given user2]' and company = '[given company name]' then "true" end as [company name2] from [table] ``` You can do this for as many company name as you ...
sql how to check multiple data existed in db
[ "", "sql", "sql-server", "database", "" ]
In Oracle pl/sql, how do I retrieve only numbers from string. e.g. 123abc -> 123 (remove alphabet) e.g. 123\*-\*abc -> 123 (remove all special characters too)
Several options, but this should work: ``` select regexp_replace('123*-*abc', '[^[:digit:]]', '') from dual ``` This removes all non-digits from the input. If using in pl/sql, you could do an assignment to a variable: ``` declare l_num number; l_string varchar2(20) := '123*-*abc'; begin l_num := regexp_...
``` your_string := regexp_replace(your_string, '\D') ```
Oracle retrieve only number in string
[ "", "sql", "oracle", "" ]
I have a set of tables (with several one-many relationships) that form a single "unit". I need to ensure that we weed out duplicates, but determining duplicates requires consideration of all the data. To make matters worse, the DB in question is still in Sql 2000 compatibility mode, so it can't use any newer features....
So, I managed to figure out what I needed to do. It's a little clunky though. First, you need to wrap the Xml `Select` statement in another select against the Unit table, in order to ensure that we end up with xml representing only that unit. ``` Select Id, ( Select Action, TriggerType, IU.TypeId, ...
If you want to determine whether record is duplicate or not, you don't need to combine all values into one string. You can do this with ROW\_NUMBER function like this: ``` SELECT Action, TriggerType, U.Id, U.TypeId, U.Message, C.Value, I.QuestionId, I.Sequence, ROW_NUMBER () OVER (PARTITION BY <LI...
Identify Duplicate Xml Nodes
[ "", "sql", "sql-server", "t-sql", "hashcode", "" ]
I've the following table: ``` UserId Start Stop 1550f503-914e-4f83-af2b-249d54cce369 2014-04-15 18:20:23.000 2014-04-15 18:21:38.000 1550f503-914e-4f83-af2b-249d54cce369 2014-04-15 18:20:23.000 2014-04-15 18:21:38.000 1550f503-914e-4f83-af2b-249d54cce369 201...
``` select UserId, COUNT(UserId) from UserSessions GROUP BY UserId ```
I think this should do it: ``` SELECT UserId, COUNT(UserId) FROM UserSessions GROUP BY UserId ``` You don't have to include the DISTINCT USERID part in the WHERE clause, as it will group on the IDs.
Get the number of same field from a table in SQL
[ "", "sql", "sql-server", "" ]
I have found several examples of SQL queries which will find missing numbers in a sequence. For example this one: ``` Select T1.val+1 from table T1 where not exists(select val from table T2 where T2.val = T1.val + 1); ``` This will only find gaps in an existing sequence. I would like to find gaps in a sequence star...
This is quite easy in Postgres: ``` select x.i as missing_sequence_value from ( select i from generate_series(0,5) i -- 0,5 are the lower and upper bounds you want ) x left join the_table t on t.val = x.i where t.val is null; ``` SQLFiddle: <http://www.sqlfiddle.com/#!15/acb07/1> **Edit** The Oracle soluti...
If you have to option to use a [common table expression](http://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression) you can generate a sequence of numbers and use that as the source of numbers. The variables `@start` and `@end` defines the range of numbers (you could easily use max...
SQL to find missing numbers in sequence starting from min?
[ "", "sql", "oracle", "" ]
I'm working on a movie database and I thought it might be a good idea to have some type of parental control in place for the future. I wrote some SQL code and it works for the most part, but i don't know why. In my main movies table I have movies rated with the standard rating g, pg, pg-13, r, and NC-17. Here is the ...
SQL doesn't understand the movie rating system. The `<` operator looks at strings in alphabetical order. So when you say `< 'R'`, it's looking for for all ratings that start with a letter before `R` in the alphabet. Since there are a limited number of options for ratings, you're best off doing something along the lines...
How is MySQL to know `R` is less than `NC-17`? MySQL knows how to sort numbers and letters but not movie ratings. You have to assign the ratings numbers and sort based on that. For example: ``` Rating Value ------------------ G 1 PG 10 PG-13 20 R 30 NC-17 40 ``` Than give ...
SQL code need help understanding
[ "", "mysql", "sql", "" ]
Not-null dependent means that at least 1 field is not null. Ideas? Example: email and phone-number can be not-null dependent. If email is null, phone-number must be not-null. If phone-number is null, email must be not-null.
MySQL doesn't support CHECK constraints, despite [this feature having been requested since 2004.](http://bugs.mysql.com/bug.php?id=3464) Annoyingly, it parses CHECK constraint syntax, but it doesn't store the constraint or enforce it later. I have thought for a long time that this is misleading to accept an SQL statem...
``` CREATE TABLE T ( EMAIL VARCHAR(256), PHONE VARCHAR(10) ); ALTER TABLE T ADD CONSTRAINT CHECK (EMAIL IS NOT NULL) OR (PHONE IS NOT NULL); ``` Some SQL dialects allow or require you to put the `CHECK` constraint in the `CREATE TABLE` statement.
How to define a table in SQL with 2 fields being not-null (mandatory) dependent?
[ "", "mysql", "sql", "create-table", "" ]
I have a table in which 10 records available(insert record using bulk insert) now I want select some record with row number and some specific condition. No my problem how we get actual row number of the record. Bulk insert code ``` BULK INSERT WorkDataLoad FROM 'D:\NPfiles\xyz.txt' with ( TABLOCK ) ``` Table Recordl...
Use `row_number()` to first assign a row number, then select only the rows you require: ``` with cteRows as ( Select RecordLine, rn = ROW_NUMBER() OVER (ORDER BY RecordLine DESC) from WorkDataLoad ) select rn, RecordLine from cteRows where Recordline IN ('Record1', 'Record3', 'Record5', '...
``` SELECT t.* FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY RecordLine DESC ) AS RowNo, Recordline FROM WorkDataLoad ) AS t WHERE t.Recordline = 'Record1' OR t.Recordline = 'Record3' OR t.Recordline = 'Record5' OR t.Recordline = 'Record6' ...
Get actual row number of the record in sql
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2012", "" ]
I'm using a request to get a collection of columns name: ``` SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE [...] ``` From this collection, I'd like to count every not null, not empty value from the original table group by column name. Let's say I have a table containing ``` COL1 | COL2 | COL3 -----------...
Here is a simple process. Run the following query: ``` SELECT 'SELECT ''' + COLUMN_NAME + ''', COUNT(['+COLUMN_NAME']) as NotNull FROM [' +SCHEMA_NAME+ '].['+TABLE_NAME+ '] union all ' FROM INFORMATION_SCHEMA.COLUMNS WHERE [...] ``` Copy the results into a query window, remove the final `union all`, and run the query...
The below code seems to work for your issue ``` create table sample ( col1 varchar(10), col2 varchar(10), col3 varchar(10) ) INSERT INTO sample (COL1,COL2,COL3) VALUES ('VAL1 ',' VAL2 ',NULL); INSERT INTO sample (COL1,COL2,COL3) VALUES ('VAL3 ',' ',' VAL4'); INSERT INTO sample (COL1,COL2,COL3) VALUES ('V...
Selecting columns from a query
[ "", "sql", "sql-server", "t-sql", "analytics", "" ]
I'm going to count returned rows by this query: ``` select * from tableName where( number > 1000); ``` I tried this query to get rows count: ``` select count(*) as count from (select * from tableName where( number > 1000)); ``` but I got syntax error. What is wrong with that?
This works if you are using nested query & don't use 'count' as your temporary variable name: ``` select count(temp.id) as num from (select * from tableName where number > 1000) temp ```
You dont want Nested Query Just Use ``` select count(*) as count from tableName where number > 1000 ; ```
counting rows of selected data in mysql
[ "", "mysql", "sql", "" ]
I am trying to extract those Jars which contain both `Bunties` and `Candies`. ``` Row# Column1 Columm2 --------------------------------------- 1 Jar1 Bunties 2 Jar1 Candies 3 Jar1 Biscuits 4 Jar1 Jellies...
You could use a `GROUP BY` with a `HAVING` to get the result: ``` select Column1 from dbo.yourtable where Columm2 in ('Bunties', 'Candies') group by Column1 having count(distinct Columm2) = 2; ``` Your `WHERE` clause will include the values that you are looking for, then you `GROUP BY` the `Column1` and count the di...
You could use EXISTS: ``` SELECT Distinct t.Column1 FROM dbo.TableName t WHERE t.Columm2 IN ('Bunties', 'Candies') AND EXISTS( SELECT 1 FROM dbo.TableName t2 WHERE t2.Column1 = t.Column1 AND t2.Columm2 <> t.Columm2 AND t2.Columm2 IN ('Bunties', 'Candies') ) ```
Get distinct Column1 values which contains all required Column2 values
[ "", "sql", "sql-server-2008", "" ]
I've been playing around with the sample on [Jeff' Server blog](http://weblogs.sqlteam.com/jeffs/archive/2004/11/10/2737.aspx) to compare two tables to find the differences. In my case the tables are a backup and the current data. I can get what I want with this SQL statement (simplified by removing most of the column...
Could you use the following setup to accomplish your goal? ``` SELECT 'New not in Old' Descriptor, * FROM ( SELECT * FROM [JAS001new].[dbo].[AR_CustomerAddresses] EXCEPT SELECT * FROM [JAS001].[dbo].[AR_CustomerAddresses] ) a UNION SELECT 'Old not in New' Descriptor, * FROM ( SELECT * FROM ...
You can't add the table name there because union, except, and intersection all compare all columns. This means you can't differentiate between them by adding the table name to the query. A group by gives you control over what columns are considered in finding duplicates so you can exclude the table name. To help you w...
SQL Server : compare two tables with UNION and Select * plus additional label column
[ "", "sql", "sql-server", "union", "intersect", "" ]
Having given up on SQL Azure Data Sync for synchronizing data between two SQL Azure databases, how can I remove all the DataSync related objects (tables, triggers etc)? E.g: ``` DataSync.<table>_dss_tracking DataSync.schema_info_dss DataSync.scope_config_dss DataSync.scope_info_dss ``` And all the other objects? Is ...
There is an article on msgooroo.com: <https://msgooroo.com/GoorooTHINK/Article/15141/Removing-SQL-Azure-Sync-objects-manually/5215> Essentially the script is as follows: ``` -- Triggers DECLARE @TRIGGERS_SQL VARCHAR(MAX) = ( SELECT 'DROP TRIGGER [' + SCHEMA_NAME(so.uid) + '].[' + [so].[name] + '] ' ...
I recently ran into this issue and while the script in the accepted answer did remove the DataSync schema, it did not remove the dss or TaskHosting schemas nor the symmetric key objects that were preventing me from exporting my database. I ended up needing to contact Azure support to get everything removed. Here is th...
How to remove SQL Azure Data Sync objects manually
[ "", "sql", "t-sql", "azure-sql-database", "" ]
I know that in SQL when we compare two NULL values, result is always false. Hence, statements like ``` SELECT case when NULL = NULL then '1' else '0' end ``` will always print '0'. My question is how functions like `ISNULL` determine whether value is null or not. Because, as per my understanding (and explained in abo...
Your initial assumption appears to be that `ISNULL` is an alias for existing functionality which can be implemented directly within SQL statements, in the same way that a SQL function can. You are then asking how that function works. This is an incorrect starting point, hence the confusion. Instead, like similar comma...
You need to set the `set ansi_nulls off` and then check your result. Null can be thought of as an unknown value and when you are comparing two unknown values then you will get the result as false only. The comparisons null = null is undefined. ``` set ansi_nulls off SELECT case when NULL = NULL then '1' else '0' end `...
NULL comparison in SQL server 2008
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
HEXTORAW is a function found in several RDBMS's like [Oracle](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions064.htm), and [DB2 on LUW](http://www-01.ibm.com/support/knowledgecenter/SSEPGG_10.5.0/com.ibm.db2.luw.sql.ref.doc/doc/r0059480.html). It takes a character, or integer input, and basically casts ...
In order to have a complete algorithm here: Given a character string as an input parameter 1.Validate that the character string contains only the numbers 1-9 or the letters A-F. 2.Calculate the binary value by iterating over each character, and concatenating the corresponding binary value: ``` binary hexadecima...
From this page: <http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i46018> > When Oracle automatically converts RAW or LONG RAW data to and from > CHAR data, the binary data is represented in hexadecimal form, with > one hexadecimal character representing every four bits of RAW data. > For exam...
How does the HEXTORAW() function work? What is the algorithm?
[ "", "sql", "oracle", "algorithm", "rdbms", "db2-luw", "" ]
Need help figuring out how to do a cross-tabulated report within one query. There are 3-4 tables involved but the users table may not need to be included in the query since we just need a count. I have put together a screenshot of the table schema and data as an example which can be seen below: ![](https://i.stack.img...
``` SELECT MIN(ro.OptionText) RowOptionText, MIN(co.OptionText) RowOptionText, COUNT(ca.AnswerID) AnswerCount FROM tblQuestions rq CROSS JOIN tblQuestions cq JOIN tblOptions ro ON rq.QuestionID = ro.QuestionID JOIN tblOptions co ON cq.QuestionID = co.QuestionID LEFT JOIN tblAnswers ra ON ra.OptionID = ro.OptionID LEF...
I think I see the problem. I know you can't modify the schema, but you need a conceptual table for the crosstab information such as which questionID is the rowHeader and which is the colHeader. You can create it in an external data source and join with the existing source or simply hard-code the table values in your sq...
SQL Cross Tab Query
[ "", "sql", "sql-server", "performance", "t-sql", "sql-server-2012", "" ]
I have a table that looks like this ``` dbo.Box ID SourceID OverrideQueueID 1 1 NULL 2 1 2 3 2 NULL ``` I need to figure out a way to say if the OverrideQueueID IS NULL then just do a join from dbo.Box to dbo.Source.ID, otherwise if OverrideQueueID IS NOT NULL ...
I hope a union will help you, like given below. ``` Select Col1,Col2 From dbo.Box B Join dbo.Source S On S.Id = b.SourceID Where B.OverrideQueueID is Null Union Select Col1,Col2 From dbo.Box B Join dbo.Queue Q On Q.Id = b.SourceID Where B.OverrideQueueID is Not Null ```
One possible way: ``` select * from Box as a join Box as b ON a.OverrideQueueID is null and a.ID = b.SourceID join Queue as q ON a.OverrideQueueID is not null and a.ID = q.ID ```
Conditional join to two different tables based on 2 columns in 1 table
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2012", "" ]
Is there any diffrence between the time taken for `Select *` and `Select count(*)` for the table having no primary key and other indexes in SQL server 2008 R2? I have tried `select count(*)` from a view and it has taken 00:05:41 for 410063922 records. `Select (*)` from view has already taken 10 minutes for first 60000...
The execution time difference is due to the fact that `SELEC *` will show the entire content of your table and the `SELECT COUNT(*)` will only count how many rows are present without showing them. ## **Answer about optimisation** In my opinion you're taking the problem with the wrong angle. First of all it's importan...
`count(*)` returns just a number and `select *` returns all the data. Imagine having to move all that data and the time it takes for your hundred of thousands of records. Even if your table was indexed probably, running `select *` on your hundreds of thousands of records will still take a lot of time even if less than ...
Why select count(*) is faster the select * even if table has no indexes?
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have multiple tables that I'm trying to join. I have added indexes to the tables to increase the speed but is still taking a long time to join. I suspect this is expected but i was wondering if there is a more efficient way to create a join with multiple tables. I also set the net\_read\_timeout = to 150 since i was ...
Although the query itself looks simple yet strange, here it is with joins. Note... Since you had a=b b=c c=d etc... it also means a=r a=s a=t etc... So, instead of having all rely on the alias in front of it, it MIGHT help the engine to have all of the other speed tables as directly joined to the root "a" level alias a...
If the `speed` column is not unique in those tables (and likely it's not; given that you said you added an index with `speed` as a leading column... If there are multiple rows with the same value of `speed`, in those tables, then your query could be creating an *immense* intermediate set. Let's do some simple math. I...
optimization for joining many tables in mysql
[ "", "mysql", "sql", "" ]
I do quite a bit of data analysis and use SQL on a daily basis but my queries are rather simple, usually pulling a lot of data which I thereafter manipulate in excel, where I'm a lot more experienced. This time though I'm trying to generate some Live Charts which have as input a single SQL query. I will now have to cr...
Use [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx) ``` SELECT c.Agent, SUM(s.price) AS TotalSales, SUM(CASE WHEN s.OutboundCallDate IS NOT NULL THEN s.price ELSE 0 END) AS OutboundSales FROM contact c, sales s WHERE c.id = s.id GROUP BY c.agent ``...
I think the code would look ``` SELECT contact.agent, SUM(sales.price) FROM contact, sales WHERE contact.id = sales.id AND SUM(WHERE sales.OutboundCallDate) GROUP BY contact.agent ```
Adding another column based on different criteria (SQL-server)
[ "", "sql", "sql-server", "" ]
I have a table: ``` model1 model2 speed ram ----- ------ ------ ---- 1121 1233 750 128 1232 1233 500 64 1232 1260 500 32 1233 1121 750 128 1233 1232 500 64 1260 1232 500 32 ``` And I need to remove duplicate pairs of model1 and model2. Here these rows are 4-6. Looking at t...
Untested, use at your own risk, but it could serve as starting point to see unique only: ``` select model1,model2 from T EXCEPT select model2,model1 from T where model2 > model1; ```
If you want to filter out duplicates from your results, seems like it should be simply: ``` where cast(model1 as char(4))+cast(model2 as char(4))<>cast(model1 as char(4))+cast(model2 as char(4)) AND cast(model1 as char(4))+cast(model2 as char(4))<>cast(model2 as char(4))+cast(model1 as char(4)) ``` If you want to SEL...
Duplicates by few rows
[ "", "sql", "sql-server", "database", "duplicates", "" ]
I'm trying to find rows with same Number but different Value, I arrived to this query: ``` DECLARE @Table1 AS TABLE (Number INT, Value int ) INSERT @Table1 VALUES (32, 3) INSERT @Table1 VALUES (32, 5) INSERT @Table1 VALUES (45, 5) INSERT @Table1 VALUES (45, 5) SELECT DISTINCT Number, COUNT(Value) FROM @Table1 GROUP B...
Does your query return expected results? I usually see it written like this: ``` SELECT Number, COUNT(DISTINCT Value) FROM @Table1 GROUP BY Number HAVING COUNT(DISTINCT Value) < 2 ``` Or, based on your comment below, you could do this: ``` SELECT Number FROM @Table1 a WHERE EXISTS(SELECT * FROM @Table1 b WHERE a.Num...
``` SELECT Number, COUNT(distinct Value) as value FROM @Table1 GROUP BY Number ```
Get Values from a column with different values in another
[ "", "sql", "sql-server", "" ]
suppose I have a table name : **TEST**, that it has 2 columns **ID** and **CONTENT**, like this : **TEST** TABLE : **ID** ======= **CONTENT** 0 ======= hello world now, how can I split **CONTENT** column from 0 index to 5 index to retrieve just **hello** word? (at here, **ID**=> 0) (I just want to use sql, not othe...
``` select substr(content, 0, 5) from test ```
> The `substr(X,Y,Z)` function returns a substring of input string X that > begins with the Y-th character and which is Z characters long. If Z is > omitted then `substr(X,Y)` returns all characters. The answer to your question is: ``` select substr(content, 0, 5) from test where id >= 0; ```
how to use substring function sqlite android
[ "", "android", "sql", "sqlite", "" ]
I'm looking to essentially have a centralized table with a number of lookup tables that surround it. The central table is going to be used to store 'Users' and the lookup tables will be user attributes, like 'Religion'. The central table will store an Id, like ReligionId, and the lookup table would contain a list of re...
Optimization techniques will likely depend on the size of the center table and intended query patterns. This is very similar to what you get in data warehousing star schemas, so approaches from that paradigm may help. For one, ensuring the size of each row is absolutely as small as possible. Disk space may be cheap, b...
Since you are set on your way. you can consider duplicating data in order to join less times in a similar way to what is done in olap database. <http://en.wikipedia.org/wiki/OLAP_cube> With that said I don't think this is the best way to do it if you have 100 properties.
100 Join SQL query
[ "", "sql", "sql-server", "normalization", "" ]
I am trying to select the tables from my database where they start with **srt\_factor\_** (which in this case are only the first two). My tables are: ``` srt_factor_20121119 srt_factor_20130430 srt_factorxyzk_20130813 ``` My query erroneously returns instead of the first two tables only, the last one as well (srt\_f...
`'_'` is a wildcard in SQL Server, representing one character. Try this instead: ``` Select (TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME LIKE 'srt[_]factor[_]%'; ```
The problem is in the underscores which have a special meaning in SQL (it's like the `*` wildcard, but for exact one character). You have to escape them like this: ``` TABLE_NAME LIKE 'srt[_]factor[_]%' ``` See [MSDN](http://msdn.microsoft.com/en-us/library/ms179859(v=sql.110).aspx) on the use of wildcard characters ...
Wildcard query % fetches wrong data
[ "", "sql", "sql-server", "" ]
I have a problem with DATEDIFF function. My date format is `dd/mm/yyyy`. `@START_DATE = 01/02/2004` `@END_DATE = 29/01/2014` The query `(DATEDIFF(DAY,@START_DATE,@END_DATE) / 365)` return `10`, but the number of correct years is `9`. This happens because my query does not consider leap years. What I can do to kee...
I believe the following logic does what you want: ``` datediff(year, @START_DATE - datepart(dayofyear, @START_DATE) + 1, @END_DATE - datepart(dayofyear, @START_DATE) + 1 ) as d2 ``` Note: This treats that dates as `datetime`, because arithmetic is easier to express. You can also ...
Technically there would be 365.242 days in a year, when accounting for leap years so: ``` FLOOR(DATEDIFF(day, @STARTDATE, @ENDDATE) / 365.242) ``` Should be more correct. Test: ``` SELECT FLOOR(DATEDIFF(day, '1980-01-16','2015-01-15') / 365.242), FLOOR(DATEDIFF(day, '1980-01-16','2015-01-16') / 365.242) ``...
(Transact-SQL) DATEDIFF and leap years
[ "", "sql", "sql-server", "t-sql", "" ]
All, This is my first post on Stackoverflow, so go easy... I am using SQL Server 2008. I am fairly new to writing SQL queries, and I have a problem that I thought was pretty simple, but I've been fighting for 2 days. I have a set of data that looks like this: ``` UserId Duration(Seconds) Month 1 ...
You are joining two queries together here: * Per-User average per month * All Organisation average per month If you are only going to return data for one user at a time then an inline select may give you joy: ``` SELECT AVG(a.duration) AS UserAvergage, (SELECT AVG(b.Duration) FROM tbl b WHERE MONTH(b.StartDate) =...
missing partition clause in Average function ``` OVER ( Partition by MONTH(StartDate)) ```
SQL Aggregates OVER and PARTITION
[ "", "sql", "sql-server", "window-functions", "" ]
I've got a small problem I ran into. I want o create a form that ask for a procedure name and returns the params of the stored procedure and the columns that the procedure returns. For example ``` CREATE PROCEDURE abc @Param1 int, @Param2 varchar(1) as SELECT * FROM TableA WHERE Param1 = @Par...
You can use **sys.dm\_exec\_describe\_first\_result\_set**. See the example B *"Returning information about a procedure"*: ``` USE AdventureWorks2012; GO CREATE PROC Production.TestProc AS SELECT Name, ProductID, Color FROM Production.Product ; SELECT Name, SafetyStockLevel, SellStartDate FROM Production.Product ; G...
This is by no means a complete answer, but I wanted to show how [SET FMTONLY](http://msdn.microsoft.com/en-us/library/ms173839.aspx) is used. It may solve part of the OP's request. ``` CREATE PROCEDURE abc @Param1 INT AS SELECT TOP(@Param1) * FROM master.sys.objects GO --When set OFF, 3 rows are returned...
get returned fields datatypes from a stored procedure
[ "", "sql", "sql-server", "delphi", "stored-procedures", "" ]
I am attempting to run a SQL query that will filter either to a value passed in a parameter, or if the value in the parameter is 'Unspecified' then all values should be returned. The parameter is `@station` which may contain the values `'Unspecified', 'Station1', 'Station2', 'Station3'` etc. If the parameter `@statio...
``` where tblRTC.CODE IN ('C1', 'C2', 'C3') and CAST(tblDET.START_DATE AS Date) >= CAST (@start_date AS Date) and CAST(tblDET.END_DATE AS Date) <= CAST (@end_date AS Date) and tblSTACON.DESCRIPTION = (case when @station not in( 'Unspecified') then @station else tblSTACON.DESCRIPTION end) ```
hope this helps ``` where tblRTC.CODE IN ('C1', 'C2', 'C3') and CAST(tblDET.START_DATE AS Date) >= CAST (@start_date AS Date) and CAST(tblDET.END_DATE AS Date) <= CAST (@end_date AS Date) and tblSTACON.DESCRIPTION = (case when @station <> 'Unspecified' then @station else tblSTACON.DESCRIPTION end) ```
Conditional filtering based on a specified value or unspecified
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table with the current values: ![Result of two queries](https://i.stack.imgur.com/93Hk4.png) What I want is to get the `projekt` value where kod is `Greger` and `Åutte`. As of now, my attempt returns nothing. Since the condition spans over two rows, I have no idea how to get the `projekt` I need. The wante...
Use this: ``` SELECT a.projekt FROM myTable a WHERE EXISTS ( SELECT b.projekt FROM myTable b WHERE b.projekt=a.projekt AND kod='Greger' ) AND EXISTS ( SELECT c.projekt FROM myTable c WHERE c.projekt=a.projekt AND kod='Åutte' ) ``` Another way is to COUNT the matching records, but you have to be sure you c...
How about something similar? ``` select distinct projekt from myTable where kod in ('Greger','Åutte') group by projekt having count(projekt) > 1 ```
How do I get a column value where the condition spans over two rows?
[ "", "sql", "" ]
I have a data set with a date stamp and an ID number as shown: ``` Date_Stamp | ID 2013-07-17 | ID1 2013-07-17 | ID1 2013-08-19 | ID1 2013-08-19 | ID2 ``` From this data, I need to populate a table that has the following fields: Date, ID, First\_attempt, Second\_Attempt, Third\_Attempt, Total\_Attempts. With th...
``` ;WITH TEMPTABLE AS( SELECT DATE_STAMP, ID, ROW_NUMBER() OVER( PARTITION BY ID ORDER BY DATE_STAMP ) AS ROWNUMBER, Count(ID) OVER(PARTITION BY Date_Stamp, ID) as countID FROM #temp) SELECT DATE_STAMP, ID, MAX(CASE WHEN ROWNUMBER = 1 THEN 1 ELS...
Try this: ``` ;WITH CTE AS ( SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY Date_Stamp, ID ORDER BY Date_Stamp), Total = COUNT(*) OVER(PARTITION BY Date_Stamp, ID) FROM YourTable ) SELECT Date_Stamp AS [Date], ID, MAX(CASE WHEN RN = 1 THEN 1 ELSE 0 END) First_attempt, ...
SQL - Creating counts for 1st, 2nd, 3rd occasion in a list
[ "", "sql", "sql-server", "count", "counter", "" ]
``` DECLARE @a int; DECLARE @b int; SET @a = 9; SET @b = 2; SELECT CEILING (@a/@b); ``` It is returning as 4 instead of 5. Why? **Edit:** I would like to get next smallest integer if the quotient is not whole number.
Try: ``` SELECT CEILING (@a/CAST(@b AS float)) ``` And consider `NULLIF(@b,0)` too, to avoid a Division By Zero error.
After dividing 9 by 2 a decimal fraction is *Truncated* to its integer part - 4, not *Rounded* to 5. Try: ``` SELECT 9/2 ``` Resilt is 4. Then `CEILING(4) = 4` To get next integer declare variables as data types that can handle decimal part: `NUMERIC`,`FLOAT`, `REAL`.
CEILING returns FLOOR result - SQL SERVER 2008 R2
[ "", "sql", "database", "sql-server-2008", "floor", "ceil", "" ]
Can someone help me with a SQL query for this situation. I have a table with a surrogate key and a business key. For example this table: ``` ID ------ contact_id 1 -------- 100 2 -------- 100 3 -------- 200 4 -------- 100 5 -------- 100 ``` Does anyone know a query to get the next biggest ID of a contact\_id. I...
This should do it if I understand you properly :) ``` ---Supply the ID and the Contact_ID DECLARE @ID INT = 1 ,@C_ID INT = 100; WITH OrdCte AS( SELECT ID,Contact_ID,ROW_NUMBER() OVER(PARTITION BY Contact_ID ORDER BY ID) ord FROM #sample ) SELECT B.ID,B.Contact_ID FROM OrdCte A JOIN OrdCte B ...
I am not sure what you expect the **next big** value for `contact_id` 200, so in this case it will use the same `contact_id` as **next big** ``` Select Main.*,ISNULL(NextB.contact_id,Main.contact_id) as NextBig From TableName Main Outer APPLY (Select contact_id From TableName T ...
How to get the next biggest int value in SQL?
[ "", "sql", "sql-server", "" ]
I'm trying to select all tables which have columns OWNERID or L1ID or L1, but not have any of the following columns, HID, DHID, SPHID, SPHID, LINKHID, NODEID and SITEID. The following is my SQL query. It's taking a long time. Can you give me a better solution or optimize this query. ``` SELECT TABLE_NAME F...
Try not exist / exists instead. As long as you don't need to select values from the secondary tables, this is much faster than IN and especially NOT IN. Basic reason is that as soon as there is a match, the evaluation is done. ``` SELECT TABLE_NAME FROM USER_TABLES WHERE NOT EXISTS (select 1 FROM USER_TAB_COLUMNS ...
``` With exclude AS ( select TABLE_NAME FROM USER_TAB_COLUMNS WHERE COLUMN_NAME IN('HID', 'DHID', 'SPHID', 'LINKID', 'NODEID', 'SITEID') GROUP BY TABLE_NAME ) , preInclude AS ( SELECT TABLE_NAME FROM USER_TAB_COLUMNS WHERE COLUMN_NAME IN ('OWNERID', 'L1ID', 'L1') GROUP BY TABLE_NAME ) , Include AS ( ...
SQL query optimization for selecting specific columns from a table
[ "", "sql", "oracle", "optimization", "" ]
For example , I use the following function to convert `rows` into `json` in `PostgreSQL 9.2` ``` select row_to_json(row(productid, product)) from gtab04; ``` and this will returns below results ``` row_to_json --------------- {"f1":3029,"f2":"DIBIZIDE M TAB"} {"f1":3026,"f2":"MELMET 1000 SR TAB"} {"f1":2715,"f2":"GL...
To work around this we must either create a row type and cast the row to that type or use a subquery. A subquery will typically be easier. ``` select row_to_json(t) from ( select productid, product from gtab04 ) t ```
If one wants to prevent a sub-query, `json_build_object()` might be a solution. It does not map the column name, but let's your set the JSON keys explicitly. --- **Query** ``` SELECT json_build_object('productid', productid, 'product', product) FROM gtab04; json_build_object --------...
Select query in row_to_json function
[ "", "sql", "json", "postgresql", "postgresql-9.2", "composite-types", "" ]
I have a string of values like : ``` $cat = "1,5,6,8,9"; ``` now I would like to use that variable in WHERE clause. how do I do it ? ``` "select category from test where category...?" ``` I am using below code but I get null from number\_of\_result variable : ``` $array_of_cat = explode(",",$cat); if($number_of_r...
Change your SQL statement to this one. Use `implode()` to pass array elements in `IN` clause ``` $mresult = mysql_query(" SELECT * FROM books WHERE GoodName LIKE '%$title%' AND GroupCode IN (" . implode(",", $array_of_cat) . ")"); ```
You do not need to explode the variable - doing so results in an array that will result in the wrong value (the string "Array") when interpolated into the SQL string. Despite the fact that this is unsafe ([SQL injection prone](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)) you could...
using a string of values in WHERE clause - mysql
[ "", "mysql", "sql", "" ]
I have a table with three dates: ``` id date1 date2 date3 1 1945-12-13 1930-11-04 null 2 1970-09-12 1971-09-13 1972-09-14 3 null null null 4 2000-01-01 2001-01-01 2002-01-01 ``` My proc passes in 2 parameters: ``` @dateFrom datetime = N...
You need to filter each date field individually within the range, like so: ``` WHERE (Date1 >= ISNULL(@DateFrom,'17531231') AND Date1 <= ISNULL(@dateTo,'20991231')) OR (Date2 >= ISNULL(@DateFrom,'1753-12-31') AND Date2 <= ISNULL(@dateTo,'20991231')) OR (Date3 >= ISNULL(@DateFrom,'1753-12-31') AND Dat...
Just for another way to look at it. This solution would also work. It makes the where clause simpler at the expense of an additional block of code and a join. ``` CREATE TABLE #dates (id INT, date1 DATE, date2 DATE, date3 DATE) INSERT INTO #dates VALUES ('1','12/13/1945','11/4/1930',NULL), ('2','9/12/1970','9/13/197...
Filtering multiple dates in row with optional to and from parameters
[ "", "sql", "sql-server", "t-sql", "" ]
I'm rookie at kettle pentaho and Querys. What i'm trying to do is check if value A, in file 1 is in file 2. I've got 2 files, that i export from my DB: File 1: ``` Row1, Row2 A 3 B 5 C 99 Z 65 ``` File 2: ``` Row1, Row2 A 3 D 11 E 22 Z 65 ``` And i want to create on...
You can have the two streams joined by a "Merge join" step, which allows you to set freely the join keys (in your case it seems like you want both fields to be used), and also what type of join, Inner, Left Outer, Right outer or Full outer.
You can use stream lookup for that. Start with the file input for file 1, then create a stream lookup step that uses the input stream for file 2 as its lookup stream. Now just match the columns and you can add the column from file 2 to your data stream.
Pentaho Join table values
[ "", "sql", "pentaho", "kettle", "" ]
I have a table like the following: ``` id website logInTime 1 Yahoo 1/1/2001 00:00:00 2 Google 1/1/2001 00:00:01 1 Yahoo 2/1/2014 00:00:00 2 Yahoo 2/1/2014 00:00:00 ``` How can I retrieve the latest time of log in from each user based on the website?
``` select t.id, t.website, max(logInTime) from table t group by t.id, t.website ```
Is that the query you're looking for? ``` SELECT T.id ,T.website ,MAX(T.logInTime) AS [lastLogInTime] FROM yourTable T GROUP BY T.id, T.website ``` Hope this will help you.
Get the latest date of records from a table, SQL
[ "", "sql", "" ]
``` SELECT * FROM pay_invoice_list p LEFT outer JOIN paimentDetl d on p.invoice_no= d.invoiceNo and p.invoice_no LIKE ' %$temp%' ORDER BY iid DESC ``` This is my query. But it doesn't work correctly. The tow tables are not join properly. as well as the "Like" didn't work.
try like this ``` SELECT * FROM pay_invoice_list p LEFT outer JOIN paimentDetl d ON p.invoice_no = d.invoiceNo WHERE p.invoice_no LIKE ' %$temp%' ORDER BY iid DESC ```
``` SELECT * FROM pay_invoice_list p LEFT outer JOIN paimentDetl d on p.invoice_no= d.invoiceNo Where p.invoice_no LIKE ' %$temp%' ORDER BY iid DESC ``` All you needed to do is add WHERE to your query.
How to use Like in left outer join
[ "", "mysql", "sql", "" ]
Let's say I have two tables `Contracts` and `ServiceProviders`. A contract has a property `LeadServiceProvider` which references a service provider. I also have a third table called `SubServiceProviders` that maintains a many-to-many relationship between `Contracts` and `ServiceProviders` acting as sub service provide...
It seems you could use CROSS APPLY here: ``` Select distinct v.ServiceProvider From Contracts c left join SubServiceProviders subSP on c.ID = subSP.Contract cross apply (values (c.LeadServiceProvider), (subSP.ServiceProvider)) as v (ServiceProvider) Where [Some contract criteria goes here] ``` ...
If you are looking for a simple'ish way to do this in one query, you can use a CTE and unpivot the columns. I would do this explicitly with a `join` like this: ``` with t as ( Select c.LeadServiceProvider, subSP.ServiceProvider From Contracts c left join SubServiceProviders subSP on c.ID = subSP.Contract ...
How to join two columns without repeating the FROM/WHERE clauses
[ "", "sql", "sql-server", "" ]
I am using SQL Server Compact Edition 3.5 SP2. I want to use this query: ``` SELECT DISTINCT PortalURI FROM LoginHistory ORDER BY LastLoginDate DESC ``` But it tells me that it requires `LastLoginDate` field to be selected too like this: ``` SELECT DISTINCT PortalURI, LastLoginDate FROM LoginHistory ORDER BY LastLo...
Try this: ``` SELECT PortalURI, MAX(LastLoginDate) LastLoginDate FROM LoginHistory GROUP BY PortalURI ORDER BY LastLoginDate DESC ```
Please try: ``` SELECT PortalURI FROM LoginHistory GROUP BY PortalURI ORDER BY MAX(LastLoginDate) DESC ``` **EDIT:** SQL Server Compact Edition does not support aggregate functions on the ORDER BY clause. So, here is an alternative solution: ``` SELECT PortalURI, MAX(LastLoginDate) FROM LoginHistory GROUP BY PortalU...
How to use DISTINCT for just one field when ORDER BY another field is used?
[ "", "sql", "sql-server", "sql-server-ce", "sql-order-by", "distinct", "" ]
What's the most efficient way to run a query encapsulated in another? *1. Querying inside a query:* ``` select id_user from table1 where foo in (select foo from table2 where dt_signin > '2014-01-01 00:00') ``` *2. By using a temporary table:* ``` create table tmp_table as select foo from table2 where dt_sig...
Your two queries do not do the same thing. For the second approach to be equivalent, you need `select distinct`: ``` select distinct id_user from table1 t1 join tmp_table tmp on t1.foo = tmp.foo; ``` Because of this additional operation, I might expect the `in` to perform better. But, in general, when you h...
The `exists` variant frequently outperforms the others ``` select id_user from table1 where exists ( select 1 from table2 where dt_signin > '2014-01-01 00:00' and table1.foo = foo ) ``` Notice that the outer `table1.foo` is compared to `foo` in the subquery
Most efficient way to run an encapsulated query
[ "", "sql", "performance", "postgresql", "" ]
I have four MySQL tables where the first three share the first tables PK, and the forth has a FK to the third table (see below for schema). Given the PK of the forth table, I need data from the first and forth table only. Is there any need to join the second and third table? For instance, is: ``` SELECT t1.*,t4.* F...
You don't need to join any tables if they're not relevant to the query. A table is relevant if you need to refer to it columns, or you want the result set limited to rows that have matches in that table. Joining with extra tables will slow down the query, because the query planner cannot determine that these joins are ...
If all IDs are the same in all four tables, and if you don't want to exclude records that don't appear in tables 2 and 3, then there is no reason to include them in the join. It will still use the index on table 1, even without the foreign key relationship. I would consider renaming all the ID columns to signify the f...
Is joining 1-to-1 tables always necessary?
[ "", "mysql", "sql", "" ]
i have a table in sql server 2012, with one of its column having the following data in time datatype, How would you convert 00:45:00 to 0.45 or 01:45:00 to 1.45 ? please help.
From the question, it seems you only want to remove the ':' with '.'. If so, it can be achieved in many ways in SQL Server 2012. One example is below. If your column is 'Datetime', use this: ``` SELECT REPLACE(LEFT(CAST(DatetimeCol AS TIME),5),':',',') FROM Tbl ``` Else if it just 'Time' then remove the cast.
You could do arithmetic such as: ``` select cast(datepart(hour, col) + datepart(minute, col) / 100.00 as decimal(5, 2)); ``` But as noted in the comments, "1.45" seems quite confusing. Most people think this should be "1.75". If you want the latter -- with precision to the minute -- you can do: ``` select cast(dat...
convert time to decimal in SQL server 2012
[ "", "sql", "time", "decimal", "" ]