Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I know there are tons of similar questions already, but they don't quite meet my needs. I'm aware that (+) is an Oracle-only join operator used in WHERE clauses, and the the orientation dictates LEFT or RIGHT. However, I'm not entirely sure if my situation matches because the syntax looks different from everything I've...
As far as I know, Oracle does not have an `=+` operator ([here](http://docs.oracle.com/cd/E25178_01/fusionapps.1111/e20835/appsql.htm#i1033699) is an example of a reference). It does, however, have an `=` and a unary `+`. So, I think this would parse as: ``` HSS.SKN_NO = (+ RFPRICE.SKN_NO) ``` This, in turn, would be...
If the "+" was on the other side of that statement i would say it is a right outer join condition. never have seen it there, though. If you move it to the right of the statement, does it still run? if so its a right outer join to HSS. I would find out what the program is supposed to do and rewrite it using CTE since i...
Oracle Equals-Plus Operator (Join On t1.col1 =+ t2.col2)
[ "", "sql", "join", "syntax", "oracle11g", "operators", "" ]
I have the following challenge. I have 2 tables. First table contains changes in values of bikes, at a certain moment (i.e. price catalogue). This means a certain price for a product is valid untl there is a new price within the table. ``` Product | RowNr | Year | Month | Value -------------------------------------...
You could do something like this, which will retrieve the most recent price catalogue value for the product, using the price that is less than or equal to the product table date. ``` SELECT p.product , p.date , valueAsOfDate = ( SELECT TOP 1 c.value FROM priceCatalogue c WHERE c.product ...
just use the `YEAR()` and `MONTH()` functions to take those parts of the date, and join them on your versioned table. ``` select from product p inner join productVersion pv on p.product = pv.product and Year(p.Date) = pv.Year and Month(p.Date) = pv.Month ```
Using t-sql to lookup value based on dates in other table
[ "", "sql", "sql-server", "date", "case", "partition", "" ]
I have a query which output a a column name `member_name` ``` select LEFT(member_name, charindex('/', member_name) - 1) + ' ' + SUBSTRING(member_name, charindex('/', member_name) + 1, 1) as member_name from member ``` It output the string with the last name and first letter of first name. How can I output in the ...
``` select substring(member_name, charindex('/', member_name) + 1, 1) as first_initial, left(member_name, charindex('/', member_name) - 1) as last_name from member ```
I don't have the reputation to reply to comments just yet, but as you asked in a comment in the answer, It **can be** done in cold fusion, but I'd think SQL is your better choice. ``` <cfoutput query="get_names"> <cfset l_name = listfirst(member_name,"/")> <cfset f_initial = left(listlast(member_name,"/"),1)> <!...
How to separate string output?
[ "", "sql", "" ]
I have a query like the below: ``` SELECT *, ( SELECT `name` FROM `users` WHERE `users`.`id`=``.`` ) AS `fullName` FROM `listings` WHERE `fullName` LIKE '%praveen%'; ``` But when I execute the above query, I am getting this error: ``` #1054 - Unknown column 'fullName' in 'where clause' ``` I know that this bug ...
I think this is the correct syntax of what you are after: ``` select l.*, u.name as fullname from listings l join users u on l.user = u.id where u.name like '%praveen%' ```
Try this.... ``` SELECT * FROM ( SELECT * , (SELECT `name` FROM `users` WHERE `users`.`id`=``.`` ) AS `fullName` FROM `listings` ) Q WHERE `Q`.`fullName` LIKE '%praveen%'; ```
Unknown column in WHERE clause when using subquery
[ "", "mysql", "sql", "subquery", "where-clause", "" ]
In SQL Server 2008, I need to query across columns in T-SQL and return the largest number I find (example below using dates, but same idea applies to numbers). "NULL" indicates a null value, not the literal word (sorry if I'm being captain obvious). The column "DesiredResultColumn" shows the final result I want from se...
As per a [similar question](https://stackoverflow.com/a/6871572/1270504): ``` SELECT tbl.ID, (SELECT MAX(Date) FROM (VALUES (tbl.Column1), (tbl.Column2), (tbl.Column3)) AS AllDates(Date)) AS DesiredResultColumn FROM tbl ``` Of course, that only works on SQL 2008 and above, but you said you have 2008 so...
you can probably use a `case` condition along with `ISNULL()` to get the result like below ( a sample, didn't included nullity check using `ISNULL()`. You can include that) ``` select ID, Column1, Column2, Column3, case when Column1 > Column2 and Column1 > Column3 then Column1 ...
Returning largest value across columns in SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Trying to create sql or PIG queries that will yield a count of distinct values results based on type. In other words, given this table: ``` Type: Value: A x B y C y B y C z A x A z A z A x B x B z B x C x ``` I want to get ...
``` A = LOAD 'tablex' USING org.apache.hcatalog.pig.HCatLoader(); x = foreach A GENERATE id_orig_h; xx = distinct x; y = foreach A GENERATE id_resp_h; yy = distinct y; yyy = group yy all; zz = GROUP A BY (id_orig_h, id_resp_h); B = CROSS xx, yy; C = foreach B generate xx::id_orig_h as id_orig_h, yy::id_resp_h as id_res...
Updated code according to Edit#3 in question: ``` A = load '/path/to/input/file' using AvroStorage(); B = group A by (type, value); C = foreach B generate flatten(group) as (type, value), COUNT(A) as count; -- Now get all the values. M = foreach A generate value; -- Left Outer Join all the values with C, so that eve...
PIG query to pivot rows and columns with count of like rows
[ "", "sql", "hadoop", "apache-pig", "" ]
Like many others here I don't have a lot of experience under my belt. I've been directed to convert non clustered indexes to clustered (No clustered indexes exist). In the attached query I print out the @sql variable to see what my command looks like and it's only about half the tables. 1st question. Is there a limit ...
There are several things to improve here. Some of the suggestions will make others obsolete (mainly # 14 about using a CTE would nullify most of the rest of them), but you said you were new to SQL Server so I will mention them all as they might help in future projects. And to be clear I have highlighted the two critica...
SQL Server Management Studio does have a limit of about 44k characters (at least for SQL Server 2008, the last time I had this problem) for select statements with a string variable. However, the full SQL still gets executed (in my experience). Your problem looks different, though. I'm not sure what you are trying to d...
Build of varchar(max) command variable is truncated
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm using the following query to get information about all tables in a DB: ``` SELECT t.NAME AS TableName, i.name as indexName, sum(p.rows) as RowCounts, sum(a.total_pages) as TotalPages, sum(a.used_pages) as UsedPages, sum(a.data_pages) as DataPages, (sum(a.total_pages) * 8) / 1024 as T...
The problem is that there's more than one allocation\_unit per partition, so the same partition can appear more than once and therefore the sum(p.rows) ends up counting the same partition more than once, so you get a multiple of the right number of rows. Here's how I solved the problem: (note that my query isn't ident...
From [the sys.partitions documentation](http://msdn.microsoft.com/en-us/library/foo1c19e1b1-c925-4dad-a652-581692f4ab5e.aspx) > rows bigint **Approximate number of rows in this partition.** (emphasis mine). The system views aren't going to keep a spot-on number of rows in the table. Think of what that would entail an...
Count(*) differs from rows in sys.partitions
[ "", "sql", "sql-server", "database-schema", "" ]
I want to extract all the rows from a database table, where the rows cross-reference each other. My table contains 2 rows: `ref1` & `ref2` Table example: ``` ID ref1 ref2 01 23 83 02 77 55 03 83 23 04 13 45 ``` In this case, I want my query to return only rows 01 and 03, because they cross...
A simple JOIN can do that in a straight forward manner; ``` SELECT DISTINCT a.* FROM mytable a JOIN mytable b ON a.ref1 = b.ref2 AND a.ref2 = b.ref1; ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/1980fe/2).
``` select * from tbl t1 where exists ( select 'x' from tbl t2 where t1.ref1 = t2.ref2 and t1.ref2 = t2.ref1 ) ```
Find records which cross-reference each other
[ "", "mysql", "sql", "" ]
I'm working on a small search engine project and I need some help with a SQL query. My table looks like this (example): ``` word | docNum --------------------------- 1. blue | 1 2. pen | 2 3. pen | 1 4. green | 1 5. key | 2 6. key | 1 7....
Group by the `docnum` and select only those having all 4 words you look for ``` select docnum from your_table where word in ('blue','pen','green','key') group by docnum having count(distinct word) = 4 ```
For above result simply you can use this query : ``` SELECT * FROM `your_table` WHERE docnum=1 and word IN ('blue','pen','green','key') ```
Selecting records from mysql table
[ "", "mysql", "sql", "" ]
I have one table named 'Vote' and there is a column named status. Status can have true or false values. I want to find subtract result. Something like this ``` select (select count(*) from vote where status=true) - (select (*) from vote where status=false) ``` the above sql is giving error: incorrect syntax ...
Try this one: ``` select sum( (case when status='true' then 1 else -1 end) ) from table ```
You missed to write count in your second select ``` select count(*) ``` instead of ``` select (*) ``` So your query would become ``` select (select count(*) from vote where status = 'true') - (select count(*) from vote where status = 'false') ``` If datatype is bit then try this: ``` select (select count(*...
SQL subtracting count(true) from count(false) value
[ "", "sql", ".net", "sql-server", "t-sql", "" ]
I have a table that holds data for employees and results of a questionnaire they took. The questionnaire has 3 questions, but not all questions had to be answered. I am trying to find out what questions were not answered by the employees. EmployeeData: ``` EmployeeID | Question | Answer ------------------------------...
The method for doing this is to create a list of all questions for all employees and then remove the ones that are already answered. You can do this with subqueries, a `cross join`, and a `left outer join`: ``` select e.*, q.* from (select distinct employeeid from employeedata) e cross join (select distinct ques...
First you need a list of the employees. A better source would be the employee table if it exists. What if an employee didn't fill out the survey? But based on your request, we'll use the employees in the table. ``` SELECT DISTINCT EmployeeID FROM EmployeeData ``` Now we need to add in the possible questions. For thi...
TSQL Get records that don't exist in a table
[ "", "sql", "sql-server", "inner-join", "exists", "not-exists", "" ]
I want to alter a view using a T-SQL script dynamic. Each month I have a new table in my database, I want to include the new table in my view. My idea is to create a var inside a T-SQL procedure and then build the sql statment to create the code I will use to alter the view. With this I only need to EXEC (@SqlView). Th...
Here is another approach that doesn't use a loop. ``` declare @SqlResults nvarchar(max) = '' select @SqlResults = @SqlResults + 'select a,b from ' + t.name + ' union all ' from sys.tables t where t.name like '%table0%' select @SqlResults = 'ALTER VIEW SomeView as ' + left(@SqlResults, LEN(@SqlResults) - 10) select...
This is the SQL that I use when trying to generate a script for every table, altered to plug in your specific details: ``` DECLARE @SQLTable TABLE ( ID INT IDENTITY(1,1) NOT NULL, Sequel VARCHAR(4000) NOT NULL ) INSERT INTO @SQLTable (Sequel) SELECT 'SELECT A, B FROM ' + TABLE_NAME + ' UNION ALL' FROM I...
Dynamic view with sysobjects tables
[ "", "sql", "sql-server", "t-sql", "" ]
What I am trying to do can be exemplified (Incorrectly) by the following query ``` SELECT * FROM Table1 WHERE User IN (CASE (SELECT Username From Table2 Where Table2.ID = 1) WHEN IS NULL THEN NULL ELSE (SELECT Username From Table2 Where Table2.ID = 1) END) ``` Since `User = NULL` is not t...
If you want to consider two `NULL` values as matching, you can do: ``` select t1.* from table1 t1 where exists (select 1 from table2 t2 where t1.user = t2.username or t1.user is null and t2.user is null ); ``` If you are trying to match values in `table2` and if there are no v...
A link where you use null as a relation between table will get you a wrong number of rows. Duplicated rows and stuff. The simplest query I can think of (in order to avoid this) is: ``` select t1.* from table1 t1 join table2 t2 on t1.user = t2.username ``` This will filter out the nulls. In case that you also need...
Where Clause That Grabs Values From A Table And If It Returns Null It Grabs Only Nulls
[ "", "sql", "sql-server", "t-sql", "syntax", "null", "" ]
I have a local server set up on my computer with a local database. I am trying to connect to a network server with a linked server (I'm having a lot of trouble with this) and then create tables and views in the local database from the data in the network database. I'm using Microsoft SQL Server Management Studio 2012.
Try something like : ``` SELECT * from openquery(LINKED_SERVER_NAME,'SELECT * FROM TABLE') ``` If your linked server is well configured, you should be able to query the tables in the linked server using [openquery](http://msdn.microsoft.com/fr-fr/library/ms188427.aspx).
Try this. First you link the Server then run query against the linked Server. ``` EXEC Sp_addlinkedserver @server="MY-PC\SQLServer1", @srvproduct='SQL Server' -- from SQL Server2 you run this query SELECT * FROM Openquery("my-pc\sqlserver1", 'select * from Students') ``` Reference: [Running Query against linke...
How do you pull data from a database to another one using a linked server?
[ "", "sql", "sql-server", "database", "sql-server-2012", "linked-server", "" ]
I am wanting to calculate the difference between the max(value) returned from a database against a row value returned. Example Data 1. 400 2. 300 3. 200 4. 100 max(value return) = 400 Returned result should be: 1. 0 (no difference between the max value and row value) 2. 100 3. 200 4. 300 etc Any ideas how this c...
Try this below soln. ``` SELECT A.MaxtotalPoints - A.totalPoints AS GAP FROM ( SELECT userName, totalPoints , MAX(totalPoints) MaxtotalPoints FROM userTable WHERE value='1' ) A ORDER BY GAP; ```
Try this: ``` SELECT a.*, b.maxTotalPoints - a.totalPoints as gap from userTable a INNER JOIN ( SELECT userName, max(totalPoints) as maxTotalPoints FROM userTable ) b on (a.userName = b.userName) WHERE a.value='1' ORDER BY a.totalPoints DESC ```
MYSQL Get Difference between two values
[ "", "mysql", "sql", "" ]
I have a list of tables **Product** ``` { ProdID (INT), Name(varchar), ...} ``` **Store** ``` { StoreID(INT), Location(varchar), ...} ``` **Inventory** ``` {StoreID(INT) references Store(StoreID) ,ProdID(INT) references Products(ProdID),...} ``` I want the list of products not available in each store
``` ;WITH CTE AS ( SELECT P.ProdID , S.StoreID FROM Product P CROSS JOIN Store S ) SELECT C.StoreID, C.ProdID FROM CTE C WHERE NOT EXISTS (SELECT 1 FROM Inventory WHERE C.StoreID = StoreID AND C.ProdID = ProdID) ```
Then you want to select all stores that do not have products in inventory. ``` select s.StoreID, p.ProdID, p.Name from Store s, (select ProdID, Name from Product where ProdID not in (select i.ProdID from inventory i ...
Products not available in each store
[ "", "sql", "sql-server", "" ]
I have the following situation. In a **MySql** database I have a **posts** table. This table contains the following 2 fields: **post\_modified** and **post\_date** For each record present in the **posts** table I need set the value of **post\_modified** field with the value into the **post\_date** How can I do a que...
That's an easy one: ``` UPDATE posts SET post_modified = post_date; ```
This query should do the job : ``` UPDATE posts SET post_modified=post_date; ```
How to change the value of this field in all the records of this MySql table?
[ "", "mysql", "sql", "database", "rdbms", "" ]
I have a puzzle which I'm hoping someone can help me solve I have a table of apartment listings. Each listing has one or more 'unavailable' dates stored individually in another table, let's call it 'off\_days'. e.g. a listing which is unavailable from the 1st until the 4th of Sept would have 4 entries in the 'off\_day...
The apartment is available for gaps in the off days. That means that you want to know how big the gap is for each sequence, and the `lag()` function can give you this information: ``` select od.*, lag(unavailable) over (partition by apartmentid order by unavailable) as prev_una from offdays od; ``` The actual ...
### Candidate apartments Using [**`generate_series()`**](https://stackoverflow.com/questions/tagged/generate-series) and two nested [`EXISTS`](http://www.postgresql.org/docs/current/interactive/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS) expressions, you can translate this English sentence into SQL pretty much ...
Find available apartments given a date range, a duration, and a list of unavailable dates
[ "", "sql", "ruby", "postgresql", "bit-manipulation", "" ]
I have a table with 13 columns (one is for the row ID # and the other 12 represent one for each month of the year). Each column will only contain numbers and I want to write several queries to check each row for certain conditions and return the ID of any rows that match. So far I've been fine with writing all the bas...
So, as an alternate answer to @Pieter's answer and to illustrate how a simpler data structure may make your task easier, I suggest the following: ``` create view tblEasy as ( select pkID, 1 as colMonth, colJan as colValue from tblMonthData UNION select pkID, 2 as colMonth, colFeb as colValue from tblMonthData UNION se...
Unpivot the table to perform the comparison, and then if necessary pivot back to the original format.: ``` with unpvt as ( select YearNo ,case MonthNo when 1 then colJan when 2 then colFeb when 3 then colMar when 4 the...
How To Shorten This SQL Query Without A Million AND/OR's?
[ "", "sql", "sql-server", "" ]
I have a stored procedure which is going really slow. I ran the SP and looked at the execution plan and was able to see what was taking so long time. The part that is slow: ``` DECLARE @id int ,@date datetime ,@endDate datetime SELECT @id = 3483 ,@date = DATEADD(DAY, -10, GETDATE()) ,@endDate =...
You could use a sub-query instead of the scalar valued function. ``` // ... ,prevId = ( SELECT TOP 1 x.id FROM dbo.table AS x WITH(READUNCOMMITTED) WHERE 1 = 1) // ... ``` In most cases, it's best to avoid scalar valued functions that reference tables because they are basically black boxes that need to be ra...
First thing, you should cut the function all together and inline the query. Which from what I see it would be fairly simple. Or if you want to preserve a function there use a table valued function. For both check: <http://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx> Second, the best results in optimi...
Optimizing SQL query using function
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have 100 records from 3 users. I want to show the most recent record from each user. I have the following query: ``` SELECT * FROM Mytable WHERE Dateabc = CURRENT DATE AND timeabc = ( SELECT MAX(timeabc) FROM Mytable ) ``` It returns the most recent record for everyone, and I need it to return most recen...
I assume somewhere in your table you have a userID... ``` select userID, max(timeabc) from mytable group by userID ```
Should the solution support both DB2 and mysql? ``` SELECT * FROM Mytable as x WHERE Dateabc = CURRENT_DATE AND timeabc = (SELECT MAX( timeabc ) FROM Mytable as y where x.user = y.user) ``` If it's only DB2 more efficient solutions exists: ``` SELECT * from ( SELECT x.*, row_number() over (partition by user o...
DB2 Show the latest row record from users, using the date and time
[ "", "mysql", "sql", "database", "db2", "squirrel-sql", "" ]
I need a query to get the Name of the Clients where there is no Client Contact record and if there is any Client Contact then they are ended. Please see below table structure. Table : **Client** ``` Client ID Client Name ------------------------- 1 John 2 Sean 3 Johnso...
Here's a query pattern that I use for queries like this that can give substantial performance gains compared to "left join" patterns, when the tables involved get really large: ``` select c.[Client Name] from Client c where not exists ( select * from Client_Contact cc where c.[Client ID] = cc.[Client ID] and cc.[E...
Try .. ``` select distinct cl.* from Client cl left outer join Client_Contact clcnt on cl.[Client ID] = clcnt.[Client ID] where (clcnt.[Client ID] IS NULL OR clcnt.[End Date] IS NULL) ```
SQL Query , Clients with No Client Contact and No Active Client Contact
[ "", "sql", "sql-server", "t-sql", "" ]
I have a data structure similiar to: ``` Person | Counter Mary 1 Mary 2 John 5 John 6 ``` I am trying to **Group By** on the Person column, and add up the values for the counter, for each person. Meaning, I am trying to return: ``` Person - Mary - Has 3 Counters Person - John - Has 11 Counter...
Here you go: ``` DECLARE @DATA TABLE (Person VARCHAR(25), [Counter] INT) INSERT INTO @DATA SELECT 'Mary',1 UNION SELECT 'Mary',2 UNION SELECT 'John',5 UNION SELECT 'John',6 SELECT 'Person - ' + ISNULL(Person,'Not Assigned') + ' - has ' + CAST(SUM([Counter]) AS VARCHAR) + ' counters' from @DATA GROUP BY Person ```
What you want is a group by clause just as you stated, so something based on this: ``` SELECT Person, SUM(Counter) FROM MyTable GROUP BY Person ``` I didn't include the extra text from your original query to make it a bit more compact.
Add Int Column Values Similar To Count
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I get a string as input from an application that is supposed to be a date. For some asinine reason the developers of the application decided provide precision to the microsecond. Well, actually, to the tenth of a microsecond. The string is in the format: `2014-08-15T17:38:22.2930000` Before they changed this input fo...
Either of these should work: ``` SELECT CONVERT(DATE, '2014-08-15T17:38:22.2930000', 101) SELECT CONVERT(DATETIME2, '2014-08-15T17:38:22.2930000', 101) ```
Whoops, the following assumes that a date *and* time are desired. Substituting in DATE for DATETIME2 will work, just as it does with CONVERT and the time component is simply dropped. --- A CAST to DATETIME2 works (this is for SQL Server *2008 R2* - YMMV elsewhere), ``` select CAST('2014-08-15T17:38:22.2930001' AS DA...
Converting string with microseconds to DATE
[ "", "sql", "sql-server", "sql-server-2008", "date", "iso8601", "" ]
# Question How can I keep leading zeros when concatenating two numbers together in an Access query? # Table ``` FileYear | FileIteration ------------------------ 14 | 0001 14 | 0002 14 | 0003 14 | 0004 ``` (`FileIteration` has a "0000" format, but is still stored as integer) # Query ``` S...
Using the `Format` function is my opinion the "correct" way to do it although there are many ways to achieve what you want in this case. The output of `Format()` will be a string ``` SELECT MAX(FileYear & Format(FileIteration,"0000")) FROM FileNumber WHERE FileYear=Format(Date(),"yy"); ```
If it's always a 4-digit number, you can simply do this: ``` Fileyear * 10000 + FileIteration ``` If the number of digits is dynamic, let's assume it's in the column NoOfDigits: ``` Fileyear * 10 ^ NoOfDigits + FileIteration ```
How can I keep leading zeros when concatenating two numbers together in a query?
[ "", "sql", "ms-access", "ms-access-2007", "" ]
How do I convert table column data from 'LastName, FirstName' to 'FirstName LastName' in Postgres. So if the table column contains 'Ona, Lisa' I want it to return 'Lisa Ona'. If the column doesnt contain a ' ,' then I want it to return null. I've been trying to use postgres functions SUBSTRING and REGEXP\_REPLACE but ...
You need `strpos` and `substr` functions and a `CASE` to return `NULL`. ``` SELECT CASE WHEN strpos(name,', ') > 0 THEN substr(name,strpos(name,', ') + 2) ||' ' || substr(name,0, strpos(name,', ')) ELSE NULL END FROM person ``` [fiddle](http://sqlfiddle.com/#!15/d72db/1)
Nevermind worked out a solution using SPLIT\_PART function ``` SELECT t1.sort_name, split_part(t1.sort_name, ', ', 2)|| ' ' || split_part(t1.sort_name, ', ', 1) FROM artist t1 WHERE t1.sort_name LIKE '%, %' ```
How do I convert table column data from 'LastName, FirstName' to 'FirstName LastName' in Postgres
[ "", "sql", "postgresql", "substring", "" ]
I have 2 tables (A, B). They each have a different column that is basically an order or a sequence number. Table A has 'Sequence' and the values range from 0 to 5. Table B has 'Index' and the values are 16740, 16744, 16759, 16828, 16838, and 16990. Unfortunately I do not know the significance of these values. But I do ...
If the values are in ascending order as per your example, you can use the `ROW_NUMBER()` function to achieve this: ``` ;with cte AS (SELECT *, ROW_NUMBER() OVER(ORDER BY [Index])-1 RN FROM B) SELECT * FROM cte ```
You could use a `case` expression to convert table a's values to table b's values (or vise-versa) and join on that: ``` SELECT * FROM a JOIN b ON a.[sequence] = CASE b.[index] WHEN 16740 THEN 0 WHEN 16744 THEN 1 WHEN 16759 THEN 2 ...
SQL Join on sequence number
[ "", "sql", "sql-server-2008", "join", "" ]
There are alot questions on this topic, still can't figure out a way to make this work. The query I'm doing is: ``` SELECT `b`.`ads_id` AS `ads_id`, `b`.`bod_bedrag` AS `bod_bedrag`, `a`. `ads_naam` AS `ads_naam`, `a`.`ads_url` AS `ads_url`, `a`.`ads_prijs` AS `ads_price`, `i`.`...
Judging by your output you want: ``` SELECT amb.ads_id, MAX(amb.bod_bedrag) max_bod_bedrag, am.ads_naam, am.ads_url, am.ads_prijs ads_price, ai.url img_url, ac.url cat_url FROM ads_market_bids amb JOIN ads_images ai ON ai.ads_id = amb.ads_id ...
One approach is to simulate row\_number() (which MySQL does not have), but it allows for selection - by record - rather than by aggregates which may come from disparate source records. It works by adding to variables to each row (it does **not** increase the number of rows) Then, using an ordered subquery those variabl...
Order a Group BY
[ "", "mysql", "sql", "" ]
I have table with data something like this ``` Id value1 value2 IsIncluded ---------------------------------- 1859 1702 4043 0 1858 1706 4045 0 1858 1703 4046 1 1860 1701 4046 0 1861 1702 4047 0 ``` To get the Ids with `min(value1)` and `max(value2)` and filter base...
Similar to Gordon Linoff, this worked for me select Id, min(value1), max(value2) from table group by Id having sum(case when IsIncluded=1 then 1 else 0 end)=0
``` select Id, min(value1), max(value2) from table t where t.IsYpIncluded=0 and not exists ( select 0 from table t2 where t.Id = t2.Id and t2.IsYpIncluded = 1 ) group by t.Id; ```
Filter the data with GROUP BY in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
Trying to use the `REPLACE` to rename the start and end of the string. The string that I have is, for example: `ABCD - [001]`. I wanto to get just the `001` and count. Example: [SQLFIDDLE](http://sqlfiddle.com/#!3/99e73/2) The result should be: ``` Description Total 001 4 002 2 003...
Your description fields (at least in the example) all have the numbers in the same position. So, the easiest way to get them is `substring()`: ``` SELECT (case when Description LIKE '%/[___/]%' ESCAPE '/' then substring(description, 9, 3) else Description end) as Description, COUNT (*) AS ...
[SQL Fiddle](http://sqlfiddle.com/#!3/99e73/25) **MS SQL Server 2008 Schema Setup**: ``` CREATE TABLE Table1 ( Description varchar(20) ); INSERT INTO Table1 ( Description ) VALUES ('ABCD - [001]'),('ABCD - [001]'),('XIo9 - [001]'),('001'), ('XYZW - [002]'),('002'),('XYZW - [003]'),('XYZW - [003...
Using replace in select clause
[ "", "sql", "sql-server-2008", "" ]
Is there a way to fine tune the SQL Server Management Studio Filter Settings results (in the Object Explorer) by using wildcards to find objects like `XYZ_unknown_abc` using a `Contains` operator? I tried `(XYZ*abc)` or `(XYZ abc)` with no luck.
Coming a bit late, but %XYZ%abc% in the search box shows db object with names containing XYZ and abc, in that order.
Wildcards are still not allowed in the filter setting within Object Explorer in SSMS. BTW .. you can check this new set of Operators: <https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms181166(v=sql.90)>
Use Wildcard / Regex in filter settings of SSMS object explorer to find an object
[ "", "sql", "regex", "sql-server-2008", "wildcard", "ssms", "" ]
I want to get average for a column Name Salary HI 33168,00 Hello 32882,00 When I tried with below query ``` select Name, Salary, Avg(Salary) as avg from table group by name, Salary ``` I'm getting Salary and Avg salary both same value. expected result: ``` Name Salary HI ...
If you group by name and salary you will get one row for each such combination. In many cases this means that avg(salary) will be the same as salary. If you want to only get the average(salary) per name: ``` select Name, Avg(Salary) as avg from table group by name ``` If you want each individual salary as well you ca...
If you group by [name] and [Salary], assuming your name is unique, you will get one average salary per [name], which will be the same as the salary value ``` select Avg(Salary) as avg from table ``` If you want detail and the average row, you could use a union all ``` select name, Salary from table UNION ALL...
How to get average for a column value in sql server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have one table in which I would like **only one entry**. So if someone is trying to insert another row it shouldn't be allowed, only after someone deleted the previously existing row. How do I set a rule for a table like this?
A `UNIQUE` constraint allows multiple rows with `null` values, because two `null` values are not considered to be the same. (Except when using [`NULLS NOT DISTINCT` in Postgres 15](https://stackoverflow.com/a/8289253/939860) or later.) Similar considerations apply to `CHECK` constraints. They allow the expression to b...
Add a new column to the table, then add a check constraint and a uniqueness constraint on this column. For example: ``` CREATE TABLE logging ( LogId integer UNIQUE default(1), MyData text, OtherStuff numeric, Constraint CHK_Logging_singlerow CHECK (LogId = 1) ); ``` Now you can only ever have one row ...
How to allow only one row for a table?
[ "", "sql", "postgresql", "postgresql-9.1", "" ]
The whole question is: Rewrite the query so that the user is prompted to enter a letter that the last name starts with. For example, if the user enters “H" (capitalized) when prompted for a letter, then the output should show all employees whose last name starts with the letter “H.” ``` SELECT last_name FROM employee...
This query should work: ``` SELECT last_name FROM employees WHERE last_name like '&Start_Letter%'; ``` I have tested it in Oracle11g.
``` SELECT last_name FROM employees WHERE last_name like &Start_Letter + '%'; ```
SQL prompt to enter a letter that the last name starts with
[ "", "sql", "database", "oracle", "" ]
I have the following like table ``` A B Yes OOS No No OOS Yes OOS No Yes No ``` I want to do the following ``` Criteria A B Yes 2 1 No 1 3 OOS ...
You need to get the values into a single column, so you can use `group by`. Here is one method: ``` select criteria, sum(A) as A, sum(B) as B from ((select A as criteria, 1 as A, 0 as B from liketable ) union all (select B, 0, 1 from liketable ) ) t group by criteria; ``` Using th...
For this sample data, you could do this with a join of derived tables: ``` SELECT qa.Criteria, qa.A, qb.B FROM (SELECT A AS Criteria, count(A) AS A FROM temp_db GROUP BY A) qa FULL OUTER JOIN (SELECT B AS Criteria, count(B) AS B FROM temp_db GROUP BY B) qb ON qa.Criteria=qb.Criteria ``` But if there are missing cr...
Mysql Count multiple columns based on the same values
[ "", "mysql", "sql", "" ]
I have a table measurements that has data like below. ``` week hips wrist abs weight 1 26.3 6.3 24.3 100 2 25.2 6.3 23.3 96 ``` I am trying to get the result from week 2 to week one ``` hips wrist abs weight -1.1 0 -1 -4 ``` I tried joining the tabl...
Have you tried this? ``` select mprev.hips - m.hips as hips, mprev.wrist - m.wrist as wrist, mprev.abs - m.abs as abs, mprev.weight - m.weight as weight from measurements m join measurements mprev on me.week = mprev.week + 1; ```
``` SELECT a.[hips]-b.hips as Hips , a.wrist - b.wrist as Wrist , a.abs - b.abs as Abs , a.weight - b.weight as Weight FROM tableName a LEFT JOIN tableName b ON a.week-1=b.week ```
How do I subtract from the same table sql
[ "", "sql", "sql-server-2008-r2", "" ]
I have a table with columns (id,col\_id,type\_id,value) which looks like below ``` | id | col_id | type_id | value | ------------------------------------ | 1 | 152 | 22 | DGL | | 2 | 152 | 27 | AD56JK-5 | | 3 | 152 | 30 | 5708 | | 4 | 154 | 22 | JVM | | 5 | 154 ...
To either insert or update, use the INSERT statement with ON DUPLICATE KEY UPDATE clause. There must be a unique index on col\_id + type\_id to make it work. ``` insert into mytable (col_id, type_id, value) select col_id, 30 as type_id, concat(value, col_id) as new_value from mytable src where type_id = 22 on ...
Can you try this. (It is in TSQL, but you will understand how it works.) ``` DECLARE @TAB TABLE (ID INT,COL_ID INT,TYPE_ID INT, VALUE VARCHAR(15)) INSERT INTO @TAB VALUES (1,152,22,'DGL152'), (2,152,27,'AD56JK-5'), (3,152,30,'5708'), (4,154,22,'JVM154'), (5,154,27,'AD29JL-9'), (6,154,30,'9584'), (7,155,22,'MVR'), (8,...
insert a new row if doesnot exists depending on the colum value in other row of same table
[ "", "mysql", "sql", "" ]
I have two tables with the following data: ``` [Animals].[Males] DataID HerdNumber HerdID NaabCode e46fff54-a784-46ed-9a7f-4c81e649e6a0 4 'GOLDA' '7JE1067' fee3e66b-7248-44dd-8670-791a6daa5d49 1 '35' NULL [Animals].[Females] DataID Herd...
You can just do: ``` SELECT DataID, HerdNumber, HerdID, NaabCode, NULL as BangsNumber FROM [Animals].[Males] UNION ALL SELECT DataID, HerdNumber, HerdID, NULL as NaabCode, BangsNumber FROM [Animals].[Females] ``` **[SQL Fiddle](http://sqlfiddle.com/#!6/94929/2)** I don't remember that SQL Server supports the `corres...
Just do the `union` explicitly listing the columns: ``` select DataID, HerdNumber, HerdID, NaabCode, NULL as BangsNumber from Animals.Males union all select DataID, HerdNumber, HerdID, NULL, BangsNumber from Animals.Females; ``` Note: you should use `union all` instead of `union` (assuming that no single animal is bo...
T-SQL Union with Dissimilar Columns
[ "", "sql", "sql-server", "" ]
I'm not even sure if this is possible using SQL, but I'm completely stuck on this problem. I have a table like this: ``` Total Code 212 XXX_09_JUN 315 XXX_7_JUN 68 XXX_09_APR 140 XXX_AT_APR 729 XXX_AT_MAY ``` I need to sum the "total" column grouped by the code. The issue is that "XXX\_09\_JUN" and "XXX\_7\_JUN...
One option is to use a `CASE` expression: ``` GROUP BY CASE WHEN Code LIKE '%!_09!_%' ESCAPE '!' THEN 'had_a_number' WHEN Code LIKE '%!_7!_%' ESCAPE '!' THEN 'had_a_number' WHEN Code LIKE '%!_AT!_%' ESCAPE '!' THEN 'had_at' E...
[SQL Fiddle](http://sqlfiddle.com/#!3/f0a20/1) **MS SQL Server 2008 Schema Setup**: ``` CREATE TABLE TEST_TABLE(Total INT, Code VARCHAR(20)) GO INSERT INTO TEST_TABLE VALUES (212, 'XXX_09_JUN'), (315, 'XXX_7_JUN'), (68, 'XXX_09_APR'), (140, 'XXX_AT_APR'), (729, 'XXX_AT_MAY') GO ``` **Query 1**: ``` SELECT SUM(To...
Using conditions to specify groups for GROUP BY
[ "", "sql", "sql-server", "sql-server-2008", "reporting-services", "" ]
I am looking for a means of removing leading and trailing spaces based on the following scenario within an Oracle 11gR2 DB using SQL. Not sure if I require REGEXP\_REPLACE. At the moment I have the following possible scenario: ``` v_entries := '"QAZ "," QWERTY ","BOB "," MARY ","HARRY"," TOM JONES "'...
Assuming you don't want to split the string into its components, you can use a regular expression to remove the spaces. If you want to get rid of all spaces - so you don't have any two-word values, for example - then you can use: ``` v_entries := regexp_replace(v_entries, '[[:space:]]', null); ``` But if you might ha...
You should use the `trim()` function to remove leading and trailing spaces. [Here's the documentation](http://docs.oracle.com/javadb/10.6.1.0/ref/rreftrimfunc.html) on how to use `trim()`.
How to remove both leading and trailing spaces within a group of data in Oracle11gR2?
[ "", "sql", "regex", "oracle11g", "" ]
Is it possible to achieve something like this in SQL? ``` SELECT * FROM `services` WHERE servide_id = ('wifi','pulizia','parking','ombrellone','driver','colazione') AND active = 1 ``` For example i have an table like: ``` service |price |active wifi €60 0 park €20 1 option €30 1 an...
You need to use the SQL [IN](http://www.w3schools.com/sql/sql_in.asp) operator to filter on multiple values. So your query should be : ``` SELECT * FROM `services` WHERE servide IN ('wifi','pulizia','parking','ombrellone','driver','colazione') AND active = 1 ```
Just use `IN` ``` SELECT * FROM `services` WHERE service_id IN ('wifi','pulizia','parking','ombrellone','driver','colazione') AND active = 1 ```
SQL : how to select different rows where values are equal to an set of values?
[ "", "mysql", "sql", "" ]
My stored procedure: ``` CREATE PROCEDURE TEST_TEMPLATE @TEMPLATE_TYPE INT=NULL AS BEGIN SELECT TEMPLATE_ID, TEMPLATE_NAME FROM BDC_TEMPLATES WHERE TEMPLATE_CAN_BE_APPLIED_TO IN ( CASE WHEN @TEMPLATE_TYPE=0 OR @TEMPLATE_TYPE=1 THEN @TEMPLATE_TYPE --...
First of all you can't use `INT` variable with `IN` statement, you need to use table variable with `SELECT` statement. **UPDATE** You can’t use a scalar variable in the `IN` statement like record set. However if this variable has a single data value (as I think this is what you are trying to do) is OK. In this case th...
let's see if this help ``` CREATE PROCEDURE TEST_TEMPLATE @TEMPLATE_TYPE INT=NULL AS BEGIN SELECT TEMPLATE_ID, TEMPLATE_NAME FROM BDC_TEMPLATES WHERE (TEMPLATE_CAN_BE_APPLIED_TO = @TEMPLATE_TYPE AND (@TEMPLATE_TYPE=0 OR @TEMPLATE_TYPE=1)) OR (TEMPLATE_CAN_BE_APPLIED_TO IN(SELECT DATA FROM UDF_DP_S...
SQL query error from case when statement with subquery
[ "", "sql", "sql-server", "subquery", "" ]
i've got a problem. I have a table with these columns: languageID languageItem Every row can have only "2" or "3" as languageID and languageItem is always different, but only with the same languageID. For example i can have: ``` 2 | header.title 2 | header.description 3 | header.description 3 | header.title ``` The...
You can do this by just inserting values that don't exist. The query looks like: ``` insert into table(languageId, languageItem) select 3, languageitem from table t where languageid = 2 and not exists (select 1 from table t3 where t3.languageid = 3 and ...
You can use INSERT IGNORE here: ``` insert ignore into mytable(languageId, languageItem) select 3 as languageId, languageitem from mytable where languageid = 2; ``` (Provided of course there is a unique index on languageId + languageItem.)
Sql query for searching values in the same table
[ "", "mysql", "sql", "" ]
Can MySQL search for table rows using two or more indexes? I have a table with these columns: ``` relation: - type varchar(32) - id_foo int - id_bar int ``` I need to search for rows based on `type` and either `presta_id` or `vario_id`. The queries will look like this: ``` SELECT id_foo FROM relation WHERE type = '...
It is better to create two indexes: `relation(type, id_bar)` and `relation(type, id_foo)`. In your case, the two columns could be in either order. But you need two indexes to optimize both queries. MySQL actually has pretty good documentation on the use of composite indexes. See [here](http://dev.mysql.com/doc/refman...
Yes MySQL can. You can find out yourself by issuing: ``` EXPLAIN SELECT id_foo FROM relation WHERE type = 'baz' AND id_bar = 128 ``` There MySQL prints which indexes were used. Multi column indexes (type,id\_bar and type,id\_foo; you need both in order to speed up both `select` queries) are a possible way to speed u...
MySQL - lookup based on more indexes
[ "", "mysql", "sql", "indexing", "" ]
One of the columns of my SQL Server table is `mm:ss` of `varchar` type where `mm` = minutes and `ss` = seconds. I need to get the average of that column. Should I convert that column to `datetime` format first? If so can you tell me how? If not can you tell me what I should do? Here is my failed attempt to convert i...
If you want the average, I would convert the column to number of seconds and work with that: ``` select avg(pace_secs) as average_in_seconds from (select cast(left(pace, 2) as int) * 60 + cast(right(pace, 2) as int) as pace_secs from t ) t; ``` If you want this back in the format, then you can do: ``` sel...
``` declare @pace varchar(20) = '23:05 '; SELECT cast( '2014-01-01 '+cast(@pace as varchar(5))+':00' as datetime) ```
SQL conversion from varchar to datetime
[ "", "sql", "sql-server", "" ]
How can I set the default value of a field as '0000-00-00 00:00:00'? If we can't use '0000-00-00 00:00:00' as the default? What is the **basic** valid tiemdate? For instance, this is the SQL for creating my article table, ``` -- ----------------------------------------------------- -- Table `article` -- -------------...
**Cause of the error: the SQL mode** You can set the default value of a `DATE`, `DATETIME` or `TIMESTAMP` field to the special "zero" value of '0000-00-00' as dummy date if the sql mode permits it. For MySQL versions lower than 5.7.4 this is ruled by the NO\_ZERO\_DATE mode, see this excerpt of the [documentation](htt...
There is a solution. I'm not sure about the security of this so I recommend to ``` SELECT @@SESSION.sql_mode session ``` first. Save the value in your clipboard, then ``` SET SESSION sql_mode = ''; ``` After that you can create or alter the table with default values like '0000-00-00 00:00:00'
How can I set the default value of a field as '0000-00-00 00:00:00'?
[ "", "mysql", "sql", "date", "datetime", "" ]
I'm attempting to create a stored procedure that implements an exclusive or to return a specific record from a table (BasisValues). Here's the table: ``` Basis Value 1 4.25 2 1.25 3 99.00 0 0.00 ``` I've designed a stored procedure to return a BasisValue as follows: ``` CREATE PROCEDURE Ge...
You want to use `order by` to select the prefered value: ``` SELECT TOP 1 Value FROM BasisValues WHERE ( BASIS = @Basis) OR ((BASIS <> @Basis) AND (Basis = '0')) ORDER BY (case when BASIS = @BASIS then 1 else 0 end) DESC; ``` This query (without the `top`) will return one or two values, based on what you desc...
``` CREATE PROCEDURE GetBasisValue @Basis VARCHAR(2) AS BEGIN SELECT ISNULL((SELECT Value FROM BasisValues WHERE (BASIS = @Basis)), '0.00') END ```
Implementing 'exclusive or' to return one record
[ "", "sql", "sql-server-2008", "stored-procedures", "logical-operators", "" ]
so I've got a student table which has FirstName, Lastname, MisID and NetworkName. (MisID is username) Theres an issue that students can potentially have two laptops (an older one) which is not allowed. How can I find when for example the userID occurs twice (therefore having two laptops) This is my code so far but i...
You need to use: ``` select distinct MisID, networkname FROM dbo.CompiledStudentData as t1 inner join ( Select MisID FROM dbo.CompiledStudentData GROUP BY MisID HAVING COUNT(distinct networkname) >= 2 ) as t2 on (t1.MisID = t2.MisID) order by 1, 2 ``` the main idea here: 1. get list of students (MisID) w...
`Select count(1) as cnt , MisID , networkname FROM dbo.CompiledStudentData GROUP BY MisID, networkname`
Finding multiple (different) values under same ID SQL
[ "", "sql", "sql-server", "" ]
how to optimize this query and increase its performance, ``` SELECT user.id,user.name,profile.info,score.amount FROM user LEFT JOIN profile ON profile.user_id = user.id AND profile.type = 'language' LEFT JOIN score ON score.user_id = user.id AND score.type = 'total' WHERE email = 'example@mail.com' ``` return results...
For this query: ``` SELECT u.id, u.name, p.info, s.amount FROM user u LEFT JOIN profile p ON p.user_id = u.id AND p.type = 'language' LEFT JOIN score s ON s.user_id = u.id AND s.type = 'total' WHERE u.email = 'example@mail.com'; ``` (I just added table aliases to make the query more readable and t...
You should give the `profile` and `score` tables composite indexes on `(type, user_id)`. I'm not sure whether it will be better to have `type` or `user_id` first in the indexes, you should try each of them and see which is better; you can use `EXPLAIN` to compare the execution plans for this.
optimize SQL query with multiple JOIN
[ "", "mysql", "sql", "" ]
I have defined a stored procedure in Postgresql: ``` create or replace function test1(arg1 text, opt1 text default 'default value') returns text as $$ select $1 || ' ' || $2; $$ language sql; ``` I would like to inspect this function definition to find out: 1. Which parameters have a default value 2. (bonus) W...
You can select the optional arguments from `pg_proc`, but you probably won't be able to parse their default values' expressions on PostgreSQL's side (because they can have different types). ``` select proargnames[pronargs-pronargdefaults+1:pronargs] optargnames, pg_get_expr(proargdefaults, 0) optargdefaults fro...
You can use `pg_get_function_arguments()` to retrieve the definition of the parameters: ``` SELECT pg_get_function_arguments(p.oid) as parameters FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid WHERE p.proname = 'test1' AND n.nspname = 'public'; ``` This will return `arg1 text, opt1 text DEFAULT ...
Postgresql: How can I inspect which arguments to a procedure have a default value?
[ "", "sql", "postgresql", "" ]
I want to retrieve the maximum invoice number from my invoice table where it returns the following when I select all records where you can clearly see the maximum invoice no as "10". ``` select * from invoice ``` ![enter image description here](https://i.stack.imgur.com/dLTbo.png) But when I query for ``` select MA...
This situation can occur if your `invoice_number` is stored as a text column e.g. `varchar(10)`. In that case, based on alphabetical order, 9 will be the maximum value. Ideally, you should be storing values on which you want to perform numerical operations as numeric datatypes e.g. `int`. However, if for some reason y...
It happens because your column is a `VARCHAR`, try to cast it to `UNSIGNED`: ``` select MAX(CAST(invoice_number AS UNSIGNED)) as maxinv from invoice ``` As Joshi noticed, if you have negative values you can use `SIGNED` ``` select MAX(CAST(invoice_number AS SIGNED)) as maxinv from invoice ```
MAX(Column) returns me a wrong value
[ "", "mysql", "sql", "" ]
I'm creating a multi. language website. here is my sample sql > ``` > select * from admin_real_estate_category_languages as category_languages > left join admin_real_estate_categories as category on category_languages.real_estate_category_id = category.id > where language = 'jp' and category = 'Area' > ``` All deta...
While this might not be the best solution since it introduces an additional join, you can solve your problem in this way. First off, you probably don't want to do select \*, that's generally a bad idea. Select the columns that you actually want to use instead (even if that is all columns). If you then have the actual ...
You could select both, order by language and limit to one (to get just the best match). ``` WHERE language in ('jp', 'en') ORDER BY language DESC LIMIT 1 ``` This assumes that there is only one translation resource to be returned. If there are many, you'd have to group by (or just get all and handle it in your appli...
SQL: Default where clause
[ "", "mysql", "sql", "sql-server", "" ]
I have a table that is having 2 duplicate rows (total of 3 rows), so I used the code below to get the duplicate value in the column ``` SELECT CustNo, COUNT(*) TotalCount FROM Rental GROUP BY CustNo HAVING COUNT(*) > 1 ORDER BY COUNT(*) DESC ``` So once I get the repeated value, I need to get the CustNo derived as du...
``` Select * from Customer where CustNo IN ( SELECT CustNo FROM Rental GROUP BY CustNo HAVING COUNT(*) > 1 ) ```
You can use `join`: ``` SELECT c.* FROM (SELECT CustNo, COUNT(*) TotalCount FROM Rental GROUP BY CustNo HAVING COUNT(*) > 1 ) cc JOIN Customer c on cc.CustNo = c.CustNo; ```
Row value from another table
[ "", "sql", "sql-server", "t-sql", "select", "" ]
I'm trying to make an output array from next statement: I have 2 tables. In each table there is "material\_code" which plays the main role. I want to select *material\_code* from *table1* where it'is equal to *material\_code* from *table2* and join them where *status* (from table2) is equal to *0*. This is what I've ...
You should try this one: ``` SELECT material_code FROM table1 LEFT JOIN table2 ON table1.material_code = table2.material_code WHERE status = 0 ```
Sounds like you want an `INNER JOIN` ``` SELECT material_code FROM table1 INNER JOIN table2 USING (material_code) WHERE status = 0 ``` If you use `LEFT JOIN`, you will get records that only exist in table1 and not in table2. You also want to use `USING` not `ON` if the column name is the same in both tables (at leas...
Select join statement is not working
[ "", "mysql", "sql", "" ]
I wrote a SQL function in SQL Server to convert year-week string into a date as below: ``` CREATE FUNCTION dbo.f_ConvertStringToDate (@yearWeek VARCHAR) RETURNS DATETIME AS BEGIN RETURN DATEADD(WEEK, CONVERT(INT, SUBSTRING(@yearWeek, 6, 2)), DATEADD(YEAR, CONVERT(INT, SUBSTRING(@yearWeek, ...
I found that this worked when I changed your definition to: ``` CREATE FUNCTION dbo.f_ConvertStringToDate (@yearWeek VARCHAR(50)) RETURNS DATETIME AS BEGIN RETURN DATEADD(WEEK, CONVERT(INT, SUBSTRING(@yearWeek, 6, 2)), DATEADD(YEAR, CONVERT(INT, SUBSTRING(@yearWeek, 1, 4)) - 1900, 0)) END ``` Just to note, the way ...
Varchar [ ( n | max ) ] Variable-length, non-Unicode string data. n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered + 2 bytes. When n is not specified in a data definition or...
Adding a value to 'datetime' causing an overflow in SQL Server select query
[ "", "sql", "sql-server", "" ]
I'm working on a problem with two tables. Charge and ChargeHistory. I want to display a selection of columns from both tables where either the matching row in ChargeHistory has a different value and/or date from Charge or if there is no matching entry in ChargeHistory at all. I'm using a left outer join declared using...
You probably want to explicitly select the null values: ``` SELECT values... FROM bcharge charge LEFT OUTER JOIN chgHist history ON charge.key1 = history.key1 AND charge.key2 = history.key2 AND charge.key3 = history.key3 AND charge.chargeType = history.chargeType WHERE charge.chargeType = '2' AN...
You can explicitly look for a match in the `where`. I would recommend looking at one of the keys used for the `join`: ``` SELECT . . . FROM bcharge charge LEFT OUTER JOIN chgHist history ON charge.key1 = history.key1 AND charge.key2 = history.key2 AND charge.key3 = history.key3 AND charge.chargeType...
Oracle left outer join, only want the null values
[ "", "sql", "oracle", "join", "outer-join", "" ]
Let's say I have a table with two columns: ``` id | value ---------- 1 | 101 2 | 356 3 | 28 ``` I need to randomly permute the value column so that each id is randomly assigned a new value from the existing set {101,356,28}. How could I do this in Oracle SQL? It may sound odd but this *is* a real problem, just w...
You can do this by using `row_number()` with a random number generator and then joining back to the original rows: ``` with cte as ( select id, value, row_number() over (order by id) as i, row_number() over (order by dbms_random.random) as rand_i from table t ) select cte.id,...
An Option : `select * from x_table where id = round(dbms_random.value() * 3) + 1;` [Here 3 is the number of rows in your random data table and I am assuming that id is incremental and unique?] I'll think of other options.
Permuting values in SQL
[ "", "sql", "oracle", "permutation", "" ]
I'm fairly new to SQL, and I'm having some problems converting a data type of Guid to String when creating my View. After having a look into the issue I'm not sure why the following statement is throwing the error: ``` Create View or Function failed because no column name was specified for column 2. ``` Statement: `...
You just need to give a new name for that column that will be used when selecting from the view: ``` CREATE VIEW CustomerContactView AS SELECT [Id] ,CAST([Guid] AS NVARCHAR(100)) AS Guid ,[ContactGuid] ,[MethodId] ,[Details] ,[OutcomeId] ,[ActionRequired] ,[IsValid] FROM [Main].[dbo].[Customer_ContactLog...
In a view, when you apply a function or otherwise manipulate a column, concatenate multiple columns, anything like that, you need to give that column an alias: `CAST([Guid] AS NVARCHAR(100)) AS <some clever alias goes here>`.
Converting data type on SQL Server View Creation
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have one table in oracle database which has one column of type `varchar2` and it stores date. the problem is it store date in 2 character year format like 19/08/66 which is equivalent to the 19/08/1966. But when i convert this date using `to_date` function, it returns 19/08/2066 but expecting 19/08/1966. how can i co...
Use to\_date function. ``` TO_DATE('16/06/66','DD/MM/RRRR') ``` Output is 16/06/1966 ``` TO_DATE('16/06/16','DD/MM/RRRR') ``` Output is 16/06/2016 `TO_DATE('16/06/16','DD/MM/RRRR')` when u have run this query in 1940s Output is 16/06/1916 The logic Oracle follows as below the function accepts a 2-digit year and ...
If I remember Oracle correct the `to_date`function accepts a format\_mask and if you use this mask: `'DD/MM/RRRR'` values between 0-49 will return a 20xx year and values between 50-99 will return a 19xx year. So try this: ``` to_date('19/08/66', 'DD/MM/RRRR') ```
Oracle varchar2 to date conversion
[ "", "sql", "oracle", "" ]
I am having problem with the following error > ORA-01843: not a valid month The following query works well if I use ``` SELECT mx.work_order_no, mx.work_order_name, mx.comments FROM max_orders mx WHERE TO_DATE (wo_dt, 'dd/mm/rr') <= (TO_DATE (SYSDATE, 'dd/mon/rr') - 7) ``` However if I change where condition ...
I propose you create a stored function to identify the bad rows: ``` create function invalid_date(p_d in varchar2) return number as v_d date; begin v_d := TO_DATE(p_d, 'dd/mm/rr'); return 0; exception when others then return 1; end; / select * from mx_orders where invalid_date(wo_dt)=1; ```
`SYSDATE` is already a date. You should not be passing it into `TO_DATE()`. When you do that you're doing an implicit conversion to a string, and an explicit conversion back. Gordon Linoff already showed a better way to do that. Based on the view definition you added, `wo_dt` is a string. You're expecting that to be i...
ORA-01843: not a valid month When where condition is changed
[ "", "sql", "oracle", "" ]
Im trying to update a column in SQL so i tried using this: ``` update [BaseHistorica_] set Cierre=CONVERT(datetime2,cierre,103) ``` But appears the following error message: ``` Msg 241, Level 16, State 1, Line 15 Conversion failed when converting date and/or time from character string. ``...
The error message tells us that attempting to convert into datetime2 fails "from character string"; hence [Cierre] appears to be a string already. 1. learn what the actual data type of [Cierre] is first (probably varchar or nvarchar) 2. then learn what format the `stored` values conform to, possibly (if you are lucky)...
What's happening is column Cierre is a string format, such as varchar or nvarcher. When updating BaseHistorica\_ you're trying to convert cierre to datetime2 and store it in column Cierre, which is a string. You'll have to figure out the format of the strings in Cierre and conform to that standard. There's a problem w...
Convert date in SQL
[ "", "sql", "sql-server", "string", "sql-update", "converters", "" ]
I have an Ingres table with date field (data type ingresdate) which has a not null restriction. However blank i.e. empty values are allowed. How can you check for a blank value? Of course testing for null values using ifnull() does not work - as per example below. ``` INGRES TERMINAL MONITOR Copyright 2008 Ingres Cor...
Actually, thanks to PaulM, I figured it out: ``` INGRES TERMINAL MONITOR Copyright 2008 Ingres Corporation Ingres SPARC SOLARIS Version II 9.2.3 login select id, date_field, case when date_field = '' then '01/01/2014' else date_field end as test_field from test +-----------------------------------------------------...
You can use ``` select * from test where date_field = '' ```
How to check for a blank date value in Ingres
[ "", "sql", "date", "string", "ingres", "" ]
I have two sets of data with the same fields: ``` +----+---------+-------------+ | PK | myCDKey | DateCreated | +----+---------+-------------+ | 1 | 131048 | 8/18/2014 | | 2 | 131049 | 8/18/2014 | | 3 | 131050 | 8/18/2014 | | 4 | 131051 | 8/18/2014 | | 5 | 131052 | 8/18/2014 | | 6 | 131053 | 8/18...
[**SQL Fiddle**](http://sqlfiddle.com/#!2/c3b601/14/0): ``` SELECT m1.PK, m1.myCDKey, 'delete' AS `DELETE/ADD` FROM MyTable1 m1 WHERE m1.myCDKey NOT IN ( SELECT t2.myCDKey FROM MyTable2 t2 ) UNION SELECT m2.PK, m2.myCDKey, 'add' AS `DELETE/ADD` FROM MyTable2 m2 WHERE m2.myCDKey NOT IN ( SELECT t1.myCDKey ...
the version using a FULL JOIN would be: ``` select coalesce(m1.PK,m2.PK) PK , coalesce(m1.myCDKey, m2.myCDKey) myCDKey , case when m1.PK is null then 'add' when m2.PK is null then 'delete' else 'error' end as action from MyTable1 m1 FULL OUTER JOIN MyTable2 m2 ON m1.myCDKey = m2.myCDKey WHERE m1.PK is null or ...
merging two sets of data and figuring out which is new and which is old
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
How do you sum a column from an inner join? I have got this far but the results are not correct, for example. ``` SELECT DISTINCT it.CODE, pl.UNITS FROM ITEMDETAILS it inner join plant pl ON it.CODE = pl.CODE WHERE it.LOCNUMBER = '3434'; ``` This give me this result which is correct ``` CODE UNITS GE-ARH 2 GE-...
You can do something like: ``` select sum(units) from ( SELECT DISTINCT it.CODE, pl.UNITS FROM ITEMDETAILS it inner join plant pl ON it.CODE = pl.CODE WHERE it.LOCNUMBER = '3434' ) un ``` Or depending on the sql version ``` ;with un as ( SELECT DISTINCT it.CODE, pl.UNITS FROM ITEMDETAILS it inner join pl...
I would do it like this ``` SELECT SUM(UNITS) AS TOTAL_UNITS FROM ( SELECT DISTINCT it.CODE, pl.UNITS FROM ITEMDETAILS it inner join plant pl ON it.CODE = pl.CODE WHERE it.LOCNUMBER = '3434' ) X ```
Sum column from inner join
[ "", "sql", "sql-server", "" ]
I have an Excel file that exports data into Word. It includes a cover page and grabs the user name ("First.Last") and changes it to "First Last" but I also need to include the user's professional title. This information is housed in an Access table. It has a field called Name and a field called Title. The Name field ma...
Here is the final solution. Thank you to everyone who helped! ``` Dim Path As String Dim User As String Dim Title As String Dim db As DAO.Database Dim rs As DAO.Recordset User = Environ("UserName") User = Replace(User, ".", " ") User = StrConv(User, vbProperCase) Path = "Directory\FileName" Set db = DBEngine.OpenD...
Try this: ``` Public Sub JohnTayloristheBest() Dim conAccess As ADODB.Connection Set conAccess = New ADODB.Connection Dim rdsAccess As ADODB.Recordset Dim strTitle as String With conAccess .ConnectionString = "Data Source= **insert filepath here** " .Provider = "Microsoft.ACE.OLEDB.12.0" .Open End Wit...
Retrieve value from Access table in Excel
[ "", "sql", "excel", "vba", "" ]
In my Ms Sql command, I want to get sum of C.HEIGHT's values ``` SELECT SUM(C.HEIGHT) FROM CIHAZ AS C INNER JOIN ILISKI AS I ON I.REL_CIHAZ=C.ID WHERE I.REL_DOLAP=2 ``` This value is returning NULL but I want to give Default Value to sum(C.HEIGHT) . How can we provide this? Thanks.
Use `COALESCE` to provide a default value in case the column value is NULL, like so: ``` SELECT COALESCE(SUM(C.HEIGHT), yourdefaultvalue) FROM CIHAZ AS C INNER JOIN ILISKI AS I ON I.REL_CIHAZ=C.ID WHERE I.REL_DOLAP=2 ``` `COALESCE` is an ANSI standard function, and you can use it in the way shown above in MySQL, Or...
You can use [`COALESCE`](http://msdn.microsoft.com/en-gb/library/ms190349.aspx) but, since you're aggregating over all results, you're probably getting `NULL` because there are no rows. In that case, you need to wrap the *entire* query as a subquery to get `COALESCE` to act the way that we want: ``` SELECT COALESCE( ...
SQL Command Default Value
[ "", "mysql", "sql", "default-value", "" ]
I have a table 'consumption' in mysql with around 5 million records like: ``` month from | month to | consumption 2012-12-20 2013-01-10 200 2013-01-11 2013-02-13 345 ``` Is there a way to get the consumption for each month like: consumption for January(2013-0...
``` SELECT m.month, SUM( -- partial consumption = date subrange / date range * consumption ( DATEDIFF( IF(c.month_to > m.last_day, m.last_day, c.month_to), IF(c.month_from < m.first_day, m.first_day, c.month_from) ) + 1 ) / (DATEDIF...
Datediff is your friend - try `consumption * 30 / Datediff(day, monthfrom, monthto)`
MYSQL query to get monthly consumption data from table
[ "", "mysql", "sql", "database", "time-series", "energy", "" ]
I'm having this small issue. the table basically looks like the following **Subject** * SubjectId * SubjectName * ParentSubjectId `ParentSubjectId` references the subject table itself. and it can go down for many levels (no specific number of levels) example (using countries just for the sake of this example): ``...
Write as: ``` declare @Subject as varchar(max) set @Subject = 'Rome'; -- set subject name here WITH SubjectCTE AS ( SELECT SubjectId , SubjectName , ParentSubjectId FROM Subject WHERE SubjectName = @Subject UNION ALL SELECT C.SubjectId , C.SubjectName , C.ParentSubjectId FROM SubjectCTE AS P JOIN Subject AS C ON P.P...
This is simple to handle, just add new column HID (varchar) and fill it. ``` 01 Europe 02 America 0101 France 0102 Italy 010101 Paris ``` Selecting parent: ``` DECLARE @childHID varchar(10) = '010101' --Paris SELECT A.ID, A.Name FROM Address A WHERE A.HID = SUBSTRING(@childHID, 1, 2) -- first level ``` ...
SQL - how to get the top parent of a given value in a self referencing table
[ "", "sql", "sql-server", "" ]
I have a `sales` table in which I store every sales. This table has columns like `year_ordered`, `userId`, `orderId` etc. I wish to write a SQL query to select rows, where user has ordered every year from 2008. So I only want those who have been loyal and ordered from 2008 till 2014. I have tried with this query, but...
What you strive for is called relational division. There are basically two ways to accomplish that: ``` select COUNT(distinct ss.year_ordered) as sales_count, ss.userID from subscriber_sub ss where ss.date_deleted is null and ss.year_ordered > 2007 group by ss.userID having COUNT(distinct ss.year_ordered) >= ( sel...
Try this for your `HAVING` clause: ``` HAVING (SELECT COUNT(DISTINCT ss.year_ordered)) = 7 ```
Select where user bought every year
[ "", "sql", "sql-server-2008", "" ]
I have my database setup to allow a user to "Like" or "Dislike" a post. If it is liked, the column isliked = true, false otherwise (null if nothing.) The problem is, I am trying to create a view that shows all Posts, and also shows a column with how many 'likes' and 'dislikes' each post has. Here is my SQL; I'm not su...
Problem 1: FULL OUTER JOIN versus LEFT OUTER JOIN. Full outer joins are seldom what you want, it means you want all data specified on the "left" and all data specified on the "right", that are matched and unmatched. What you want is all the PostData on the "left" and any matching Likes data on the "right". If some righ...
Instead of selecting `Count(trippin.LikesDislikesData.liked)` you could put in a select statement: ``` Select AccountData.username, PostData.posttext, CategoryData.categoryname, (select Count(*) from LikesDislikesData as likes2 where likes2.postid = postdata.id and likes2.liked = 'like' ) as TimesLiked ...
How can I perform the Count function with a where clause?
[ "", "sql", "sql-server", "" ]
I have a sql table that is an audit trail. I am trying to grab the most recent time the price was changed. Using this query I have the following data ``` select id as id_1 ,item_no, price ,post_dt ,post_tm ,aud_action from iminvaud_sql where item_no = '1-ADVENT EN...
Your query is essentially: ``` select s.* from iminvaud_sql s where s.item_no = '1-ADVENT ENGLISH' and s.aud_action in ('B','C') order by id desc; ``` As far as I can tell, the "B" and "C" are not adding any information. Instead, let's look at the first occurrence of the most recent price. I will base this on `id`. ...
Not sure what your requirement is - but if you just want the top row - then use top: ``` select select top 1 id as id_1, item_no, price, post_dt, post_tm, aud_action from iminvaud_sql where item_no = '1-ADVENT ENGLISH ' and aud_action in ('B','C') order by post_dt desc, post_tm desc ```
How do I grab the most recent price change from table
[ "", "sql", "sql-server-2008-r2", "" ]
I want list all the rows by alternative publisher with price ascending, see the example table below. ``` id publisher price 1 ABC 100.00 2 ABC 150.00 3 ABC 105.00 4 XYZ 135.00 5 XYZ 110.00 6 PQR 105.00 7 PQR 125.00 ``` The expected result would ...
This should do it: ``` select id, publisher, price from ( select id, publisher, price, row_number() over (partition by publisher order by price) as rn from publisher ) t order by rn, publisher, price ``` The window functions assigns unique numbers for each publisher price. Based on that the outer order b...
``` SELECT id, publisher, price FROM tbl ORDER BY row_number() OVER (PARTITION BY publisher ORDER BY price), publisher; ``` One cannot use the output of [window functions](http://www.postgresql.org/docs/current/interactive/functions-window.html) in the `WHERE` or `HAVING BY` clauses because window functions are app...
Select all rows based on alternative publisher
[ "", "sql", "postgresql", "sql-order-by", "window-functions", "" ]
Is there any function in `PostgreSQL` that returns `Boolean` whether a given string is a date or not just like `ISDATE()` in MSSQL? ``` ISDATE("January 1, 2014") ```
You can create a function: ``` create or replace function is_date(s varchar) returns boolean as $$ begin perform s::date; return true; exception when others then return false; end; $$ language plpgsql; ``` Then, you can use it like this: ``` postgres=# select is_date('January 1, 2014'); is_date --------- t (...
@ntalbs answer is good except in the case of `NULL` values. I don't want `is_date` to return `true` if I pass it a `NULL` value. This tweak gets around that issue: ``` create or replace function is_date(s varchar) returns boolean as $$ begin if s is null then return false; end if; perform s::date; return ...
Check whether string is a date Postgresql
[ "", "sql", "postgresql", "date", "" ]
have no idea how to solve following: There are three tables each with a column of names, for example * Table 1 - column name 'Name' - values 'A', 'B' and 'C' * Table 2 - column name 'Name' - values 'A' and 'B' * Table 3 - column nane 'Name' - values 'A' and 'C' The goal is to UNION the tables - each value of the thr...
Does this do what you want? ``` select Name, max(Table1) as Table1, max(Table2) as Table2, max(Table3) as Table3 from (select Name, 1 as Table1, 0 as Table2, 0 as Table3 from table1 union all select Name, 0 as Table1, 1 as Table2, 0 as Table3 from table2 union all select Name, 0 as ...
If your db supports full joins you can try the query below. ``` select coalesce(t1.Name,t2.Name,t3.Name) myValue, (case when max(t1.Name) is not null then 1 else 0 end) c1, (case when max(t2.Name) is not null then 1 else 0 end) c2, (case when max(t3.Name) is not null then 1 else 0 end) c3 from Table1 t1 f...
Union three tables and show where data came from
[ "", "sql", "union", "" ]
I have a database table that contains multiple entries for each user during a period of time. The query I'm trying to build will only return the most recent record for each user during that time period. what I have thus far: ``` SELECT * FROM (SELECT DISTINCT * FROM picks_recorded) WHERE date_submitted > '" . $week_s...
Try this: ``` select distinct p.* from picks_recorded p inner join (select userid, max(date_submitted) as maxdate from picks_recorded WHERE date_submitted > '" . $week_start . "' AND date_submitted < '" . $week_end . "' group by userid) s on p.userid = s.userid and p.date_submitted = s.maxdate ``` Basically, we use ...
Try to change `DISTINCT *` into this `DISTINCT(userid)`. For example: ``` SELECT * FROM (SELECT DISTINCT(userid) FROM picks_recorded) WHERE date_submitted > '" . $week_start . "' AND date_submitted < '" . $week_end . "' ORDER BY date_submitted DESC LIMIT 1; ```
select most recent records with unique user id
[ "", "mysql", "sql", "distinct", "" ]
Scenario: I am creating a website for a checklist, it can be done/accessed by multiple users in the same time thus it needs certain fields to be editable, saveable and retrievable. Dilemma: The checklist has 212 entries, this means 212 rows. I have 5 columns that needs entries thus, 212x5. This means, I have ...
why not directly add 1 more column in your checklist table? your table structure should look like 1. userid 2. entryid (value from 1-212) 3. col1\_entry 4. col2\_entry 5. col3\_entry 6. col4\_entry 7. col5\_entry
looking thrrough all your requirements, thou you've ban the common 6 column setup, I'd still suggest you to use a similar setup. try to have a table like this ``` id [bigInt] (PK,auto_incrment) rowId [int] //checklist row id columnId [int] //checklist column id text [varchar/text] create_date [Date] create_time [Time...
Dilemma about the number of columns on a table
[ "", "mysql", "sql", "database", "" ]
I've got some sensory information going into a table. I have figured out the query that will tell me exactly when the value at a particular device changes. What I need to know is the status of all of the other sensors at that time. The trick is, the timestamps won't be equal. I could get a data point from sensor 1, th...
## Query For a **small**, **given** set of sensors to retrieve (this works for Postgres **8.4** or later): ``` SELECT c.sensor AS sensor_change , d1.state AS state_1, d1.stime AS stime_1 , d2.state AS state_2, d2.stime AS stime_2 , d3.state AS state_3, d3.stime AS stime_3 FROM ( SELECT sensor, stim...
There are a couple of things making this not-so-straightforward: * You want to do a subquery for each `state_changed_view` row, but the subquery must mention the corresponding `stime` from the view (to restrict it to earlier records). Ordinary subqueries aren't allowed to depend on external fields, but you can accompl...
SQL Query where I get most recent rows from timestamp from another table
[ "", "sql", "postgresql", "join", "timestamp", "plpgsql", "" ]
I need to add a constraint to one table in my database. The table name is Experience. And there is a column named ToDate. Every time the select statement executes like following. ``` select ToDate from Experience ``` It should return current date. So every time select statement executes, the ToDate column get update...
You can use a [computed column](http://msdn.microsoft.com/en-us/library/ms188300.aspx#TsqlProcedure). That's specified like `colname as <expression>`: ``` create table t1(id int, dt as getdate()); insert t1 values (1); select * from t1; ```
You cannot use a constraint, because a constraint is basically a rule on what can go in the table, how the table can relate to others, etc. It has no bearing on the data in the table once it goes into the table. Now if I am understanding you correctly, you want to update the `ToDate` column whenever you select that col...
sql current date constraint
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have a column in the sql server called "Ordinal" that is used to indicate the display order of the rows. It starts from 0 and skips 10 for the next row. so we have something like this: ``` Id Ordinal 1 0 2 20 3 10 ``` It skips 10 because we wanted to be able to move item in between items (based on ordinal...
You can re-number the sequences using a somewhat complicated `UPDATE` statement: ``` UPDATE u SET u.sequence = 10 * (c.num_below-1) FROM test u JOIN ( SELECT t.id, count(*) AS num_below FROM test t JOIN test tr ON tr.sequence <= t.sequence GROUP BY t.id ) c ON c.id=u.id ``` The idea is to obtain a count of it...
These won't answer your question directly--I just thought I might suggest some other approaches: One possibility--don't try to do it by hand. Have your software manage the numbers. If they need re-writing, just save them with new numbers. a second--use a "Linked List" instead. In each record store the index of the ne...
What is the best way to reassign ordinal number of a move operation
[ "", "sql", "algorithm", "" ]
Is there some SQL that will either return a list of table names or (to cut to the chase) that would return a boolean as to whether a tablename with a certain pattern exists? Specifically, I need to know if there is a table in the database named `INV[Bla]` such as `INVclay`, `INVcherri`, `INVkelvin`, `INVmorgan`, `INVg...
This should get you there: ``` SELECT * FROM INFORMATION_SCHEMA.TABLES where table_name LIKE '%INV%' ``` EDIT: fixed `table_name`
To check for exists: -- ## -- note that the sql compiler knows that it just needs to check for existence, so this is a case where "select \*" is just fine if exists (select \* from [sys].[tables] where upper([name]) like N'INV%') select N'do something appropriate because there is a table based on this pattern';
How can I Retrieve a List of All Table Names from a SQL Server CE database?
[ "", "sql", "sql-server-ce", "windows-ce", "database-schema", "" ]
I am currently having a problem when trying to select where a job is listed in the tbl\_jobs table and has not been assigned to a delivery item in the tbl\_delivery\_items table by using a NOT IN subquery. The sub query should return supplier\_job\_job\_id 1 (which it does when you run this as a seperate query), with ...
The problem is that the subquery is rendered as a string. You can see this clearly in the generated query that you supplied. This seems to be a limitation in the `where_not_in` method of CodeIgniter. A possible solution, change the code to call the `where` method and render a slightly larger part of the query yourself...
The query isn't executing the subquery it is using the string value: ``` `supplier_job_job_id` NOT IN ( 'SELECT delivery_item_job_id FROM tbl_delivery_items' ) ``` Will check if `supplier_job_job_id` equals the string `'SELECT delivery_item_job_id FROM tbl_delivery_items'`. You should consider a `LEFT JOIN` to `tb...
MySql NOT IN failing to return empty set
[ "", "mysql", "sql", "codeigniter", "sql-in", "" ]
I have this sample table on MSSQL Server ``` CREATE TABLE tbl ( value FLOAT, formula NVARCHAR(50) ); INSERT INTO tbl VALUES ('45.6452','/0.055'); ``` now i want to select the table with the result of the 2 columns ``` select <computation> as Result from tbl ``` what is the correct query to generate the result ...
You can try using `CASE WHEN` clause, however the calculations should be known beforehand (and also should be supported in SQL server): ``` select case left(formula,1) when '/' then value / convert(float,stuff(formula,1,1,'')) when '*' then value * convert(float,stuff(formula,1,1,'')) when '+' then valu...
You can try using this query ``` DECLARE @query VARCHAR(1000) SET @query = '' SELECT @query = @query + ' SELECT ' + CONVERT(VARCHAR,value) + formula + ' as [RESULT]' FROM xtbl EXEC(@query) ```
how to compute value on columns with formula
[ "", "sql", "sql-server", "" ]
I meet a SQL statement with ORDER BY clause, that I can not understand. ``` SELECT ... FROM ... WHERE ... JOIN ... ORDER BY ( CASE WHEN versions.effective_date IS NULL THEN 1 ELSE 0 END) DESC, versions.effective_date DESC, v...
**Illustration:** Supposing original data is ordered like this ``` effective_date, effective_date, name, id 3/1/2010 3/1/2010 ABC 1 1/1/2010 1/1/2010 ABC 2 2/1/2010 2/1/2010 ABC 3 NULL NULL ABC 4 ...
> ORDER BY (CASE WHEN versions.effective\_date IS NULL THEN 1 ELSE 0 END) DESC If `versions.effective_date` not available (`NULL`), those records will be **`listed at last`**. All other records (`NOT NULL`) will be shown at **`top of the list`**.
SQL order by with case
[ "", "mysql", "sql", "sql-server", "sql-order-by", "" ]
In Sql Server 2008 my select query result is like below. ``` Col1 Col2 Col3 ------------------------------------------ 1001 HO 160.00 1001 HO 40.00 1001 HO 200.00 1002 HO 10.00 1002 HO ...
i am just created sample data and gave you the query.So you can implement in your original query ``` declare @t table(id int,Name varchar(10)) insert into @t (id,name)values (1,'HO') insert into @t (id,name)values (1,'HO') insert into @t (id,name)values (2,'HO') insert into @t (id,name)values (2,'HO')...
Try this ``` select col1, col2+cast(row_number() over (partition by col1 order by col1) as varchar(10)) as col2, col3 from your_table ```
Sequence numbers for individual values in column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table test with a column names which have both integer as well as non integer values ``` +------------+ | names | +------------+ | 123 | | 123abc | | 89 | | dkkjdk | | dkdn | +------------+ ``` I would like to display the count of integer and non integer values in a single r...
Here is the solution ``` SELECT COUNT(CASE WHEN not names REGEXP '^[0-9]+$' THEN 1 END) AS ALPHA, COUNT(CASE WHEN names REGEXP '^[0-9]+$' THEN 1 END) AS DIGIT FROM test; ``` Output ``` +-------+-------+ | ALPHA | DIGIT | +-------+-------+ | 3 | 2 | +-------+-------+ ```
Use a sum of a condition based on regex: ``` select sum(names rlike '^[0-9]+$') integer_count, sum(names not rlike '^[0-9]+$') non_integer_count from test ``` See [SQLFiddle](http://sqlfiddle.com/#!2/c60d2/3) Some explanation: * `rlike` is the regex version of `like` * the regex `^[0-9]+$` matches if the *e...
display count of numeric and non numeric column value in a single row in mysql
[ "", "mysql", "sql", "" ]
``` SELECT t.KeyID, t.VaR, t.DB FROM ( SELECT t1.[KeyID], t1.[VaR], '383' AS DB FROM Table1 AS t1 UNION ALL SELECT t2.[KeyID], t2.[VaR], '55' AS DB FROM Table2 AS t2 ) AS t INNER JOIN ( ( SELECT t3.[KeyID], t3.[VaR] FROM Table1 AS t3 UNION ALL SELECT t4.[KeyID], t4.[VaR] F...
this code must be work ``` SELECT t.KeyID, t.VaR, t.DB FROM ( SELECT t1.[KeyID], t1.[VaR], '383' AS DB FROM Table1 AS t1 UNION ALL SELECT t2.[KeyID], t2.[VaR], '55' AS DB FROM Table2 AS t2 ) AS t INNER JOIN ( select * from ( SELECT t3.[KeyID], t3.[VaR] FROM Table1 AS t3 UNION A...
You can only `GROUP BY` the subject of a `SELECT`, so you'd need to add an additional `SELECT` clause to get this to work, I think. Something like: ``` SELECT t.KeyID, t.VaR, t.DB FROM ( SELECT t1.[KeyID], t1.[VaR], '383' AS DB FROM Table1 AS t1 UNION ALL SELECT t2.[KeyID], t2.[VaR], '55' AS DB FROM Tabl...
SQL Group By and Inner Join syntax
[ "", "sql", "ms-access", "syntax", "group-by", "inner-join", "" ]
I have an awkward SQL Puzzle that has bested me. I am trying to generate a list of possible configurations of student blocks so I can fit their course choices into a timetable. A list of possible qualifications and blocks for a student could be as the following: ``` Biology A Biology C Biology D Biology E Chemist...
For a fixed number of qualifications, the answer is relatively simple - the `CROSS JOIN` option from the previous answers will work perfectly. However, if the number of qualifications is unknown, or likely to change in the future, hard-coding four `CROSS JOIN` operations won't work. In this case, the answer gets more ...
One giant cross join? ``` select * from tablea,tableb,tablec,tabled ``` That will actually work for what you need, where tablea is the biology entries, b is chem, c is computing and d is tutorial. You can specify the joins a bit better: ``` select * from tablea cross join tableb cross join tablec cross join tabled. ...
Generating all possible combinations of a timetable using an SQL Query
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I really need help this time. I search everywhere, tried numerous solutions. but i can't seem to solve my problem. Now i'm going to ask, please help. I have been having this problem for a week now. ``` ExecuteSQL("select * from account_database where idnum= @idnum and password= @pass") 'Dim idnum As New SqlParameter("...
Problem is simply you're doing this in the wrong order. You're attempting to execute your SQL statement before defining the parameters. You don't need ExecuteSQL() until you've defined your parameters. It likely breaks on the following line in ExecuteSQL() ``` ' See how many rows the query will impact ' Since @idnum a...
Try this: ``` cmd.Parameters.AddWithValue("idnum", idnumtxt.Text) ``` Reference: * [SqlParameterCollection.AddWithValue @ MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx).
vb.net sql parameterization
[ "", "sql", "vb.net", "vb.net-2010", "" ]
i have a this sql query using uin ``` SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert WHERE scores_ofexpert.user_id = '30' AND scores_ofexpert.score > '0' UNION SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert WHERE scores_ofexpert.user_id = '30' AND scores_ofexpert.score < '0' UNI...
You can use `CASE` ``` SELECT SUM(CASE WHEN s.score < 0 THEN s.score ELSE 0 END) n_sum, SUM(CASE WHEN s.score > 0 THEN s.score ELSE 0 END) p_sum, SUM(s.score) `sum` FROM scores_ofexpert s WHERE s.user_id = '30' ```
This is another answer ``` SELECT ( SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert WHERE scores_ofexpert.user_id = '30' AND scores_ofexpert.score > '0' ) p_sum, ( SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert WHERE scores_ofexpert.u...
joining 3 field in mysql
[ "", "mysql", "sql", "union", "" ]
Having difficulty with inner joins when trying to display from 3 tables. They are structured as in the picture below: <http://pbrd.co/1odLBZy> What I'm trying to achieve is to select the following from the **task** table: * ProjectID (as project.Name) * WorkerID (as user.Username) * Name * OrderInProject * TimeSpent...
``` SELECT p.Name AS ProjectID, u.Username AS WorkerID, t.Name, t.OrderInProject, t.TimeSpent, t.Description, t.DueDate FROM task t INNER JOIN user u ON t.WorkerID = u.UserID INNER JOIN project p ON t.ProjectID = p.ProjectID ``` If you also want to get the `Username` of the `ProjectManagerID` then use the follo...
In order to answer something like this it is best to start with a single table then add the columns and other tables testing each addition along the way. That said the following should be close: ``` SELECT t.Name, t.OrderInProject, t.TimeSpent, t.Description, t.DueDate, p.Name, ...
Inner join from 3 tables
[ "", "sql", "join", "inner-join", "" ]
I need to create a stored procedure that: 1. Accepts a table name as a parameter 2. Find its dependencies (FKs) 3. Removes them 4. Truncate the table I created the following so far based on <http://www.mssqltips.com/sqlservertip/1376/disable-enable-drop-and-recreate-sql-server-foreign-keys/> . My problem is that the ...
Use a cursor to go through your SELECT results, populating a variable with the single column, and executing that query with EXEC(@YourVariable). Be sure to use parens around the variable!
The issue is that you are only preparing the SQL statement and not executing it (I think) ``` CREATE PROCEDURE DropDependencies(@TableName VARCHAR(50)) AS BEGIN DECLARE @SQL nvarchar(max) SELECT @SQL = 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT ' +...
Stored procedure to remove FK of a given table
[ "", "sql", "sql-server-2012", "" ]
This is my sql query I wont to convert into rails model query ``` sql : SELECT "vouchers".* FROM "vouchers" WHERE "vouchers"."business_id" = 31 AND '2014-08-20' between start_date and end_date; ``` My tried model query but this not working please help me to make it working ``` Voucher.where(["#{Date.today} BETWEEN ...
Assuming that start\_date and end\_date are columns try this version ``` Voucher.where("current_date between start_date and end_date").where(business_id: 31) ```
Try in this format: ``` data = ModelName.where("today >= from_date AND today <= to_date") ```
how to write Rails model query between date
[ "", "sql", "ruby-on-rails", "database", "ruby-on-rails-3", "activerecord", "" ]
I am trying to check for dates but after running the query below, it displays no result. Could someone recommend me the correct syntax? ``` SELECT TOP 10 * FROM MY_DATABASE.AGREEMENT WHERE end_dt=12/31/9999 ```
**12/31/9999** might look like a date for you but for the database it's a calculation: **12 divided by 31 divided by 9999** and because this involves INTEGER division this results in an INTEGER **0** So finally you compare a DATE to an INT and this results in typecasting the DATE to a INT. The only reliable way to w...
Is it a date column? Then try `where end_dt = '9999-12-31'`.
check for dates syntax - teradata SQL
[ "", "sql", "teradata", "" ]
why does this work, ``` select* from some_table WHERE some_column_name like '%i%' ``` and not this? ``` select* from some_table WHERE some_column_name like (select ''''+'%' +value +'%' + '''' as val from [dbo].[fn_Split](' i this is a test testing Chinese undefined',' ') ...
the LIKE operator takes a string for an argument. It cannot be used on a table, which I assume your function returns. I think what you want to do is JOIN to the function, and then check where LIKE fn.Value: ``` select * from some_table t INNER JOIN (select value as val from [dbo].[fn_Split](' i this is a test testin...
One possible reason is because you are appending single quotes onto the beginning and end of the string, and none of the values actually store single quotes in the string. Another reason is might not work is because the subquery returns more than one row or zero rows. The function `fn_split()` is your own function, so...
sql, using a subquery in the like operator
[ "", "sql", "sql-server", "" ]
Is there any SQL statements to replace everything in a string with an 'X'. The strings aren't all the same length so it makes it a bit tricky. I haven't been able to find anything that does this except the function below but it takes a long time when I pass in 'a-z0-9' since I have to search on all of those but I reall...
If this is SQL Server, you can use the `REPLICATE` function and simply replicate `x` the `LEN()` of the string. ``` SELECT REPLICATE('x', LEN(@String)) ``` [sqlFiddle](http://sqlfiddle.com/#!3/f084e/1) *Edit - Looks like this is also available in MySQL via `REPEAT()` but I haven't tested*
You can use Replicate and Len functions to replace all characters. ``` declare @str varchar(20) set @str = 'abc' select @str = REPLICATE('X', len(@str)) select @str ```
SQL Replace all characters in a string
[ "", "sql", "string", "replace", "" ]
I have a table containing following column ``` APP_ID(VarChar),USER_ID(VarChar), ROLE_ID(Number),.... app1 user1 3 app1 user2 3 app2 user2 4 app2 user3 3 app3 user1 7 ``` As you can ...
No. You might have a collision. For instance, these two rows would have the same id (app1user212): ``` app1 user2 12 app1 user21 2 ``` This is easily fixed by using delimiters. So, the following would be fine with most tables: ``` (a.APP_ID || '|' || a.USER_ID || '|' || a.ROLE_ID) as ID ```
Can you use the `rownum`? ``` UPDATE table SET table_key = rownum; ```
Generating unique number in Oracle
[ "", "sql", "oracle", "oracle11g", "" ]
I am reviewing a query which should pull in a list of transactions within a month, either based on its **created\_at** date OR its **returned\_at** date. ``` SELECT * FROM (`transaction`) WHERE `created_at` >= '2014-08-01' AND `created_at` <= '2014-08-31' OR `returned_at` >= '2014-08-01' AND `returned_at` <= '201...
Writing it explicitly is always a good idea, but yeah, [`AND` comes before `OR`](http://dev.mysql.com/doc/refman/5.5/en/operator-precedence.html) For your pleasure, checked them all explicitly for you: ``` $ php -r '$d = 0; while($d < pow(2,4)){$bin = sprintf("%04b",$d); echo $bin." => ".@mysql_result(mysql_query("SE...
Its operator precence. AND is guaranteed to be evaluated before OR
mysql OR/AND - how does order of operations work
[ "", "mysql", "sql", "database", "" ]
Got a table in SQL Server which contains a `varchar` column with date data. Unfortunately the dates are in a whole slew of different formats. ``` 2012-05-01 27/05/2012 07MAY2014 19/07/13 ``` There may be others, but that's all I've encountered so far. I need to squeeze these into a `datetime` column into another ta...
My guess is that you just have to try to differentiate between the different classes and handle each case in the appropriate way. Something like this: ``` declare @tab table (d varchar(20)) insert @tab values ('2012-05-01'),('27/05/2012'),('07MAY2014'),('19/07/13') select case when isnumeric(left(d,4)) ...
In SQL Server 2012, you could use `try_convert()`. Otherwise, you could multiple updates: ``` UPDATE myTable SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103) WHERE ISDATE(myDateColumn) = 0 AND MyDateColumn like '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]'; UPDATE myTable SET myDateColumn = CONVER...
How to standardise a column of mixed date formats in T-SQL
[ "", "sql", "sql-server", "t-sql", "date", "datetime", "" ]
I'm basically trying to reverse what this question is asking... [SQL Server query xml attribute for an element value](https://stackoverflow.com/questions/12913724/sql-server-query-xml-attribute-for-an-element-value) I need to produce a result set of "row" elements that contain a group of "field" elements with an attri...
It's a bit involved in SQL Server - the normal behavior is what you're seeing - the column names will be used as XML element names. If you *really* want all XML elements to be named the same, you'll have to use code something like this: ``` SELECT 'id' AS 'field/@name', id AS 'field', '', 'version' AS...
You can do this without having to specify the columns as constants and that will allow you to also use `select *`. It is a bit more complicated than the answer provided by marc\_s and it will be quite a lot slower to execute. ``` select ( select T.X.value('local-name(.)', 'nvarchar(128)') as '@name', ...
SQL Server generating XML with generic field elements
[ "", "sql", "sql-server", "xml", "" ]