Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using Mainframe Db2. Its a patient database. My requirement is to fetch different information from 3 tables, TABACC, TABPAY and TABINS. TABACC will always have a row for a patient but TABPAY and TABINS may or may not have a row for a patient in the system. Which will be more efficient, a QUERY on TABACC with LEFT...
It depends. If all you doing is pulling back 1 row data from three tables, then it's hard to beat COBOL's random read. There's simply less overhead. SQL isn't magic. But you mention writing out to a file. So lets assume that you're pull back 100s, 1,000s or even millions of rows from those files and outputting them t...
If the columns on which you are joining are indexed then that is the more efficient method.
Left Outer Join Vs Individual Queries DB2
[ "", "sql", "db2", "mainframe", "" ]
The software I am working on has a requirement to get the first and last records of an ordered dataset. Dataset is ordered by a date column. The data I have: ``` --table "notes": -- ordered by this -- | -- V note_id date_created attribute1 attribute2 ... -- I want to get ------...
You can use window functions: ``` select t.* from (select t.*, row_number() over (order by date_created) as seqnum, count(*) over () as cnt from t ) t where seqnum = 1 or seqnum = cnt; ``` In Oracle 12, you can also do: ``` select t.* from t order by date_created fetch first 1 rows only union...
If I got it right, try this: ``` select t1.* from YOUR_TABLE t1 , ( select min(note_id) keep(dense_rank first order by date_created) min_val , max(note_id) keep(dense_rank last order by date_created) max_val from YOUR_TABLE ) t2 where t1.note_id = t2.min_val or t1.note...
Oracle SQL get the first and last records from an ordered dataset
[ "", "sql", "oracle", "" ]
I have date in my select query in below format ``` Thu Sep 04 23:03:30 GMT 2014 ``` and in my Table date is in this format ``` 13-NOV-13 03.38.22.000000000 AM ``` How can I convert in the DB format. I tried using ``` TO_CHAR('Thu Sep 04 23:03:30 GMT 2014','DD-MMM-YY HH:MI:SS') ``` but not working. Any help will b...
This: ``` select to_char(timestamp '2014-09-04 23:03:30 GMT','DD-MON-YY HH:MI:SS') from dual ``` converts the timestamp represented by 'Thu Sep 04 23:03:30 GMT 2014' into the format 'DD-MON-YY HH:MI:SS' (I think you meant MON, not MMM) But the input literal has to be changed to '2014-09-04 23:03:30 GMT' (as shown) ...
Try This: ``` LEFT(DATENAME(dw,date),3) +' '+ CAST(date AS VARCHAR(20)) ```
Date in SQL Select Query
[ "", "sql", "" ]
I have a SQL variable: ``` SET @TSQL = 'this is test string [this text may vary] other text' ``` Now I want to replace the sub-string "[this text is may vary]" with my own different text. Can anybody help me? Remember the the sub-string which I want to replace is not static it is dynamic and may vary. This looks sim...
Take the Substring before '[' add your replacement and the Substring right of ']' ``` declare @TSQL varchar(100) declare @R varchar(100) SET @TSQL = 'this is test string [this text may vary] other text' SET @R = 'MySubstitute' Select Left(@TSQL,Charindex('[',@TSQL)-1) + @R + RIGHT(@TSQL,Charindex(']',REVERSE(@TSQL))-1...
Is it just as simple as this? ``` SET @TSQL = 'this is test string ' + @NewText + ' other text' ``` Or, if the expected-preceding-text is not the only text preceding, maybe: ``` SET @TSQL = 'this is test string [this text may vary] other text' DECLARE INT @TSQL_PrefixEnding = PATINDEX('%this is test string [[]%[]] o...
How to replace a substring before and after a specific character in SQL Server?
[ "", "sql", "sql-server", "database", "" ]
I'm trying to convert `nvarchar(16)` to `bigint` but receives an error as follows ``` "Arithmetic overflow error converting expression to data type int." ``` How can I fix it this is my sp ``` Create Procedure [dbo].[GenerateAccountNo] As Begin declare @tmp bigint set @tmp =(CONVERT(bigint,'1111111111111111')) re...
The return value from a stored proc is INT, not BIGINT. Stored procs are designed for data selection. You should use a FUNCTION in this case instead to return a scalar value that is not related to a table.
From [MSDN](http://msdn.microsoft.com/en-us/library/ms187926.aspx) > Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure). You are returning the status(`INT`) from a Stored Procedure. This would be the execution result code (success or failure). If you want...
Converting nvarchar to bigint in sql server
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table name video table video ``` id name upload_date 1 one 1408336348 2 two 1409884215 ``` now i want to select all data also calculate if video uploaded between last 2 days then yes or no result like ``` id name upload_date new 1 one 1408336348 no 2 two 1409884215 ...
Try using case ``` SELECT v.* ,case when (from_unixtime(v.upload_date) < NOW() - INTERVAL 2 DAY) then 'yes' else 'no') end AS new FROM `video` as v ```
That's not the correct syntax for an [`IF`](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if) in MySQL. Try it like this: ``` SELECT v.*, IF(from_unixtime(v.upload_date) < NOW() - INTERVAL 2 DAY, 'yes', 'no') AS new FROM `video` as v ```
Mysql Database query with if condition
[ "", "mysql", "sql", "" ]
I have a query like so ``` Select * from tableA A LEFT JOIN mydb.tableB B ON A.pk = B.tableA_pk LEFT JOIN mydb.tableC C ON B.tableC_pk = C.pk WHERE C.PK IN ('325','305', '322') ORDER BY A.pk desc; ``` This will return a result like so with potentially multiple rows for an entry where applicable ``` 4, xxx, y...
After reading suggestions and other answers I achieved it like so..many thanks for all help.... ``` SELECT DISTINCT C.PK ,B.PK ,B.tableC_pk ,B.tableA_pk ,A.pk FROM tableC C INNER JOIN tableB B ON C.PK = B.tableC_pk INNER JOIN tableA A ON A.PK = B.tableA_pk INNER JOIN ( SELECT tableC_pk,MAX(PK) AS PK FROM tableB WHE...
You can use variable by iterating it with 1 like so. ``` Select A.*, @i:=@i+1 AS rownum from tableA A LEFT JOIN mydb.tableB B ON A.pk = B.tableA_pk LEFT JOIN mydb.tableC C ON B.tableC_pk = C.pk WHERE C.PK IN ('325') and (SELECT @i:= 0) r ORDER BY A.pk desc; ``` **Note:** I have not tested above query.
SQL Select/Join, LIMIT result to 1st entry per element in query list
[ "", "mysql", "sql", "database", "" ]
Hi i am trying to make simple database with 2 tables, first for user information, and second for their uploads, because it's project for faculty, i have some assignments... And one is to use foreign key. ``` DROP TABLE IF EXISTS `korisnici`; CREATE TABLE `korisnici` ( `UserID` INT(11) NOT NULL AUTO_INCREMENT, `us...
I think the error message is actually misleading. What I see from your code is that it is the insert into SLIKE that fails because UserID=2 does not match the UserID of the previous insert into KORISNICI.
You have child record and so since you have put the **ON DELETE RESTRICT** as well as **ON UPDATE RESTRICT** constraints(I mean as they are *default*) whatever changes you make on the parent row i.e. a row in *korisnici* table with child rows in *slike* table will be restricted by ***MySQL***. Now for deletion yo...
MySQL: Cannot delete or update a parent row: a foreign key constraint fails
[ "", "mysql", "sql", "foreign-keys", "constraints", "parent", "" ]
Since I'm new to SQL Server, I think I need a little help here... Since I've rewritten the code below many times there might be other errors as well, sorry about that. Removed the 'GO' for now. Problem: I don't know how to create a foreign key from "model" in the table `Cars` to the table `Model`. My broken code: `...
This code managed to solve the problem I think, several of you people here did contribute, thank you. ``` alter table Cars add constraint fk_colors foreign key (colorid) references colors([id]) ```
I advise against naming all your primary keys the same (`ID`) as this runs in to problems when creating foreign keys. Your table `Cars` has `model` as `nvarchar`, which is unnecessary if you are using surrogate keys. Change the data type to `int`, the name to `model_id` and add a constraint to the table: ``` ALTER TA...
Problems with foreign keys
[ "", "sql", "sql-server", "" ]
I've function that should change notation of numbers from 12345.67€ to 12345,67€ ``` select replace( to_char(round( 123456.789 ,2),'999G999G999G990D'||substr('0000000000',1,2),'nls_numeric_characters=''.,'''),'.',',' ) || ' €' from dual; ``` current result is: 123,456,79 € the result...
ALTER SESSION SET NLS\_TERRITORY='SWEDEN' for an example. Or Estonia. Numeric formats are derived from the setting of the NLS\_TERRITORY parameter, but they can be overridden by the `NLS_NUMERIC_CHARACTERS` parameter.
You should either set the NLS parameters, if they are not already correct, in the session or in the query e.g. ``` select to_char(123456.789 ,'9999990D00L' ,'nls_numeric_characters='',.'' nls_currency=''€''') from dual ```
Change number output [.] to [,] in pl/sql
[ "", "sql", "oracle", "plsql", "oracle-apex", "" ]
Hi I table in which every row have data like: ``` 0150566115,"HEALTH 401K","IC,ON","ICON HEALTH 401K",,,1,08/21/2014 ``` What i want is to remove every comma(,) that is enclosed between double quotes " ". and then slpit the rest of the string with comma(,) I dont want to do it checking every single character setting...
Try the following: ``` DECLARE @str nvarchar(max) = '0150566115,"HEALTH 401K","IC,ON","ICON HEALTH 401K",,,1,08/21/2014' SELECT SUBSTRING(@str, 1, CHARINDEX('"', @str, 1) - 1) + REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(@str, CHARINDEX('"', @str, 1), LEN(@str) - CHARINDEX('"', REVERSE(@str), 1) - CHARINDEX('"', @s...
The format of your data appears to be a delimited CSV format. This is a format frequently used by Excel, and it is unfortunate that SQL Server doesn't seem to have a simple way to read it in. When I am faced with such files, I usually do the following: * Load them into Excel * Save them in a *tab* delimited format * I...
Replace comma between quotes with space
[ "", "sql", "sql-server", "database", "t-sql", "sql-server-2012", "" ]
Trying to set up a query which returns the earliest date in a year in multiple years. Ex: ``` 06-apr-1990 07-may-1991 03-apr-1992 07-jun-1993 ``` the earliest would be `03-apr-1992` any help is appreciated (-: I'm using Oracle SQL Developer the dates are in Date format
If you are using SQL Server, try : ``` SELECT TOP(1) date FROM table ORDER BY Month(date), Day(date) ``` For MySQL this should do the trick : ``` SELECT date FROM table ORDER BY Month(date), Day(date) LIMIT 1; ``` For Oracle : ``` SELECT date FROM table ORDER BY Month(date), Day(date) WHERE ROWNUM <= 1; ```
Try the following query: `SELECT column_name,column_name FROM table_name ORDER BY column_name,column_name ASC|DESC;` source [w3school.](http://www.w3schools.com/sql/sql_orderby.asp)
Earliest Date in a year in multiple years
[ "", "sql", "oracle", "" ]
I have following table ``` +-----+--------+-----------+-----------+-------+ | id | job_id | source_id | target_id | value | +-----+--------+-----------+-----------+-------+ | 204 | 5283 | 247 | 228 | 1201 | | 349 | 4006 | 247 | 228 | 100 | | 350 | 4007 | 247 | 228 | 500 ...
if you use user defined variables you don't need to join the table to itself. just do a row by row comparrision like so ``` SELECT id, job_id, target_id, if(@a = source_id, @b - value, value) as diff, @b := value as value, @a := source_id as source_id FROM changes CROSS JOIN (SELECT @a:=0, @b:=0)t `...
I suspect that you're looking for something like this - although the COALESCE bit seems misleading to me... ``` SELECT a.*, COALESCE(b.value-a.value,a.value) diff FROM ( SELECT x.* , COUNT(*) rank FROM changes x JOIN changes y ON y.id <= x.id GROUP BY x.id ) a LEFT JOIN ( SELECT x.* , COUNT(*) rank FR...
Calculate difference between one column over multiple rows using coalesce and join
[ "", "mysql", "sql", "" ]
This is probably pretty simple and dumb to ask but Im just not getting there right now. I have a db for cocktails and want to check which cocktails I can make with the available ingredients: > Get the names of all cocktails where **every** ingredient is in stock These are my tables: ``` create table cocktails ( na...
A correlated subquery should work: ``` select cocktail_name as all_ingredients_in_stock from cocktail_ingredients ci inner join ingredients_in_stock iis on ci.ingredient_name = iis.ingredient_name group by cocktail_name having count(*) = (select count(*) from cocktail_ingredients where cocktail_na...
You can use a LEFT JOIN and a IN clause for this. Something like this: ``` SELECT name FROM cocktails WHERE Name NOT IN( SELECT DISTINCT ci.cocktail_name FROM cocktail_ingredients ci LEFT JOIN ingredients_in_stock istk ON ci.ingredient_name=istk.ingredient_name WHERE istk.ingredient_name IS NULL) ``` This query inver...
SELECT Statement for cocktail db
[ "", "sql", "" ]
I want to interrogate a result set for a particular value: ``` DECLARE @validIds; SET @validIds = (SELECT id FROM client WHERE valid = 1); IIF(@id IN @validIds, 1, 0) ``` This obviously isn't working, what's the best way to do this? If I have the following "client" table: ``` id | valid 1 | 0 2 | 1 3 | 1 ``` W...
## Test Data ``` DECLARE @validIds table (id int); INSERT INTO @validIds VALUES (1),(2),(3) DECLARE @Client table (id int); INSERT INTO @Client VALUES (1),(2),(3),(4),(5) ``` ## Query ``` SELECT c.id AS Client_ID ,CASE WHEN EXISTS (SELECT 1 FROM @validIds WHERE id = c.id) THEN 1 ELSE 0 END AS [...
Create a table variable to hold your valid ids. Then return 1 if your @id variable is in the list of valid ids - if not return 0. ``` DECLARE @validIds TABLE (id INT); INSERT INTO @validIds (id) SELECT id FROM clients WHERE VALID = 1; SELECT ISNULL((SELECT 1 from @validIds where @id = id), 0); ```
Check for value in table variable in IIF
[ "", "sql", "sql-server", "" ]
I need help with query statement to add selected records. Example of records in table **"tblA"**: ``` Name, Year, Level, Points, Item John, 2012, 1, 2, bag John, 2012, 1, 1, book John, 2013, 1, 1, pen John, 2013, 1, 1, pencil John, 2014, 2, 3, hat John, 2014, 2, 1, ...
To get all names and their points (following your logic), you could try: ``` SELECT tblA.Name, SUM(points) AS totalPoints FROM tblA JOIN ( SELECT MAX(year) year, Name, Level FROM tblA GROUP BY Name, Level) tblA2 ON tblA.Name = tblA2.Name AND tblA.year = tblA2.year AND tblA.Level = tblA2.Level GROUP BY Name ``` If you...
Maybe also try it like this: ``` select tblA.name, tblA.year, sum(tblA.points) from tblA inner join ( select name, level, max(year) as yr from tblA group by name, level ) as yearTbl on tblA.name=yearTbl.name and tblA.year=yearTbl.yr and tblA.level=yearTbl.level group by tblA.name, tblA.year ```
MYSQL: sum of latest record
[ "", "mysql", "sql", "" ]
SQL Fiddle <http://sqlfiddle.com/#!2/1c5fc3/1> I am trying to create simple messaging system, but I am having trouble with the desired results from the SQL queries. Here are the tables I have; I am trying to get INBOX data.. INBOX Definiton for this problem: This should be threaded display in inbox, ie. google mail...
Updated solution after taking into account explanations for message status: ``` SELECT DISTINCT t.*, tm.* , ms.* FROM thread t -- tm should be last message INNER JOIN thread_messages tm ON t.id_thread = tm.id_thread INNER JOIN message_status ms ON (ms.id_thread_messages = tm.id_thread_messages)AND ...
i think this is the solution that you are looking for ``` SELECT * FROM thread JOIN thread_users ON thread.id_thread = thread_users.id_thread JOIN thread_messages ON thread.id_thread = thread_messages.id_thread JOIN message_status ON thread_messages.id_thread_messages = message_status.id_thread_messages WHERE thread_...
Get the last message for each thread
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I have a requirement to create a Sales report and I have a sql query: ``` SELECT --top 1 t.branch_no as TBranchNo, t.workstation_no as TWorkstation, t.tender_ref_no as TSaleRefNo, t.tender_line_no as TLineNo, t.tende...
Appreciate your assistance with my query. After playing around, I have found a solution that works just as I want. It is as below: I did a Group by as hinted by @Yogesh86 on a few fields. ``` SELECT MAX(t.branch_no) as TBranchNo, Max(t.workstation_no) as TWorkstatio...
Not exactly sure on what data you have, but you might want to try ``` GROUP BY TlineNo, TCode ... ``` But you have to keep a look on not to group by something that would result in duplicate contribution values.
Assistance with SQL Query (aggregating)
[ "", "sql", "sql-server", "sql-server-2012", "" ]
i would like to ask you if there is a way to get the value of maxlength of column in ms sql server. For example in the table A we have: ``` id | value ----+-------- 1 | 0123 2 | 00034567 3 | 547 ``` The desired result for this data set is 00034567. Wherever i have searched for this problem i get the answer ...
``` SELECT TOP 1 t.value FROM table AS t ORDER BY LEN(t.value) DESC ```
Sort by length and take the first row: ``` select top 1 value from mytable order by len(value) desc ``` If you want ties: ``` select value from mytable where len(value) = (select max(len(value)) from mytable) ``` Or more efficient but SQL Server specific: ``` select value from ( select value, rank() over (orde...
How to get the value of max length in sql server
[ "", "sql", "sql-server", "max", "maxlength", "" ]
Hiii look at this request and tell me why always Oracle give me this error ``` ORA-00932: inconsistent datatypes: expected DATE got NUMBER 00932. 00000 - "inconsistent datatypes: expected %s got %s" ``` note 1 : that when I remove `TRUNK()` it's work but I went to put it on the request note 2 : I use this date for...
I supsect the problem is with your column `DATEORDERED` which is `NUMBER` probably An example here. ``` SQL> select * from dual where trunc(to_DATE('04-SEP-2014','DD-MON-YYYY')) > 100; select * from dual where trunc(to_DATE('04-SEP-2014','DD-MON-YYYY')) > 100 ...
There is no reason to use `trunc()` on a constant like that. Hey, just use the `date` keyword and specify the dates in ISO standard format: ``` WHERE C_Order.ad_org_id = 1401007 AND C_order.DOCSTATUS = 'CO' AND (DATE '2014-07-01' IS NULL OR C_order.DATEORDERED >= DATE '2014-07-01') AND (DATE '201...
trunc(date) always give an error
[ "", "sql", "oracle", "date", "" ]
I cant seem to find a solution for Searching a group\_concatenated value, I have 3 table that are connected with id's * 1st table have the same value with 2nd table, but no same value with 3rd, * 2nd table have the same value with 1st and 3rd table, I want to get the value inside 3rd table, concat the values in acco...
A potential answer is to filter the Users\_table in a subquery. There are a number of different forms of this option, and hard to tell from your data which is required. The one I have below simply returns the users that match the search criteria. ``` SELECT a.problem_encountered, GROUP_CONCAT(DISTINCT innerc.full_name...
You can "search" the return from the GROUP\_CONCAT() expression in the `HAVING` clause. As a more efficient alternative, I suspect you could use an EXISTS predicate with a subquery. I suspect part of the problem is that your query is referencing the same bind placeholder more than one time. (In previous releases of PD...
mysql JOIN Inside a JOIN and search a group_concatenated values
[ "", "mysql", "sql", "pdo", "" ]
I have a mysql table with a column (code) that contains 6 character strings (varchar(6)). An example record for that column would be: ``` ID code 1 ADHNQS 2 BDHLQS 3 AEGMQS ``` What I need to do is compare 1 code record at a time to the rest and retrieve "related codes". A related code will qua...
If you just have the id of your reference row (here: 1): ``` SELECT b.ID, b.code, (if(substring(b.code,1,1)=substr(a.code,1,1),1,0) + if(substring(b.code,2,1)=substr(a.code,2,1),1,0) + if(substring(b.code,3,1)=substr(a.code,3,1),1,0) + if(substring(b.code,4,1)=substr(a.code,4,1),1,0) + if(substring(b.code,5,1)=substr(...
In the example "match", the characters that match are in the same positions in both strings. It's not clear if this is the actual specification, or if that's just an anomaly in the example. Also, we note that in the example data, the list of characters is distinct, there aren't two of the same character in any string. ...
MySQL get substring match count in each column record
[ "", "mysql", "sql", "string", "substring", "match", "" ]
I don't understand how to link two tables together. This is an example: ``` CREATE TABLE IF NOT EXISTS itemStatus ( id int(11) AUTO_INCREMENT PRIMARY KEY, name varchar(64) NOT NULL UNIQUE KEY ); CREATE TABLE IF NOT EXISTS itemData ( id int(11) AUTO_INCREMENT PRIMARY KEY, title varchar(64) NOT NULL, status_i...
``` A FOREIGN KEY in one table points to a PRIMARY KEY in another table. ``` Take a look at: <http://www.w3schools.com/sql/sql_foreignkey.asp> So it should be: ``` CREATE TABLE IF NOT EXISTS itemStatus ( id int(11) AUTO_INCREMENT PRIMARY KEY, name varchar(64) NOT NULL UNIQUE KEY ); CREATE TABLE IF NOT EXISTS it...
Looks like you're very close. Try this instead: ``` CONSTRAINT `fk_id` FOREIGN KEY (`status_id`) REFERENCES `itemStatus` (`id`) ```
SQL - CONSTRAINT to link two tables
[ "", "mysql", "sql", "" ]
I am concerned about race conditions in my database backed application. My application allows users to reserve a spot in a class. If all the spots are taken, then they are placed on a wait list. In greatly simplified pseudo code, I'm doing something like: ``` 1 spots = SELECT total_spots FROM classes WHERE class_id =...
SQLite's transactions [are fully atomic](http://www.sqlite.org/transactional.html). If you wrap the entire thing in a transaction, other connections to the same database cannot make any changes at the same time.
You can also select within your insert: ``` insert into registrations (user_id, class_id, on_waitlist) values ( 500, 200, (SELECT total_spots FROM classes WHERE class_id = 200) < (SELECT COUNT(*) FROM registrations WHERE class_id = 200) ); ```
Avoide race conditions in SQLite
[ "", "sql", "database", "sqlite", "race-condition", "select-for-update", "" ]
I have a table with integer ID column. I would like to get the minimum unused value for this column. The query should find the first hole in table IDs and get the minimum value inside it. I'll try to explain it with some examples. **Example 1: no-holes table** In this case, I have a table without holes and query shou...
``` SELECT min(unused) AS unused FROM ( SELECT MIN(t1.id)+1 as unused FROM yourTable AS t1 WHERE NOT EXISTS (SELECT * FROM yourTable AS t2 WHERE t2.id = t1.id+1) UNION -- Special case for missing the first row SELECT 1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM yourTable WHERE id = 1) ) A...
A slightly different way to do it using a join rather than EXISTS:- ``` SELECT MIN(t1.id) FROM ( SELECT 1 AS id UNION ALL SELECT id + 1 FROM yourTable ) t1 LEFT OUTER JOIN yourTable t2 ON t1.id = t2.id WHERE t2.id IS NULL; ``` Down side of any solution using a sub query is that they are not likely to...
Get minimum unused value in MySQL column
[ "", "mysql", "sql", "minimum", "" ]
I want to create a stored procedure that's flexible in handling an update on multiple columns for a table, but where all or some of the values may or may not be provided. Something like this for instance: ``` UPDATE some_table SET IF(I_COLUMN_1 is not NULL) THEN COLUMN_1 = I_COLUMN_1 END IF; IF(I_COLUMN_2 is not...
Here is a proposition of query that can do the job: ``` UPDATE some_table SET COLUMN_1 = NVL(I_COLUMN_1, COLUMN_1) ,COLUMN_2 = NVL(I_COLUMN_2, COLUMN_2) WHERE SOME_KEY = I_SOME_KEY ``` I'm not very familiar with Oracle but in T-SQL i would use `ISNULL()` function to do the job and the equivalent in Oracle is the `...
My first thought would be to manipulate the variables in PL/SQL before you execute the UPDATE statement. This is pseudo-code, but something like this: ``` I_COLUMN_1 [Datatype] := NVL2([Value of Incoming Parameter], [Value for Update if Not Null], NULL); I_COLUMN_2 [Datatype] := NVL2([Value of Incoming Parameter], [Va...
Oracle Pl SQL, conditional in UPDATE statement
[ "", "sql", "oracle", "plsql", "sql-update", "conditional-statements", "" ]
I'm using Firebird 2.1. There is a table: `IDs, Labels` There can be multiple labels for the same ID: ``` 10 Peach 10 Pear 10 Apple 11 Apple 12 Pear 13 Peach 13 Apple ``` Let's say I have a set of labels, ie.: (Apple, Pear, Peach). How can I write a single select to return all IDs that have all labels associated i...
As asked, I'm posting my simpler version of piclrow's answer. I have tested this on my Firebird, which is version 2.5, but the OP (Steve) has tested it on 2.1 and it works as well. ``` SELECT id FROM table WHERE label IN ('Apple', 'Pear', 'Peach') GROUP BY id HAVING COUNT(DISTINCT label)=3 ``` This solution has the s...
It's easiest to split the string in code and then query ``` SQL> select ID CON> from (select ID, count(DISTINCT LABEL) as N_LABELS CON> from T CON> where LABEL in ('Apple', 'Pear', 'Peach') CON> group by 1) D CON> where D.N_LABELS >= 3; -- We know a priori we have 3 LABELs ID...
Firebird how to select ids that match all items in a set
[ "", "sql", "firebird", "firebird2.1", "" ]
I am not sure how to fix this: ``` dyn-72-33-214-45:python mona$ sudo /usr/local/mysql/bin/mysqld stop 2014-09-06 09:49:04 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2014-09-06 09:49:04 22992 [Warning...
I'm using OS X (Yosemite) and this error happened to me when I upgraded from Mavericks to Yosemite. It was solved by using this command ``` sudo /usr/local/mysql/support-files/mysql.server start ```
you might try this if you logged in with root: ``` mysqld --user=root ```
Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root
[ "", "mysql", "sql", "my.cnf", "" ]
Though I have relatively good exposer in SQL Server, but I am still a newbie in SSAS. We are to create set of reports in SSRS and have the Data source as SSAS CUBE. Some of the reports involves data from atleast 3 or 4 tables and also would involve Grouping and all possible things from SQL Environment (like finding t...
OLAP cubes are great at performing aggregations of data, effectively grouping over the majority of columns all at once. You should not strive to implement all the grouping at the named query or relational views level as this will prevent you from being able to drill down through the data in the cube and will result in ...
I would look at BISM Tabular if your model is not complicated. It compresses and stores data in memory. As for data processing I would suggest to keep all calculations and grouping in database layer (create views).
SSAS Environment or CUBE creation methodology
[ "", "sql", "sql-server", "reporting-services", "ssas", "olap-cube", "" ]
I have the following table: ``` ID myDate myTime Value 1 2014-06-01 00:00:00 100 2 2014-06-01 01:00:00 125 3 2014-06-01 02:00:00 132 4 2014-06-01 03:00:00 139 5 2014-06-01 04:00:00 145 6 2014-06-01 05:00:00 148 FF. 24 2014-06-01 23:00:00 205 2...
You can use simple IIF function of SQL Server: <http://msdn.microsoft.com/en-au/library/hh213574.aspx> So the query will be like the below ``` SELECT ID, myDate, IIF(myTime='00:00:00', '24:00:00', myTime) as myTime FROM MyTable WHERE myDate = '2014-06-01' ``` *Please mark as answer if it answers your question* ...
You would do this with an `or`: ``` SELECT * FROM MyTable WHERE myDate = '2014-06-01' OR (myDate = DATEADD(dd, 1, '2014-06-01') AND myTime = '00:00:00'); ``` EDIT: ``` SELECT date('2014-06-01') as mydate, (case when mydate <> date('2014-06-01') then '24:00:00' else mytime end) as mytime, REST OF ...
Change Value on SQL View
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Is there a way to work out if a call overlaps another call already in progress. For example I have a call that comes in at `10:00` and ends at `10:05`. Second call comes in at `10:02` and ends at `10:06` so is overlapping the first calls, how could I show this in a sql query? I have a few thousand calls to compare. ...
Here is non-inclusive query: ``` SELECT * FROM myCalls t1 INNER JOIN myCalls t2 on t2.CallID != t1.CallID AND t1.TimeAns < t2.TimeFin AND t1.TimeFin > t2.TimeAns ``` This query will return 2 rows for each overlap. if you want to have just one row per overlap this will do it: ``` SELECT * FROM myCalls t1 IN...
Two calls overlap when start or end of call 1 is between start and end of call 2. (No matter, which of the two calls you call "call 1" and which "call 2".) ``` WHERE ( call1.start BETWEEN call2.start AND call2.end OR call1.end BETWEEN call2.start AND call2.end ) ``` EDIT: And make your mind up, if you consider...
Overlapping call durations
[ "", "sql", "sql-server", "overlap", "" ]
how to get the exact "year" from oracle data if the given data is in this format? ``` 02-FEB-84 ``` I want to get the year, but when I do something like this ``` case when dob is not null then to_date(dob,'YYYY') when dob is null then '""' end as yearofbirth ``` I am getting the value of ``` 2084 ``` wh...
Assuming `DOB` is `varchar2()` having date in format `DD-MON-YY`, You might be looking for ``` TO_CHAR(TO_DATE(DOB,'DD-MON-RR'),'YYYY') ``` Conversion using `YY` format! Current century is 20\*\* so, 84 -> 2084 ``` SQL> SELECT TO_CHAR(TO_DATE('02-FEB-84','DD-MON-YY'),'YYYY') FROM DUAL; TO_C ---- 2084 ``` Convers...
One more condition to your case statement should do it. ``` case when to_date(dob) > sysdate then to_date(dob,'YYYY') - 100 when dob is not null then to_date(dob,'YYYY') when dob is null then '""' end as yearofbirth ```
how to get the exact year from the given date in oracle if it has a minimal format to base from?
[ "", "sql", "oracle", "" ]
I have a table "tblSalesOrder" in Microsoft T-SQL with some sample records: ``` SalesOrderID OrderDate ItemID Quantity PromotionCode ==================================================================== 1 2014-09-01 100 5 NULL 2 2014-09-01 120 10 A...
You can `join` the a date parameter in an empty `select` and `coalesce` the values: ``` select coalesce(t.SalesOrderID, 0) SalesOrderID , coalesce(t.OrderDate, d.OrderDate) OrderDate , coalesce(t.ItemID, 0) ItemID , coalesce(t.Quantity, 0) Quantity , coalesce(t.PromotionCode, 0) PromotionCode from ...
master..spt\_values is a table in all microsoft sql databases containing 2506 rows, by cross joining, it will have 2506\*2506 rows to calculate dates between from and to. Other tables can be used as well, this is just a table used to create the dates. A calendar table would be even easier to use. The EXCEPT will remov...
T-SQL NULL-Friendly Query
[ "", "sql", "sql-server", "null", "" ]
I have the following stored procedure: ``` ALTER proc [dbo].[insertperoll] @name nvarchar(50) , @snum int , @gnum int as DECLARE @value nvarchar(10) SET @value = 's'+CONVERT(nvarchar(50),@snum) DECLARE @sqlText nvarchar(1000); DECLARE @sqlText2 nvarchar(1000); DECLARE @sqlText3 nvarchar(1000); declare @g nvarcha...
You could do this using `sp_executesql` instead of `exec()` since this will allow you to use parameters, you can use an output parameter to get the value from the query: ``` DECLARE @SQL NVARCHAR(MAX) = N'SELECT @val = ' + CONVERT(NVARCHAR(10),@snum) + N' FROM dbo.GrideBtable WHERE Gnumber...
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like .. ``` ALTER PROC dbo.[insertperoll] @name nvarchar(50) , @snum int , @gnum int AS insert employ (name, Snumber, Gnumber, Salary) select @name , @sum , @gnum , case when @snum = 1 then s1...
Can I use variable in condition statement as value with where condition that test that value
[ "", "sql", "sql-server-2008", "variables", "stored-procedures", "" ]
I have three tables I am trying to build a query against in Eloquent to get only the rows from two tables that are absent from a third table. One is the table `histories` which references the other two tables `schedules` and `templates`. If there is a template schedule history, I don't want to get that schedule. Norm...
``` select schedules . *, schedules.id as 'schedule_id', histories . *, histories.id as 'history_id' from schedules left join histories ON schedules.id = histories.schedule_id and schedules.template_id = histories.template_id where histories.id IS NOT NULL ; ``` This lists schedule...
Your query should look like this: However your query is not returning any results because each schedule/template has a history record. ``` select histories . *, histories.id as 'history_id', schedules . *, schedules.id as 'schedule_id' from schedules left join histories ON schedules.id = histo...
Selecting rows absent from one table against two other tables?
[ "", "mysql", "sql", "laravel-4", "eloquent", "" ]
I have two tables that store data for my wife application. I don't have a problem to load the profile from customer table if there is a record from services table. But mysql code doesn't work if query customer record that don't have a record in services table. here is mysql code: ``` SELECT * FROM customer, service...
You need a left outer join: ``` SELECT * FROM customer c left outer join services s ON c.cust_id = s.customer_id and s.delete = '0' WHERE c.slug LIKE 'john-doe'; ``` A simple rule: Never use commas in the `from` clause. They are not needed. You should always use explicit `join` syntax, which is more express...
Use a `left join`. Remember that columns from the `left join` table are `null` if no match was found: ``` select * from customer c left join services s on s.customer_id = c.cust_id and s.deleted = '0' where c.slug LIKE 'john-doe' ```
mysql doesn't show result if the query option has empty record in one of the table
[ "", "mysql", "sql", "select", "" ]
I am learning SQL. I have these records in my table: ``` STUDENT_NAME STATUS CLASS_ID ORDERING ---------------------------------------------- Adam 'FR' 10 1 Conan 'SE' 3 5 Chris 'SE' 4 8 Louis 'JR' ...
Try this. I wrote this for MySQL, it may work for SQL Server also. It will group NULL CLASS\_IDS together (if there are any). I don't can't think of another way to do it. It gives the results you are looking for. ``` SELECT stu.* FROM STUDENTS stu ORDER BY (SELECT MIN(S.ORDERING) FROM STUDENTS S WHERE S.STATUS = st...
You can simply do ``` SELECT * FROM students ORDER BY STATUS, ORDERING, CLASS_ID ``` Here's a [fiddle](http://sqlfiddle.com/#!2/cf792/11).
Order By clause on multiple fields with group
[ "", "sql", "sql-server", "sql-order-by", "" ]
I have following 3 tables ``` ITEM table =========== id desc =========== IN table ======================= id id_item number ======================= OUT table ========================= id id_item number ========================= ``` and this data on item: 1 - GECO in: 1 - 1 - 40 2 - 1 - 2 out: 1 ...
``` SELECT item.id, A.Sum_IN, B.Sum_OUT, (A.Sum_IN - B.Sum_OUT) AS Dif from item left outer join( select id_item as id, SUM(number) AS Sum_IN FROM in GROUP BY id_item) as A ON item.id = A.id left outer join( select id_item as id, SUM(number) AS Sum_OUT FROM out GROUP BY id_item) as B ON item.id = B.id ```
Try with INNER JOIN like ``` SELECT `item`.`id`, SUM(`in`.`number`) AS Sum_IN, SUM(`out`.`number`) AS Sum_OUT FROM item INNER JOIN `IN` ON item.id = `IN`.id_item INNER JOIN `OUT` ON item.id = `OUT`.id_item GROUP BY item.id ```
SQL query of Sum from 3 tables
[ "", "mysql", "sql", "sum", "" ]
I'm trying to concatenate lastName(3 letters) + firstName(2 letters) to create a new username. When I used this script, it created new records for the concatenation results. ``` USE [database] INSERT INTO table (username) SELECT SUBSTRING(lastName, 1, 3) + SUBSTRING(firstName, 1, 2) FROM [database].[dbo].table ``` Co...
You want an update instead of an insert. The following will update all records with the new username. If you want a more specific update for just a single record, you will need a WHERE clause to identify the particular rows. ``` UPDATE table SET username = SubString(lastName, 1, 3) + SubString(firstName, 1, 2); ```
I'm not sure whether I get your question right, but shouldn't the following work? ``` UPDATE table SET username = SUBSTRING(lastName, 1, 3) + SUBSTRING(firstName, 1, 2) ``` This updates the `username` of every record in the table.
SQL Server query results as INSERT
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I wasted all the day on one query without success , **SOS** I need a help :) with a given **@CustomerId** , I need to query all the Products that linked to customer seller can sell but **not** sold to him before , the Commissions table is indication of what products seller can sell ![enter image description here](http...
``` SELECT sellableProduct FROM (SELECT Comissions.ProductId AS sellableProduct, Sellers.SellerId AS sellableSeller FROM Comissions INNER JOIN Sellers ON Comissions.SellerId=Sellers.SellerId INNER JOIN Customers ON Sellers.SellerId=Customers.SellerId WHERE Customers.CustomerId = @customerid) AS tblSellable LEFT JOIN (S...
Basically, you're looking for products that have a record in `commissions`, but not in `sales`. Using `:id` to denote the specific ID: ``` SELECT * FROM products WHERE productid IN (SELECT productid FROM commissions WHERE sellerid = :id) AND productid NOT IN (SELE...
SQL nested SELECT with JOIN
[ "", "sql", "sql-server", "" ]
I am running a query in order to get student count by cities. A table (`Address`) holds records of students' address information. ``` AddressID, StudentID, Address, City, Country, Telephone ``` are some fields of Address table. There is one point which I must tell about: City column values consists of 7 chars. Each...
You can just group by the calculated value: ``` select count(StudentID) as stuCnt, right('00' + isnull(left(City, len(City) - 5), ''), 2) as cityCode from address group by right('00' + isnull(left(City, len(City) - 5), ''), 2) order by right('00' + isnull(left(City, len(City) - 5), ''), 2) ``` ...
You can use the first query in an Inner `SELECT`, and group those results with a `SUM`: ``` SELECT SUM(stuCnt) As stuCnt, cityCode FROM ( SELECT COUNT(StudentID) AS stuCnt, RIGHT('00' + ISNULL(LEFT(City, LEN(City) - 5), ''), 2) AS cityCode FROM Address GROUP BY City ) X GROUP BY city...
How group again a grouped query in SQL
[ "", "sql", "sql-server", "" ]
I have a changelog with insert / update / delete operations: ``` change_id | object_id | operation ----------+-----------+---------- 1 | 1 | insert 2 | 2 | insert 3 | 1 | delete 4 | 1 | insert 5 | 3 | insert 6 | 2 ...
[**SQL Fiddle**](http://sqlfiddle.com/#!6/68745/1/0): ``` SELECT c.change_id, c.object_id, c.operation FROM ( SELECT MAX(change_id) AS CID FROM changelog GROUP BY object_id ) s INNER JOIN changelog c on c.change_id = s.CID ```
``` ;WITH MyCTE AS ( SELECT change_id, object_id, operation, ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY change_id DESC) AS rn FROM ChangeLog ) SELECT change_id, object_id, operation FROM MyCTE WHERE rn = 1 ``` **[SQL Fiddle Demo](http://sqlfiddle.com/...
MS SQL - Select only one row for an ID
[ "", "sql", "sql-server", "greatest-n-per-group", "" ]
I have a UserTypes table like this: ``` UserTypeID | ParentUserTypeID | Name 1 NULL Person 2 NULL Company 3 2 IT 4 3 Accounting Software ``` What I want to do is get all the `ParentUserTypeID` when a UserTypeID i...
I don't know how much you are allowed / desiring to change the structure, but you probably need to define the UserTypeID you are looking up in the CTE root, e.g.: ``` ;WITH CTE AS ( SELECT c1.ParentUserTypeID, c1.UserTypeID, c1.Name FROM dbo.UserTypes c1 WHERE UserTypeID = 4 UNION ALL SELECT ...
[SQL Fiddle](http://sqlfiddle.com/#!6/206af/6) **MS SQL Server 2012 Schema Setup**: ``` CREATE TABLE UserTypes ( UserTypeId INT PRIMARY KEY, ParentUserTypeId INT NULL, Name VARCHAR(50) ) INSERT INTO UserTypes VALUES (1,NULL, 'Person'), (2, NULL, 'Company'), (3,2, 'IT'), (4,3,'Accounting Softw...
Recursive CTE with a Where clause not returning all results
[ "", "sql", "sql-server", "recursion", "" ]
I have simple table which puzzles me: ``` CREATE TABLE [dbo].[T3] ( [id] [int] IDENTITY(1,1) NOT NULL, [S_Id] [int] NULL, [P_Id] [int] NULL, [level] [int] NULL, [Path] [nvarchar](255) NULL ) ON [PRIMARY] ``` In the table is data ``` id S_Id P_Id level Path ------------------------------------...
If you only want the max path record... Correct me if I'm wrong. ``` ;WITH tmp AS (select TOP 1 id from #TaskTask3 ORDER BY LEN(path) DESC) select t.* from #TaskTask3 t inner join tmp on tmp.id = t.id ``` --- ## Updates ``` ;WITH tmp AS (select id, row_number() over (partition by S_Id, P_Id order by len(path) DESC...
I tried to keep it simple....There are other methods (mentioned already) but I think you need to start slow... :) ``` declare @maxLen int select @maxLen = max(len(path)) from t3 select * from t3 where len (path) = @maxLen ```
Simple max() function and inner join T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
In SQL server 2008r2, i want to display only lines where some columns are not equal to '0' For example: I want to display only lines where columns 2 and 3 are <> '0' > line 1 : val1 = 2, val2 = 2, val3 = 0 > > line 2 : val1 = 1, val2 = 0, val3 = 0 > > line 3 : val1 = 0, val2 = 0, val3 = 5 > > line 4 : val1 = 10, val2...
## Count the number of values not equal to 0 by `sign(abs(x))`. ``` SELECT t.* FROM dbo.TableName t WHERE sign(abs(val1))+sign(abs(val2))+sign(abs(val3)) >1 ``` It implements the requirement of : > display only lines where some columns are not equal to '0' If "some" means val2 and val3, it could be: ``` SELECT t....
> i want to display only lines where columns 2 and 3 are <> '0' I don't see the particular problem ``` SELECT t.* FROM dbo.TableName t WHERE t.val2 <> 0 AND t.val3 <> 0 ```
SQL Server Display only lines with all values not equal to 0
[ "", "sql", "sql-server-2008-r2", "filtering", "" ]
I have a problem getting my SEQUENCE. I have created a sequence as administrator and have grant select and alter privileges to the other user. ``` CREATE SEQUENCE "OWNER"."TOT_SEQ" MINVALUE 1000 MAXVALUE 1000000000 INCREMENT BY 1 START WITH 1000 CACHE 20 NOORDER NOCYCLE ; grant select,ALTER on TOT_SEQ to user; com...
You will either have to fully qualify your sequence via: ``` SELECT <owner>.<sequence name>.nextval FROM dual; ``` Or create a public synonym for it: ``` CREATE PUBLIC SYNONYM TOT_SEQ for OWNER.TOT_SEQ; SELECT TOT_SEQ.nexval FROM DUAL; ```
Make sure that you create the sequence in uppercase, even if you use lower case in trigger / select statement.
sequence doesn't exist ORA-02289
[ "", "sql", "oracle", "" ]
I need to query the same column for different values depending on another relational value. Table is set up like this : athleteID, meetName, eventName, score Events are all the same but there are Different Meets and my query needs to return: aid, event, score from meetName = 'whatever1', score from meetname = 'whatev...
I would like to add that Natural Inner Join is what should've been done here for basic(non-commercial) sql. Syntax would've been: `select * from (subquery1) NIJ (subquery2)` The subqueries syntax: ``` select athleteID, score as ValScore from performances, NIJ athletes where meet =‘Valentin’ and event=‘beam’ ``` and...
Does not stipulate RDMS, my answer is with SQL Server: If you wanted to use a subquery you need to reference the atherleteID and eventName, also if there were more than one result (not clear from your question but I assume atheletes compete at multiple meets) you would need to aggregate. There may be a better way but...
SQL query same column twice
[ "", "sql", "" ]
I need to assign the output of split to the variable, how can do this, i tried this ``` DECLARE @StartMonth nvarchar(5) = select top 1 Value from dbo.split('jun - may', '-') ``` Step 1: ``` select top 1 Value from dbo.split('jun - may', '-') ``` Output is `jun` Step 2: I need to assign it to the variable `@StartM...
Try this ``` DECLARE @StartMonth nvarchar(5) select top 1 @StartMonth = Value from dbo.split('jun - may', '-') ```
Please try the following: ``` DECLARE @StartMonth nvarchar(5) select top 1 @StartMonth = Value from dbo.split('jun - may', '-') ```
how to get the cell value from table and assign to the variable in sql
[ "", "sql", "sql-server", "" ]
In T-SQL I am after a constraint that will stop duplicate records being inserted for the flag. For each [FK\_Something] the flag `[MyFlag]` can only be set once to value 1 but can be set to 0 many times. Is this possible and is so how without using triggers? I am using SQL Server 2008 R2. ``` set nocount on IF EX...
Thanks to Mack for his suggestion of using a function. I had to change the function logic in the function as it did not allow for the first record to be inserted. I have posted the complete solution for neatness below. TomTom's solution of the index does not involve a function so a lot of companies would accept it more...
Indices. > For each [FK\_Something] the flag [MyFlag] can only be set once to > value 1 but can be set to 0 many times. That is 1 simle index: * FK\_Something and MyFlag 1 - unique The trick here is to not apply the unique index on ALL rows, which is why you add a filter. <http://msdn.microsoft.com/en-us/library/c...
Unique grouped constraint on SQL Server table
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have the following sql: ``` select `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` from `items` left join `categories` as `c` on `c`.`id` = `items`.`category_id` left join `item_tags` as `it` on `it`.`item_id...
You may try to use **DISTINCT** if you want to avoid duplicate data. Something like this: ``` select DISTINCT `items`.`id`, `items`.`item_url`, `items`.`title`, `items`.`description`, `items`.`item_image_name`, `items`.`downloads`, `items`.`likes`, `items`.`date` from `items` left join `categories` as `c` on `c`.`id`...
You need to use DISTINCT keyword in your query: <http://www.mysqltutorial.org/mysql-distinct.aspx>
Sql returns row multiple times
[ "", "mysql", "sql", "database", "" ]
I have a query as below in my Stored Procedure: I set the @SUBCONDITION FROM MY CODE BEHIND. ``` declare @SUBCONDITION VARCHAR(100)= NULL if(@SUBCONDITION='DEPT') BEGIN Select * from table1 where IDDEPT=1 END ELSE IF (@SUBCONTION='GRADE') BEGIN SELECT * FROM TABLE1 WHERE IDGRADE=1 END ELSE IF(@SUBCONDITION='SECTION'...
Try this: ``` SELECT * FROM table1 WHERE 1 = (CASE @SUBCONDITION WHEN 'DEPT' THEN IDDEPT WHEN 'GRADE' THEN IDGRADE WHEN 'SECTION' THEN IDSECTION ELSE 0 END); ```
Yes, you can do this in one query. It would look like this: ``` Select * from table1 where (@SUBCONDITION = 'DEPT' and IDDEPT = 1) or (@SUBCONTION = 'GRADE') and IDGRADE = 1) or (@SUBCONDITION = 'SECTION' and IDSECTION = 1) ```
conditional where clause in sql 2012
[ "", "sql", "sql-server", "select", "conditional-statements", "where-clause", "" ]
I am trying to return the number of people registered in a particular month, but would like also to return zeros in months that are not in the database. The following query returns number of people registered in months in the database: ``` select extract(year from "DATECREATED") as YEAR, extract(month from ...
Unfortunately, to do this, you need a second table that just contains the month number per row. Assuming you create a table called `MONTHS` with a single column, `MONTH_NUMBER`, you could use this query to create the output you're looking for - it will count the number of rows per month for the year you specify and sh...
I tested this on mysql so you might require some tinkering for oracle. First create a table with the months of the year... ``` create table months(month int); insert into months values(1); insert into months values(2); insert into months values(3); insert into months values(4); insert into months values(5); insert in...
How to return zeros in months not in the database
[ "", "sql", "oracle", "date-arithmetic", "" ]
I have these problem I need to match the sum a columns to see if they match with the Final Total of the Invoice by Invoice Number ( I am working in a query to do it) Example ``` Invoice No Line _no Total Line Invoice total Field I will create ---------------------------------------------------------------...
Is this what you're looking for? I think subquery is what you're asking about, but i'm guessing to get an end result similar to the entire thing. ``` select t."Invoice No", t."Line no_", t."Invoice total", calcTotals.lineNum as calcSum, case when t."Invoice total" = calcTotals.lineNum then 'matched' else 'not...
You want a cumulative sum. In SQL Server 2012+, just do: ``` select e.*, (case when InvoiceTotal = sum(InvoiceTotal) over (partition by invoice_no order by line_no) then 'Match' end) from example e; ``` In earlier versions of SQL Server, I would be inclined to do it with a correlated subqu...
Sql Query Compare and Sum
[ "", "sql", "sql-server", "sql-scripts", "" ]
For sample data as below, ``` Col1 Col2 1 A 1 B 1 C 2 A 2 B ``` the output I am looking for is ``` COL1 COL2 1 A B C 2 A B ``` This can be done using LISTAGG on Oracle or recursive queries on other DBs but Redshift doesnt support both. How do I achieve this on Redshift
They just added `LISTAGG()` to Redshift (2015-07-31). <http://docs.aws.amazon.com/redshift/latest/dg/r_LISTAGG.html>
Here is a solution from another similar question - ``` SELECT col1, LISTAGG(col2,', ') WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1) AS EMPLOYEE FROM YOUR_TABLE ORDER BY col1 ``` [This question.](https://stackoverflow.com/questions/24502108/how-to-group-by-and-concatenate-fields-in-redshift) > Redshift ha...
How to write a listagg on Redshift?
[ "", "sql", "amazon-redshift", "" ]
I have a Category table: ``` CategoryID Description ------------------------- 1 Red category 2 Green category 3 Blue category ``` And an Item table: ``` ItemID CategoryID Status ------------------------------ 1 1 "New" 2 1 "New" 3 ...
``` SELECT * FROM YourTable A WHERE EXISTS(SELECT 1 FROM YourTable WHERE CategoryId = A.CategoryId AND [Status] <> A.[Status]) ```
@Koveras, this will give you all the categories with multiple statuses. ``` select categoryid from ( select distinct categoryid, status from item) t group by categoryid having count(*) > 1 ``` Your currently accepted solution will work but will be less efficient. Here is another solution. [See Fiddle Here](http:...
SQL select categories where items have different values
[ "", "sql", "sql-server", "" ]
I'm trying to make a search function in my website. When i try it out i get very crazy results back. this query works fine: ``` SELECT * FROM (`products`) JOIN `products_field` ON `products`.`id` = `products_field`.`prod_id` WHERE menu_id=569 OR menu_id=952 AND (products.title LIKE '%mcgregor%' OR products_field.va...
Written this way ``` WHERE menu_id=952 OR menu_id=569 AND ... ``` To mysql is considered a match(true) when menu\_id = 952 and what is on the right side of the -OR- is not even evaluated, because you are saying that is this OR the other(the rest of the where declaration) you can wrap this OR like so: ``` WHERE (menu...
Try adding parentheses around the menu section. ``` SELECT * FROM (`products`) JOIN `products_field` ON `products`.`id` = `products_field`.`prod_id` WHERE (menu_id=952 OR menu_id=569) AND (products.title LIKE '%mcgregor%' OR products_field.value LIKE '%mcgregor%') GROUP BY `prod_id` ```
Crazy mysql behavior getting different results with almost same query
[ "", "mysql", "sql", "search", "" ]
I want to display `dishname` and `dishprice` with `DISTINCT` value of 2nd highest `dishprice`. What is the problem with the following query? ``` SELECT dishName, DISTINCT(dishPrice) FROM `tblDish` ORDER BY dishPrice LIMIT 1,1 ```
In case there are more then one record for same price then need to group them bye price and group concat all the records ``` SELECT GROUP_CONCAT(dishName), dishPrice FROM `tblDish` GROUP BY dishPrice ORDER BY dishPrice DESC LIMIT 1,1 ```
Do it like this ``` SELECT DISTINCT(dishPrice), dishName FROM `tblDish` GROUP BY `dishPrice` ORDER BY `dishPrice` LIMIT 1,1 ``` You should always mention Distinction before selecting any other column of the table
What is wrong with this query with DISTINCT keyword?
[ "", "mysql", "sql", "distinct", "" ]
I have a program that report its version and IP to the following table ``` CREATE TABLE `Operadores` ( `Num` int(11) NOT NULL AUTO_INCREMENT, `Usuario` varchar(45) NOT NULL, `Password` varchar(15) NOT NULL, `LastLogin` varchar(25) DEFAULT '01/01/1970 00:00:00', `AdminLevel` int(10) unsigned DEFAULT '1', `G...
The reason why you are getting two rows is because you are using two columns in your `group by` clause `VersionGTS,LastIP`. If you want to get only one value then you can use the `max` function to get the max version of the `Version` column try this: ``` SELECT max(versionGTS),LastIP,LastLogin FROM gts.Operadores G...
To get the maximum version per IP, you can use this simple query: ``` SELECT MAX(Version) AS MaxVersion, LastIP FROM gts.Operadores GROUP BY LastIP ; ``` If you want to additionally return `Usuario` associated with every particular pair of `MaxVersion` and `LastIP`, you can achieve that by joining the results...
Should I use DISTINCT?
[ "", "mysql", "sql", "" ]
When I try to excecute this code, I'm getting error: *Conflict of the DELETE statement with the restriction REFERENCE "FK\_Options\_users". The conflict occurred in database "WINTOUR", table "PrintForm.Options", column 'user\_code'* Can't understand why and how to fix that. ``` declare @USER_CODE int; select ...
It seems like `Foreign Key constraint` exists between the `user_code` column in `PrintForm.Options` and the `code/user_code` column in given tables. If you try to delete all the data in given tables an error will occur as the `user_code` column in `PrintForm.Options` reference the data in the any one of the table from...
It looks to me like you are removing user 24, but the PrintForm.Options table has an entry that is still using it, and were it to be deleted, the foreign key would no longer be satisifed. Have you perchance missed "Printform.Options" from the list of delete queries?
Conflict of the DELETE statement with the restriction REFERENCE
[ "", "sql", "" ]
Some times I need to generate to many insert querys, like this: ``` update claim set register_dt = '2014-01-29 09:48' where folio = '0021' update claim set register_dt = '2014-04-09 11:30' where folio = '0080' update claim set register_dt = '2014-05-06 13:00' where folio = '0123' update claim set register_dt = '2014-0...
I'd choose to use a temporary table like @GordonLinoff shows. But that technically isn't a single query, because you have to create and populate the temporary table. One way you can truly do this in a single query is to use a huge CASE expression: ``` update claim set register_dt = case folio when '0021' then '2014-0...
The easiest way, in my opinion, would be a two step process. First store the data in a temporary table and then use that for the update. ``` create temporary table toupdate as select '2014-01-29 09:48' as register_date, '0021' as folio union all . . . ; update claim c join toupdate tu on c.f...
improve update in MySQL
[ "", "mysql", "sql", "sql-update", "" ]
Here I need to check the string which is in the format '`a,c,e`'. This situation occurred when user select multiple option from check box and in the query I need to check it with the present column. **Example**: Given string: ``` 'a,c,e' ``` Need to check the given string each word is present in the column `columnA...
Try below code: ``` DECLARE @COMMASEPSTR NVARCHAR(200), @SQL nvarchar(max), @STR nvarchar(100) = 'a,b,c' SET @COMMASEPSTR= '''' + REPLACE(@STR,',',''',''') + '''' SET @SQL = 'select columnA,columnB from test where columnA IN ( ' + @COMMASEPSTR + ')' EXEC sp_executesql @SQL ``` Tell me if I am wrong somewhere.
I am not sure about the format of your dynamic input string or format of columnA but you can try this: ``` select columnA,columnB from test where CHARINDEX(columnA, 'a,c,e')>0 ```
Check string in select statement using SQL Server 2008
[ "", "sql", "sql-server", "" ]
I have 3 different tables for a blog I am working with. 1st table: blog\_posts, it has an ID, Title, Content, user\_id (who created post), created\_date and slug. 2nd table: blog\_tags, it has an ID, post\_id and tag\_id 3rd table: tags, it has an ID and tag I am using table 3 to save all tags once, so that there a...
I assume you are happy to send two requests to the database. First, get all the posts for a given tag: ``` SELECT * FROM blog_posts bp WHERE EXISTS (SELECT * FROM blog_tags bt INNER JOIN tags t ON t.id = bt.tag_id WHERE bp.id = bt.post_id AND t.tag = @SearchTag) ``` Secon...
I did it in one go, continuing on @Bulat's code. ``` SELECT *, GROUP_CONCAT(DISTINCT bt.tag_id) as tags_id, GROUP_CONCAT(DISTINCT t.tag) as tags FROM blog_posts bp INNER JOIN blog_tags bt ON bt.post_id = bp.id ON t.id = bt.tag_id GROUP BY bt.post_id ORDER BY bp.created_date DESC ``` Then I return tags and tags\_id ...
Get all posts that have a specific tag and keep all other tags on results with SQL
[ "", "mysql", "sql", "codeigniter", "" ]
I have a requirement to split a row into two based on the nullability of two columns in the table used in the query. ``` Sample Data ------------------------------------------------------------------------------------------------- PrimaryID SecondaryID PassedSubject FailedSubject PSField FSFie...
``` SELECT PrimaryID, SecondaryID, CR.PassedSubject, CR.FailedSubject, CR.PSField, CR.FSField FROM TableName CROSS APPLY (VALUES ( PassedSubject,NULL,PSField,NULL), ( NULL, FailedSubject,NULL,FSField)) CR ( PassedSubject, FailedSubject, PSField, FSField) WHERE TableN...
``` ;WITH PassedCTE AS ( SELECT PrimaryID, SecondaryID, PassedSubject, NULL AS FailedSubject, PSField, NULL AS FSField FROM TableName WHERE PassedSubject IS NOT NULL ),FailedCTE AS ( SELECT PrimaryID, SecondaryID, NULL AS Pa...
Query to split a row into two
[ "", "sql", "sql-server", "sql-server-2008", "" ]
my query : ``` SELECT USERINFO.USERID [User ID], USERINFO.BADGENUMBER [Employee No.], USERINFO.NAME [Name] FROM USERINFO where CHECKTIME='2014-09-08' ``` when i write above query then it will not return the value of checktime='2014-09-08' ``` but when i write checktime>='2014-09-08' then it will give me the output...
Your problem is having equality between a field that may contain a value like `2014-09-08 09:19:34.000` and a value that is `2014-09-08`. These are in no way equal. Having no time is equevalent to the midnight of the specified date, so `2014-09-08` is equal to `2014-09-08 00:00:00.000`. You need a way to strip the tim...
Its happening because you are comparing unequal values. Here , you are comaparing **2014-09-08** **09:19:34.000** with some thing line **2014-09-08 00:00:00.000** So that is the reasoon , when equality operator is used , it is not returning any thing. So, you need to discard the time part from the date time. This is ...
i want data with where condition of date field - compare two dates discarding time part
[ "", "sql", "sql-server", "sql-server-2008", "" ]
This is my `users` table: <http://ezinfotec.com/Capture.PNG> I need to select all rows those are not contain 2 in except column. How to write a query for this using php & Mysql. The result i expect for this query is only return last row only. Thank you.
Don't store comma separated values in your table, it's very bad practice, nevertheless you can use `FIND_IN_SET` ``` SELECT * FROM users WHERE NOT FIND_IN_SET('2', except) ```
Try this: ``` SELECT * FROM users WHERE CONCAT(',', except, ',') NOT LIKE '%,2,%' ```
write select query for the below requirement
[ "", "mysql", "sql", "select", "concatenation", "sql-like", "" ]
This is the code I have: ``` INSERT INTO HCSERVREC (COMP_CD, JOBTL_CD, emp_no,from_dt,service_type) values ( '1',( if NOT EXISTS( SELECT 1 FROM SDOPTTABLE WHERE OPTTABLENO = '324' AND OPTTABLEVAL = '00883578' ) BEGIN INSERT INTO SDOPTTABLE ( comp_cd ,opttableno ,opttabl...
Check first and then insert ``` IF NOT EXISTS( SELECT 1 FROM SDOPTTABLE WHERE OPTTABLENO = '324' AND OPTTABLEVAL = '00883578' ) BEGIN INSERT INTO SDOPTTABLE ( comp_cd ,opttableno ,opttableval ,optname ,dt_stamp ) VALUES ( '1' ,'324' ,'00883578' ,'STOCKROO...
You need to do your check **first**, before you then either run your `INSERT`, or skip it. You cannot have `IF` statements in the middle of an `INSERT`: ``` IF NOT EXISTS(SELECT * FROM dbo.SDOPTTABLE WHERE OPTTABLENO = '324' AND OPTTABLEVAL = '00883578') INSERT INTO HCSERVREC (COMP_CD, JOBTL_CD, emp_no,from_dt,ser...
SQL Server: how to do if statement within the insert statement
[ "", "sql", "sql-server", "" ]
I want to group my data using SQL or R so that I can get top or bottom 10 `Subarea_codes` for each `Company` and `Area_code`. In essence: the `Subarea_codes` within the `Area_codes` where each `Company` has its largest or smallest result. ``` data.csv Area_code Subarea_code Company Result 10 101 ...
Using `sqldf` package: ``` df <- read.table(text="Area_code Subarea_code Company Result 10 101 A 15 10 101 P 10 10 101 C 4 10 102 A 10 10 102 P 8 10 102 C 5 11...
If you already doing it in R, why not use the much more efficient `data.table` instead of `sqldf` using SQL syntax? Assuming `data` is your data set, simply: ``` library(data.table) setDT(data)[, list(Largest_subarea_code = Subarea_code[which.max(Result)], Resultmax = max(Result), Smallest_suba...
Grouping query into group and subgroup
[ "", "sql", "r", "sqlite", "greatest-n-per-group", "" ]
I have been trying this query in different formats yet I don't know why I get this weird error. ``` insert into details ('refno','membershipno','name','dob','year_of_passing_diploma','phone','address','email','mobileno','city','state','pincode','degree','college') values('1001','2001','ragesh','1991-06-27','2012','244...
You cannot use single quotes around your column identifiers. Either use ticks or nothing: ``` insert into details (refno,membershipno,name,dob,year_of_passing_diploma,phone,address,email,mobileno,city,state,pincode,degree,college) values('1001','2001','ragesh','1991-06-27','2012','24423021','D1, silver star apartments...
Apart from quoting: you have 14 columns and 23 values in your query
MySql syntax error is thrown in spite of writting the correct query
[ "", "mysql", "sql", "syntax-error", "mysql-error-1064", "" ]
Given the following SQL Server schema: ``` CREATE TABLE #TableA (Id int); CREATE TABLE #TableB (Id int, TableA_Id int, Status_Id int) CREATE TABLE #Statuses (Id int) SELECT * FROM #TableA AS A INNER JOIN #TableB AS B ON A.Id = B.TableA_Id INNER JOIN #Statuses AS S ON B.Status_Id = S.Id...
``` SELECT B.TableA_Id FROM #Statuses S LEFT JOIN #TableB B ON B.Status_Id = S.Id GROUP BY B.TableA_Id HAVING COUNT(DISTINCT S.Id) = COUNT(DISTINCT B.Status_Id) ```
You can do this with a "simple" `where` clause. Assuming that the status column in `#TableB` only has valid status values: ``` select a.* from #TableA a where (select count(*) from statuses) = (select count(distinct status) from #TableB b where b.TableA_Id = a.id); ``` You can relax this assumption. Here is on...
Select rows from SQL table where ALL of a set of parameters exist in joined table
[ "", "sql", "sql-server", "t-sql", "" ]
Is there anyway to combine mysql queries columnwise? I have below queries ``` select count(ticket_id) as numInProgress from ost_ticket where status = 'in progress' and topic_id not in (select topic_id from ost_org_site_map) select count(ticket_id) as numAssigned from ost_ticket where status = 'open' and topic_id...
Just use these as subqueries in a select statement, e.g. ``` SELECT ($statement1$),($statement2$) ``` or with your queries: ``` SELECT (select count(ticket_id) as numInProgress from ost_ticket where status = 'in progress' and topic_id not in (select topic_id from ost_org_site_map)) as numInProgress ,(select count(ti...
You may try this: ``` SELECT (select count(ticket_id) as numInProgress from ost_ticket where status = 'in progress' and topic_id not in (select topic_id from ost_org_site_map)), (select count(ticket_id) as numAssigned from ost_ticket where status = 'open' and topic_id not in ...
combine mysql queries columnwise
[ "", "mysql", "sql", "" ]
I have an issue when trying to fetch out my data from my database. here are my table design I have an issue when trying to fetch out my data from my database. here are my table design ## table1: ``` user_id username 1 test 2 test2 3 test3 ``` ## table2: ``` id table2_userid ...
Try following Query it will work for your problem: ``` SELECT table1.user_id, table1.username, table2.key, table2.value FROM table1 LEFT JOIN table2 ON table1.user_id = table2.table2_userid and table2.key="position" group by table1.user_id ```
Try using single quotes: ``` SELECT table1.user_id, table1.username, table2.key, table2.value FROM table1 LEFT JOIN table2 ON table1.user_id = table2.table2_userid WHERE table2.key = 'position' ``` Otherwise your query seems fine to me. I've read this on SO in a comment: `[S]ingle for [S]trings; [D]ouble for [D]at...
MySQL SELECT all from first table and join matched data from second table with specific where clause for second table filter
[ "", "mysql", "sql", "select", "join", "where-clause", "" ]
I have two tables to register `TESTS` and `GRADES` Table `TEST (id_test, id_person, retry)` Table `GRADE (id_grade, id_test, id_question, grade)` It's possible that a person make a second test, in that case, retry would be char 'Y' (for yes) Now I need to sum all the grades grouped by person. The problem is that Wh...
``` select id_person,sum(b.grade) from ( select id_person,max(id_test) testid from test group by id_person )a inner join GRADE as b on a.testid = b.id_test group by id_person ``` [Working Example](http://sqlfiddle.com/#!3/4ed51/13)
``` ;WITH MyCTE AS ( SELECT *,ROW_NUMBER()OVER(PARTITION BY id_person ORDER BY retry DESC) AS rn FROM TEST ) SELECT SUM(grade) AS Total FROM MyCTE T JOIN GRADE G ON T.id_test = G.id_test WHERE rn = 1 ``` **[SQL Fiddle](http://sqlfiddle.com/#!6/b1ec8/3)**
SQL sum with condition field='x'
[ "", "sql", "sum", "conditional-statements", "" ]
``` SELECT cat.CategoryID as CategoryID, count(p.ProductID) as CountProducts FROM Category as cat LEFT JOIN Products as p on p.CategoryID IN (SELECT CategoryID FROM Category as cd WHERE cd.Pa...
The error you get tells you that the column `CategoryID` in your `WHERE` clause is ambiguous, that means that the system has a problem to identify the appropriate column because there are multiple `CategoryID` columns. In order to fix this problem, use the alias to specify which column you want to use for your `WHERE`...
The "ambiguous column" error means that there's a reference to a column identifier, and MySQL has two (or more) possible columns that match the specification. In this specific case, it's the reference to `CategoryID` column in the `WHERE` clause. It's "ambiguous" whether `CategoryID` is meant to refer to the `Categor...
mysql ...in where clause is ambiguous
[ "", "mysql", "sql", "" ]
I currently have the following query: ``` select title,location,categorie,division, reference.description as CA from emploi left join reference on emploi.categorie = reference.code_ref where id_type = 'CA' and emploi.status ='1' ``` and I have a second query, which is the same but is taking a different value...
You may try this: ``` select title,location,categorie,division, r.description as DI, r1.description as CA from emploi left join reference r on emploi.division = r.code_ref left join reference r1 on emploi.categorie = r1.code_ref where emploi.status ='1' and id_type in ('CA', 'DI') ``` Presently you are havi...
There are a couple of ways of achieving this: ``` select title,location,categorie,division, reference.description as DI from emploi left join reference on emploi.division = reference.code_ref where id_type IN ('DI','CA') and emploi.status ='1' ``` or you can change the where clause to an OR ``` where (id_type =...
Multiple sql joins from same reference table
[ "", "mysql", "sql", "" ]
Note: with help from RhodiumToad on #postgresql, I've arrived at a solution, which I posted as answer. If anyone can improve on this, please chime in! I have not been able to adapt a [previous recursive query solution](https://stackoverflow.com/questions/20979831/recursive-query-used-for-transitive-closure) to the fol...
With help from RhodiumToad on #postgresql, I've arrived at this solution: ``` WITH RECURSIVE node_graph AS ( SELECT ancestor_node_id as path_start, descendant_node_id as path_end, array[ancestor_node_id, descendant_node_id] as path FROM node_relations UNION ALL SELECT ng.path_start, nr.d...
An alternative approach would be to traverse the graph in reversed order: ``` WITH RECURSIVE cte AS ( SELECT array[r.ancestor_node_id, r.descendant_node_id] AS path FROM node_relations r LEFT JOIN node_relations r0 ON r0.ancestor_node_id = r.descendant_node_id WHERE r0.ancestor_node_id IS NULL -- sta...
Recursive query challenge - simple parent/child example
[ "", "sql", "postgresql", "recursive-query", "transitive-closure-table", "" ]
I'm using SQL Server 2012 and I need to write a query that will extract data greater than a particular date. The date field is called 'CreatedOn" and dates are recorded in this format "2014-08-18 17:02:57.903". Currently, the date part of my query stands as follows: ``` WHERE CreatedOn > '2014-08-18' ``` Problem...
Try the following condition. The problem is that `2014-08-18` is really `2014-08-18 00:00:00` (includes the hour), so any date time in that day will be greater. ``` WHERE CreatedOn >= '2014-08-19' ```
'2014-08-18' actually means '2014-08-18 00:00:00' So if you do not want 18th you should put either '2014-08-19' or specify the hours you want your date to be bigger of.
Using Dates in SQL Server 2012 Query
[ "", "sql", "sql-server", "date", "sql-server-2012", "" ]
I figured one way to solve my poorly formatted table would be to parse the "date" column in to three columns after which i can properly run queries on. The date format is 'ddmmmyyyy' style (31DEC2013). How can I parse this string into three distinct columns "day", "month", "year". Thanks in advance
The DATEPART command can do that for you. For example: ``` select datepart(day, '31DEC2013') select datepart(month, '31DEC2013') select datepart(year, '31DEC2013') ``` I would recommend just leaving your date in one column, and using datepart on the fly in your queries.
You are trying to get your data from one WRONG type to another WRONG type. It is a date value and you should use appropriate data type for it which is `DATE` or `DATETIME`. Saving this data with appropriate data type will give you access to many datetime functions for data manipulations. ## Test Data ``` DECLARE @TA...
How can I parse a varchar string into three columns, Year, Month and Day
[ "", "sql", "sql-server", "parsing", "" ]
When I try to debug an Stored Procedure using Microsoft SQL Server Management Studio, I encounter this error message: Unable to start T-SQL Debugging. Could not connect to computer ("**\***"). The dubugger cannot connect to the remote computer. This may be because the remote computer does not exist or a firewall may pr...
SSMS needs to be able to find your SQL Server by DNS. When you connect to the DB in SSMS, you can use (local), but (local) does not resolve on your network so the debug program can not find it. Try connecting to localhost or your computer's name on the "Connect to Server" screen. You should not have to run as administ...
I just wanted to pay this forward, as after searching for quite some time I've yet to see anyone mention the problem that I encountered here. I ran into this issue while connected to SQL using a SQL Server Authenticated user. Once I tried using a Windows Authenticated user I was able to debug without issue. That user ...
Unable to start T-SQL Debugging. Could not connect to computer ("*****")
[ "", "sql", "sql-server", "debugging", "" ]
I am planning to write a TSQL function of two input strings and a percentage of words similarity as an output, For example : ``` SELECT [dbo].[FN_CalcSimilarWords]('Golden horses hotel','Hotel Golden Horses') ``` Returns : ``` 3/3 ``` or ``` SELECT [dbo].[FN_CalcSimilarWords]('Golden horses','Golden horses Malaysi...
If you want to do it in SQL, here is an approach I would take. Create two temporary tables, using a split routine, called Words1 and Words2 Now join the tables and get the count, i.e. ``` select count(*) from Words1 w1 join Words2 w2 on w1.word=w2.word ``` Let SQL do it the way it is optimized for Here is how to...
With this solution I am assuming you want duplicates to be removed. Switching first and second parameter makes no difference to result. It returns a value, not a percentage since functions can only return 1 value or a table. I assume you want values between 0 and 1 making 2/3 = 0.67 or 67 percent if you multiply by 10...
Calculating the number of similar words between two strings in SQL
[ "", "sql", "sql-server", "string", "algorithm", "t-sql", "" ]
Is there a known standard for writing **SQL logic to common English** for non-programmers to understand? The Monthly Reports I'm generating need to be verified by the client and I don't think I have the balls to shove SQL down his richie rich throat. :) For example, this: ``` SELECT cust.* FROM sl_customers cust LEFT...
Here's a mostly line-by-line translation: ``` SELECT cust.* ``` Get the customer information… ``` FROM sl_customers cust LEFT JOIN sl_orders orders ON cust.id = orders.customer_id ``` …for every order (and the customer associated with the order's customer ID),… ``` WHERE DATE_FORMAT(orders.delivery_date, '%Y-...
I don't think there's a standard, but if I were trying to explain this to a non-SQL speaker, I'd say something like: > This gives me all the new customers created during August > who have active (non-cancelled) orders > delivered during August and who came from > newspaper, TV, or radio ads, or through social media
Write SQL code in common english for non-programmers to understand
[ "", "mysql", "sql", "" ]
I'm writing a PostgreSQL function to count the number of times a particular text substring occurs in another piece of text. For example, calling count('foobarbaz', 'ba') should return 2. I understand that to test whether the substring occurs, I use a condition similar to the below: ``` WHERE 'foobarbaz' like '%ba...
I would highly suggest checking out this answer I posted to [*"How do you count the occurrences of an anchored string using PostgreSQL?"*](https://dba.stackexchange.com/a/166763/2639). The chosen answer was shown to be massively slower than an adapted version of `regexp_replace()`. The overhead of creating the rows, an...
How about use a regular expression: ``` SELECT count(*) FROM regexp_matches('foobarbaz', 'ba', 'g'); ``` The `'g'` flag repeats multiple matches on a string (not just the first).
PostgreSQL count number of times substring occurs in text
[ "", "sql", "postgresql", "" ]
my aim is a SQL statement to identify different accounts in a list of assets (assets have a mainnumber and a subnumber). The table looks like this: ``` amainnr | asubnr | account ----------------------------- 10000 | 0 | 123 10000 | 1 | 123 10000 | 2 | 456 10000 | 3 | 789 10001 | 0 ...
``` SELECT b.amainnr, b.asubnr, b.account FROM atable b WHERE b.amainnr IN (SELECT a.amainnr FROM atable a GROUP BY a.amainnr HAVING count(distinct(a.account)) > 1) ```
Try this: ``` select * from atable a where exists (select 1 from atable b where a.id!=b.id and a.amainnr = b.amainnr and a.account != b.account) ```
SQL: Find different accounts in asset list
[ "", "mysql", "sql", "select", "" ]
**SQL Server 2008** My SQL table is Like below ``` ---------------------------------------- **name department fee_paid id** ---------------------------------------- Farooq ECE 10000 NULL Khan EEE 20000 NULL Syed Chemistry 4000 NULL Syed Chemistry 14000 NULL Yous...
Why don't you use `ALTER TABLE`? ``` alter table flatfile add ID int identity(1000,1) ``` **EDIT** - if you want to do it in loop: ``` declare @i as int = 1000 while @i<=1006 begin update top(1) flatfile set id=@i where id is null; set @i+=1 end ```
To get the ID it's possible to use the `Row_Number` function. Windowing functions are not allowed in an update script, but we can write an updatable view, or a CTE, and work with it instead: ``` WITH CTE AS ( SELECT [name], [department], [fee_paid], [id] , num = Row_Number() OVER (ORDER BY (SELECT N...
How to update particular column fields with while loop
[ "", "sql", "sql-server-2008-r2", "" ]
This is edited - I have tried speeding this up but still very slow - can anyone offer anymore help please? ``` SELECT DISTINCT d.`group_ID`, CONCAT(u.fname, ' ', u.lname) AS uname, u.corp_id, c.`corp_name`, u.`user_username`, u.location, ( SELECT email FROM users WHERE role = 'Level 4' ...
* You negate the left join from `regulatory` to `users` in the where clause, so use an `INNER JOIN` for those two tables * use `INNER JOIN` on corporations if this is possible (I just don't know if it is or not) * remove DISTINCT. You are already performing a `GROUP BY` and if that is done correctly distinct will be ...
I think that your query have little problem with line: ``` ... ( SELECT email FROM users WHERE role = 'Level 4' AND location = d.location AND email NOT LIKE '%manager.%' LIMIT 1 ) AS trainer, ... ``` For each row you prepare single select. Mayby you should change that query to another join. I wuld also recom...
Slow MySQL Query - how can it be speed up?
[ "", "mysql", "sql", "performance", "" ]
I'm actually trying to select one record from `amgb` using a limit while doing a join with `amga`. My tables are like this: **amga** ``` "id" "itemId" "itemTempId" "itemName" "itemCountry" "userId" "1" "US1" "T001" "Samsung Galaxy Note 5" "US" "1" "2" ...
If subquery returns one column and no more than one record you can include it as column in query: ``` SELECT a.itemName, (SELECT itemImageName FROM amgb b WHERE a.userId = b.userId AND a.itemId = b.itemId LIMIT 1 ) AS itemImageName FROM amga a WHERE a.userId = 1 AND a.itemId = 'US1'; ```
Try to use this:- ``` SELECT a.itemName, b.itemImageName FROM amga a LEFT JOIN ( SELECT itemId, userId, itemImageName FROM amgb LIMIT 1 ) b ON a.userId = b.userId and a.itemId = b.itemId WHERE a.userId = 1 and a.itemId = 'US1'; ```
MySql select with Limit 1 when using a join with 2 tables
[ "", "mysql", "sql", "" ]
Is there any way I can script out all the SQL Server objects (tables, SP, functions etc) under a schema? In our database we have a table containing name of all the schemas and there are more than 500 schema. Some of them are for dev and some are prod. I need to script out all the objects under dev schema and create a ...
Thanks guys for your reply. I have solved this by generating all the scripts through SSMS and then created a schema only database. Than I dropped all the tables, views SP, functions etc those are not part of the schema I do not need. It took me around 20 mins to do that. But after all the work is done.
[ApexSQL Script](https://www.apexsql.com/sql_tools_script.aspx) is the tool which can be very helpful in this situation. It is the tool which creates SQL scripts for database objects, and it can script all objects into one script or all objects separately. For this situation here is what you should do: 1. Select serv...
Script out all SQL objects under particular schema
[ "", "sql", "sql-server", "t-sql", "" ]
I want to store a certain struct into my database that has a JSON field within it. ``` type Comp struct { CompId int64 `db:"comp_id" json:"comp_id"` StartDate time.Time `db:"start_date" json:"start_date"` EndDate time.Time `db:"end_date" json:"end...
sqlx has a type `JSONText` in `github.com/jmoiron/sqlx/types` that will do what you need [doc](http://godoc.org/github.com/jmoiron/sqlx/types#JSONText) for JSONText
I don't know how clean of a solution this is but I ended up making my own data type `JSONRaw`. The DB driver sees it as a `[]btye` but it can still be treated like a json.RawMessage in the Go Code. ``` type JSONRaw json.RawMessage func (j JSONRaw) Value() (driver.Value, error) { byteArr := []byte(j) return d...
Storing Golang JSON into Postgresql
[ "", "sql", "json", "postgresql", "struct", "go", "" ]
I am currently trying to export the past 3 months of data from a table on my SQL Server to a new table in a new database (same columns etc but slightly different primary keys). I get an error when doing this because there is a duplicated primary key in the new table.. I was wondering whether there is a way to ignore th...
I don't know what your PK field is called but lets say it is ID. You can do this to number the records that all had the same id, then just pull out the first one from each sequence. Notice I ordered this by the date so the earliest date would be the one selected. ``` SELECT ID, systemdatetime, etc.. FROM ( SELECT *,...
Create an unkeyed copy of your target table and dump your data into that. From there, you can decide what is really unique and what isn't.
Ignoring duplicated primary keys when exporting data from one database to another in SQL
[ "", "sql", "sql-server", "export", "primary-key", "" ]
Is there any alternative, more elegant, expression to 1=2 that can be used in where clauses in sql? Something resembling `WHERE false` Couldn't find an answer to this in google. **EDIT:** In languages such as C++ the expressions (1==2) and 0 are equivalent, why doesn't TSQL accept `false` or `true` as a condition?
Well, TSQL defines `WHERE` clause as `WHERE <search_condition>` with a variety of "complex?" syntax that excludes an "expression result". Here is the reference for ["search\_condition"](http://msdn.microsoft.com/en-us/library/ms173545.aspx). `False`, `4` are expressions results. What you expect is perhaps more logica...
Firstly I think `1=2` is itself elegant. So you need to specify exactly in which situation or how you are using it. Next `1=2` specify a false condition(*which you are already aware of*). This is used mostly when you want to check for a false condition something like when you want to create the schema of the table with...
An alternative to 1=2 in sql
[ "", "sql", "t-sql", "" ]
Lets say I have a table called `census` with the following information: ``` COUNTRY PROVINCE CITY POPULATION ============================================== USA California Sacramento 1234 USA California SanFran 4321 USA Texas Houston 1111 USA Texas Da...
Ok, I finally came up two approaches that are flexible and don't make me feel like a terrible programmer. --- The first solution involves [`GROUPING SETS`](http://docs.oracle.com/cd/E11882_01/server.112/e25554/aggreg.htm#DWHSG8631). What I'm essentially trying to do is group the expression at two different levels: ...
This is exactly what **[`GROUPING SETS`](http://docs.oracle.com/cd/B19306_01/server.102/b14223/aggreg.htm#i1006842)** expressions was designed to do: ``` SELECT country, province, SUM(population) FROM census GROUP BY GROUPING SETS ( (country, province), -- first group by country and province () ...
Overall summary with multiple GROUP BY
[ "", "sql", "oracle", "group-by", "rollup", "grouping-sets", "" ]
I have a table which has data in this format: ``` id name cnt1 created_on '1','uac','116','2014-09-06 17:16:29' '2','uac','116','2014-09-06 17:17:06' '3','uac','90','2014-09-06 21:53:34' '4','uac','100','2014-08-06 21:53:34' '5','uac','1','2014-07-06 21:53:34' '6','uac','2','2014-07-26 21:53:34' '7','uac','3','2014-09...
You don't actually want a `group by` query. You want to get the last row for each set. Here is a method using `not exists`: ``` SELECT cd.* FROM qa_dashboard.project_qa_coverage_detail cd WHERE NOT EXISTS (SELECT 1 FROM qa_dashboard.project_qa_coverage_detail cd2 WHERE year(cd2.crea...
Pretty sure this will get you your expected output: **Last for month:** ``` select t.* from tbl t join (select max(created_on) as last_for_month from tbl group by year(created_on), month(created_on)) v on t.created_on = v.last_for_month ``` Except where you say you expect: ``` '6','uac','...
How to get data from mysql for given date range group by weekly,monthly
[ "", "mysql", "sql", "" ]
We have a table which will capture the swipe record of each `employee`. I am trying to write a query to fetch the list of distinct employee record by the first swipe for today. We are saving the swipe date info in `datetime` column. Here is my query its throwing exception. ``` select distinct [employee number],...
The error says it all: > ...Employee First Name' is invalid in the select list because it is not contained > in either an aggregate function or the GROUP BY clause Saying that, there are other columns that need attention too. Either reduce the columns returned to only those needed or include the columns in your `GRO...
Please Try Below Query : ``` select distinct [employee number],[Employee First Name] ,[Employee Last Name] ,min([DateTime]) ,[Card Number] ,[Reader Name] ,[Status] ,[Location] from [Interface].[dbo].[VwEmpSwipeDetail] group by [employee number],[Employee Fi...
Column invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
[ "", "sql", "sql-server", "group-by", "aggregate", "" ]
I have only gone so far: ``` select timestamp, trans, Count(trans) From( Select to_char(CREATED_TIMESTAMP) as timestamp,SOURCE_MSISDN||DEST_MSISDN||AMOUNT as trans From ADMDBMC.TRANSACTION_CASH WHERE TO_date(CREATED_TIMESTAMP) > = '1-sep-2014' AND TO_date(CREATED_TIMESTAMP) < '2-sep-2014' and STATUS_...
I think you can achieve that by truncating your timestamp on the nearest multiple of 10 minutes: you could replace `to_char(CREATED_TIMESTAMP) as timestamp` with `regexp_replace(to_char(CREATED_TIMESTAMP, 'dd-Mon-yyyy hh24:mi'), '.$', '0')` and I think your group by would then be ok. **EDIT** : the previous solution w...
Emmanuels way would return false negative for example if one transaction occured at 11:49 and second at 11:52 You could use LEAD or LAG aggregate function with window option to get timestamp of a older row then current and calculate [difference between two timestamps](https://stackoverflow.com/questions/11617962/calcu...
How do I find transactions that are less than 10 minutes apart using timestamps in sql
[ "", "sql", "oracle", "" ]
Please help me to write an SQL query in the Oracle database. There is table called tbl and it has 12 rows. I want to select first 4 rows first then next 4 and the last 4 rows. Can any anyone tell me how can I do this in Informix.
You can use `rownum`: ``` select * from (select t.*, rownum rn from tbl t) where rn between 1 and 4; / select * from (select t.*, rownum rn from tbl t) where rn between 5 and 8; / select * from (select t.*, rownum rn from tbl t) where rn between 9 and 12; / ``` If you're using `order by` clause then use `row_number()...
EDIT: now should be fixed with 3-level select: ``` select * from ( select q1.*, rownum as rn from ( --get correct rownum select * from tbl order by column --get correct order ) q1 ) q2 where q2.rn between 1 and 4; -- filter ``` for first part. For second and third part: ``` where q2.rn between 5 and ...
Fetch a fixed number of rows in SQL query in Oracle
[ "", "sql", "oracle", "informix", "" ]
Sorry if this a duplicate, but i haven't found one. Why can't i use my column alias defined in the `SELECT` from the `ORDER BY` when i use `CASE`? Consider this simple query: ``` SELECT NewValue=CASE WHEN Value IS NULL THEN '<Null-Value>' ELSE Value END FROM dbo.TableA ORDER BY CASE WHEN NewValue='<Null-Value>' THEN ...
**This has to do with how a SQL dbms resolves ambiguous names.** I haven't yet tracked down this behavior in the SQL standards, but it seems to be consistent across platforms. Here's what's happening. ``` create table test ( col_1 integer, col_2 integer ); insert into test (col_1, col_2) values (1, 3), (2, 2),...
It seems this limitation is related to another limitation in which "column aliases can't be referenced in same `SELECT` list". For example, this query: ``` SELECT Col1 AS ColAlias1 FROM T ORDER BY ColAlias1 ``` Can be translated to: ``` SELECT Col1 AS ColAlias1 FROM T ORDER BY 1 ``` Which is a legal query. But this...
Why can't i refer to a column alias in the ORDER BY using CASE?
[ "", "sql", "t-sql", "sql-server-2005", "sql-order-by", "" ]
I have a stored procedure that stores values in temp tables. It all works well, but I can not bcp it with ``` exec master..xp_cmdshell 'bcp "exec sp_test '2006-07-21' " queryout c:\test.txt -c ' ``` If I change the table to regular, then it all works. Can you not use temp tables this way? I would not necessarily wa...
I have just stumbled upon this a few days ago. What I've learned from this link: > <http://www.dbforums.com/microsoft-sql-server/1605565-can-we-have-temporary-table-store-procedure-when-using-bcp.html> is that it won't see temp tables as they'd be in the tempdb database not the one you are using. Also, I got mine w...
Have you tried referencing the temp table like this in your query: `tempdb..#Extractr` For example: ``` SELECT * INTO tempdb..#Extractr FROM TABLE A WHERE ID in (4,9,14) ```
bcp won't output temp tables
[ "", "sql", "bcp", "" ]
Using Oracle 10g, I have a table that looks like this (syntax shortened for brevity): ``` CREATE TABLE "BUZINESS"."CATALOG" ( "ID" NUMBER PRIMARY KEY, "ENTRY_ID" VARCHAR2(40 BYTE) NOT NULL, "MSG_ID" VARCHAR2(40 BYTE) NOT NULL, "PUBLISH_STATUS" VARCHAR2(30 BYTE) NOT NULL, /* Can be NEW or PUBLISHED */ ...
Requiring non-presence of joinable data is best solved with an outer join that filters out matching joins (leaving just the non-matches). In your case, the join condition is a "published" row for the same entry with a later (higher) message if. This query produces your desired output: ``` select t1.* from buziness_c...
Reading between the lines, I think this might work: ``` select * from buziness.catalog b1 where b1.publish_status = 'NEW' and not exists ( select 'x' from buziness.catalog b2 where b1.entry_id = b2.entry_id and b2.publish_status =...
Refactoring SELECT with two correlated subqueries
[ "", "sql", "oracle", "" ]
I need to create a query that pulls only the customer\_no column (because the software restrictions are as such, and I can't code it externally). But I need to be able to sort the data by create\_dt (in reverse) column. The code/SQL is restricting me in using the following because in order to sort by something that dat...
Of course you can. Your query looks like SQL Server, where this will likely do what you want: ``` Select top 3500 a.customer_no From T_CUSTOMER a WITH (NOLOCK) JOIN (Select a1.customer_no From VXS_CUST_TKW a1 WITH (NOLOCK) Where a1.tkw in (141) ) e ON e.customer_no = a.custom...
This does not look like mysql. Anyway... you could try an ordered sub-select IE ``` From (select * from T_CUSTOMER order by create_dt) a WITH (NOLOCK) ``` I hope this helps.
Ordering by a field not in the select statement in SQL
[ "", "sql", "t-sql", "join", "sql-order-by", "" ]
I have a scenario where I need something similar to `.NET's try-catch-finally block.` On my try, I will `CREATE a #temp table`, `INSERT` data to it & process other data sets based on `#temp`. On `CATCH` then `RAISERROR`. Is it possible to have a `FINALLY` block to `DROP #temp`? Below is the pseudo code: ``` BEGIN TR...
Instead of creating a table you could just declare a table variable (which will automatically go away when the query ends). ``` BEGIN TRY DECLARE @temp TABLE ( --columns ) --do stuff END TRY BEGIN CATCH --do other stuff END CATCH ```
While not exactly the same as FINALLY, the T-SQL version of Try-Catch does allow that code that needs execute after both the Try and Catch blocks can occur after the end of the END CATCH statement. Using the question code as an example: ``` BEGIN TRY CREATE TABLE #temp ( --columns ) ...
SQL Server TRY CATCH FINALLY
[ "", "sql", "sql-server", "t-sql", "" ]
I have two tables one with I have 3 tables: ``` Agents AgentID AgentEmail Prospects ProspectId ProspectMail AgentProspects AgentID ProspectID ``` The relationship between the agents and the prospects is done through AgentProspects table. I know how to join the tables to get a straight froward list of the emails for...
``` SELECT a.email , C.email from agent a CROSS APPLY ( SELECT TOP 10 pros.email FROM AgentProspects AS AP INNER JOIN prospects Pros ON ap.prospectId = pros.prospectId WHERE AP.agentId = a.agentid ) C(ema...
``` select top 10 a.email, pros.email from agent a join agentprospects ap on a.agentid = ap.agentId join prospects pros on ap.prospectId = pros.prospectId where a.IsDeleted = 0 and (select count(*) from profile p where a.agentid=ap.agentid) =4 ``` Alternatively, you can create function which return scalar (integer) ...
How do I get 10 customers that are tied to 4 agents?
[ "", "sql", "sql-server", "" ]