Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following table, named Example: ``` col1 ---------- 101 102 103 104 ``` I want below result existing column with one addition result ``` col1 newcol --------------- 101 0/''/null 102 101 103 102 104 103 SELECT COL1, @a := @a AS col2 FROM MYTABLE JOIN (SELECT @a := 0) t ...
You can use `a` to save the last one. ``` SELECT @a as Prev, @a:=COL1 as Current FROM MYTABLE ORDER BY COL1; ``` You can find further information in [MySQL User-Defined Variables](https://dev.mysql.com/doc/refman/5.7/en/user-variables.html) I hope that you will find it useful. **EDITED**: Removed the initializing ...
This is a bit complicated, but the following handles it: ``` SELECT COL1, (CASE WHEN (@oldprev := @prev) = NULL THEN NULL -- NEVER HAPPENS WHEN (@prev := col1) = NULL THEN NULL -- NEVER HAPPENS ELSE @oldprev END) as prevcol FROM MYTABLE CROSS JOIN (SELECT @prev := 0) p...
Getting previous column values in a new column
[ "", "mysql", "sql", "" ]
I am working on a long query that includes a SELECT DISTINCT and subquery. It is partially working, but not when put together. I am getting a Error: 1241 - Operand should contain 1 column(s) and I cannot see why. Any help would be greatly appreciated. Here is my code: ``` SELECT p.projId, pc.company, s.staffId, s.fNa...
Snip: ``` ... WHERE p.projId = '9' AND pc.company NOT IN ( SELECT p.projId, pc.company, s.staffId, s.fName, s.lName FROM projects AS p .... ) ``` You're trying to select when `company not in` but there are specifying more than one selected row from within your `not in` query. Just select `company`...
If you want to keep all the rows for a given projects, use a `left join`: ``` SELECT p.projId, pc.company, s.staffId, s.fName, s.lName FROM projects p LEFT JOIN projCorp pc ON p.projId = pc.projId LEFT JOIN projStaff ps ON p.projId = ps.projId LEFT JOIN staff s ON ps.staffId = s.StaffId A...
SQL SELECT DISTINCT Subquery Error: 1241
[ "", "mysql", "sql", "subquery", "union", "mysql-error-1241", "" ]
I am (fairly new to) using PL/SQL with Oracle 12c, and am having trouble with a procedure I am trying to implement. I've looked up a lot of tutorials and similar questions here, but so far I've had no luck finding anything that could help me. The situation is this: I have three tables: table1, table2, and table3. > T...
If I understand your problem correctly (sample data would be much of help), then I would use [MERGE](https://oracle-base.com/articles/10g/merge-enhancements-10g) statement as follows (**Tested**): ``` MERGE INTO table1 -- The table you want to update USING ( SELECT t2.detailB detailb, t2.detailC, t3.detailD detail...
when you updated column to listed in select query like this ``` UPDATE (SELECT table1.detailB, table2.detailB, table2.detailC, table3.detailC, table3.detail4, table1.detailA FROM table1 JOIN table2 on table1.detailB = ta...
Updating table while joining across multiple tables
[ "", "sql", "oracle", "join", "sql-update", "" ]
Following table is my database tabel `question`. [![enter image description here](https://i.stack.imgur.com/2ijR5.png)](https://i.stack.imgur.com/2ijR5.png) when I pass `$ID=2` using this function, ``` function getFirstID($ID) { $checkQ = "SELECT * FROM tabel WHERE quiz_id = '$ID"; $query = $this->d...
``` SELECT `ID` FROM tabel WHERE quiz_id = '$ID ORDER BY `ID` LIMIT 1 ``` Please try this query.
You can use `ROWNUM`,`LIMIT`,`TOP`,`PERCENT` with this case, 1.) Deal with row numbers: ``` SELECT columnNames FROM Table_name WHERE ROWNUM <= number; ``` 2.) Can limit rows: ``` SELECT columnNames FROM Table_name LIMIT number; ``` 3.) can select number of rows that you want from `TOP` ``` SELECT TOP 5 * FROM Tab...
return single value of first row when query return more than one row
[ "", "mysql", "sql", "codeigniter", "" ]
I'm new to SQL and I've been racking my brain trying to figure out exactly what a query I received at work to modify is stating. I believe it's using an alias but I'm not sure why because it only has one table that it is referring to. I think it's a fairly simply one I just don't get it. ``` select [CUSTOMERS].Prefix,...
Here's a shot at it in english... It looks like the intent is to get a list of customer names, addresses, start dates. But the table is expected to contain more than one row with the same customer name and address, and the author wants only the row with the most recent start date. Fine Points: * If a customer has t...
I assume, it selects records about customers records from table `[CUSTOMERS]` whith the most recent `[CUSTOMERS].[START_DATE]`
Understanding an SQL Query
[ "", "sql", "sql-server", "t-sql", "greatest-n-per-group", "" ]
I have a problem with retrieving of a row with max value of a big group in oracle db. my table looks like something like this: id, col1, col2, col3, col4, col5, date\_col The group would consist of 4 columns col1, col2, col3, col4, so members mof the group should be equal on these fields, and from each group I need ...
You can use the [`RANK`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions123.htm) (or `DENSE_RANK`) analytic functions to find the maximum value(s) within a group: [SQL Fiddle](http://sqlfiddle.com/#!4/8d174/2) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE table_name ( id, col1, col2, col3, col4, c...
I think you need conditional aggregation with `row_number()`: ``` select t.* from (select t.*, row_number() over (partition by col1, col2, col3, col4 order by date_col desc) as seqnum from t ) t where seqnum = 1; ``` If you want all rows with the maximum value, then use `dense_rank()` or `rank...
select rows with max value from group
[ "", "sql", "oracle", "" ]
I have a query, and when I execute it in SQL Server 2012, the `ORDER BY` clause is not working. Please help me in this. Regards. ``` DECLARE @Data table (Id int identity(1,1), SKU varchar(10), QtyRec int,Expiry date,Rec date) DECLARE @Qty int = 20 INSERT @Data VALUES ('001A', 5 ,'2017-01-15','2015-11-14'), (...
SQL tables represent *unordered* sets. When you `SELECT` from a table, then the results are *unordered*. The one exception is when you use an `ORDER BY` in the outer query. So, include an `ORDER BY` and the results will be in order. EDIT: You can eliminate the *work* for the sort by introducing a clustered primary k...
A `SELECT ... INTO` clause will help reach your expected output. I usually use temp tables in this way along with a column with a Row number using the `ROW_NUMBER()` function. It automatically orders the selected rows to the temp table. Or more simply, you can use the `ORDER BY` clause.
Order by not working when insert in temp table
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have two tables: ``` Table: products ----------------------------------------------------- | id | name | other fields... ----------------------------------------------------- | 20 | Intel i5 4690K | ... | 21 | AMD A6-7400K | ... | 23 | AMD A8-3850 |...
To get `AMD` `4 CORES`, This query works fine. You need to do inner join Twice on `product_details` to get `manufacturer` as well as `no of cores`. Here is the [**SQLFiddle Demo**](http://sqlfiddle.com/#!9/aa4ad/1) ``` Select product_details.product_id, products.name, product_details.op...
First if you need only AMD manufacture then where is the option of this value ? you said that: ``` 2478 = Number of Cores 2482 = Manufacturer 55032 = 4 cores 55050 = 6 cores ``` Ok, But where were the `value`of the `option_id = 2482` ? you must know them and include them in your `Where` clause. Also I prefer to use ...
MySQL - return unique record
[ "", "mysql", "sql", "" ]
I'm trying to get rows that have max value in each group. I have this tables ``` +-------+-----------+--------------+-----------+ | nid | name | crated | grp_id | +-------+-----------+--------------+-----------+ | 1 | RAND_NAME | 123 | 11 | | 2 | EHllo | 111 | ...
You need a subselect: ``` SELECT yourtable.* FROM yourtable LEFT JOIN ( SELECT grp_id, MAX(created) AS max FROM yourtable GROUP BY grp_id ) AS maxgroup ON ( (yourtable.grp_id = maxgroup.grp_id) AND (yourtable.created = maxgroup.max) ) ``` subselect the gets the ID/max value for each group, and the par...
Try: ``` SELECT nid, name, MAX(created), grp_id FROM t GROUP BY grp_id; ```
Rows with max value of each group
[ "", "mysql", "sql", "aggregate-functions", "greatest-n-per-group", "" ]
I have a table like this: ``` Date Product 1/1/2015 Apples 1/1/2015 Apples 1/1/2015 Oranges 1/2/2015 Apples 1/2/2015 Apples 1/2/2015 Oranges ``` How can I do a select so I get something like this: ``` Date Count of Apples Count of Oranges 1/1/2015 2 1 1/2/2015 ...
You can do conditional aggregation like this: ``` select [date], sum(case when Product = 'Apples' then 1 else 0 end) as [Count of Apples], sum(case when Product = 'Oranges' then 1 else 0 end) as [Count of Oranges] from #temp group by [date] ```
With conditional aggregation: ``` select date, sum(case when Product = 'Apples' then 1 else 0 end) as Apples, sum(case when Product = 'Oranges' then 1 else 0 end) as Oranges, from table group by date ```
SQL get count from one table and split to two columns
[ "", "sql", "sql-server", "" ]
What I'm trying to do is when new data is entered into the db, a trigger is run that converts all text to TitleCase. How I previously did this was to create a function, then using `UPDATE TABLE` to call that function, but this is very labour intensive. My previous SQL function: ``` CREATE FUNCTION [dbo].[InitCap] ...
I would actually advise keeping your `InitCap` function, since it's nice to have that logic tucked away for re-use; there's no point in having that logic in more than one place. With that in mind, your trigger really doesn't do much except update the value that got inserted: ``` CREATE TRIGGER [dbo].[TableInsert] ON [...
I'm not sure what the MS-specific syntax is for this, but a BEFORE INSERT FOR EACH ROW trigger gives you access to the new data in a record named NEW and allows you to manipulate the record's contents (eg. changing the case of values) before the INSERT is actually performed.
Using SQL Server trigger to change format of text
[ "", "sql", "sql-server", "" ]
I have table full of strings (TEXT) and I like to get all the strings that are substrings of any other string in the same table. For example if I had these three strings in my table: ``` WORD WORD_ID cup 0 cake 1 cupcake 2 ``` As result of my query I would like to get something like this: `...
Use self-join: ``` select w1.word, w1.word_id, w2.word, w2.word_id from words w1 join words w2 on w1.word <> w2.word and w1.word like format('%%%s%%', w2.word); word | word_id | word | word_id ---------+---------+------+--------- cupcake | 2 | cup | 0 cupcake | 2 | cake | 1 (2 rows) ``...
### Problem The task has the potential to stall your database server for tables of non-trivial size, since it's an **O(N²)** problem as long as you cannot utilize an index for it. In a sequential scan you have to check every possible combination of two rows, that's `n * (n-1) / 2` combinations - Postgres will run `n ...
In SQL, how to check if a string is the substring of any other string in the same table?
[ "", "sql", "postgresql", "loops", "pattern-matching", "string-function", "" ]
I am just wondering if anyone can see a better solution to this issue. I previously had a flat (wide) table to work with, that contained multiple columns. This table has now been changed to a dynamic table containing just 2 columns (statistic\_name and value). I have amended my code to use sub queries to return the s...
Create an index on the STAT column of TEST\_DYNAMIC, for quick lookups. But first consider redesigning TEST\_DYNAMIC changing STAT varchar(6) to STAT\_ID int (referencing a lookup table) Then on TEST\_DYNAMIC, create an index on STAT\_ID which will run quite a bit faster than an index on a text field.
Create your TEST\_DYNAMIC and TEST\_URNS tables like this: ``` CREATE TABLE [dbo].[TEST_DYNAMIC]( [ID] [int] IDENTITY(1,1) NOT NULL, [STAT] [varchar](50) NOT NULL, [VALUE] [int] IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_TEST_DYNAMIC] PRIMARY KEY CLUSTERED ( [ID] )) CREATE TABLE dbo.TEST_URNS ( ID [...
SQL Query Optimization (After table structure change)
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have data in which incremental sequence is broken somewhere, maybe multiple times. E.g. (2,3,4,5,6,8,10). I want to get: 1. the first "broken" place (6 is the last good in the example) 2. the number of "broken" places (2 times, on 7 and 9) using SQL (preferably general, which works on oracle and mysql and other sq...
All beginning "breaks" sorted by ids: ``` select j1.id + 1 as id from junk j1 left join junk j2 on j2.id = j1.id + 1 where j2.id is null and j1.id <> (select max(id) from junk) order by j1.id; ``` Pick the first row to get the first "break". Count number of rows to get the number of "breaks". If you need the num...
Check this : ``` select prev_id+1 as first_fail,count(*)-1 as total_broken from ( select curr.id as curr_id,prev.id as prev_id from junk as prev left join junk as curr on prev.id+1 = curr.id ) sub where sub.curr_id is null ; ``` SQL Fiddle Example: <http://sqlfiddle.com/#!9/bae781/62> Query If Gap is wider...
SQL to detect "sequence break"
[ "", "mysql", "sql", "" ]
I am to make a SQL Query that will display tenants' sales in a yearly basis based on when it started until the present time, unless it is already not active. In the given table below as an illustration, Tenant 1 and 2 display their per year sales. Tenant 1 having 5 rows as it started in 2011, and with Tenant 2 in 2014....
You can try doing a `GROUP BY` on the `TENANT` and year to achieve your desired output: ``` SELECT TENANT, YEAR(DATE), SUM(Sales) AS `TOTAL SALES` FROM TenantSales GROUP BY TENANT, YEAR(DATE) ```
One approach is to use [dynamic crosstab](http://www.sqlservercentral.com/articles/Crosstab/65048/): [**SQL Fiddle**](http://sqlfiddle.com/#!3/16b4d3/1/0) ``` DECLARE @sql NVARCHAR(MAX) = N'' SELECT @sql = 'SELECT Tenant' + CHAR(10) SELECT @sql = @sql + ' , SUM(CASE WHEN [Year] = ' + CONVERT(VARCHAR(4), yr) +...
SQL Query to Dynamically Display Sales In a Yearly Basis
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am new to this, so I apologize upfront for any confusion/frustration. I appreciate any help that I can get! I have a table (**MainTable**) that I have created two views with (**GoodTable** and **BadTable**). * Each table has 4 columns (*ID*, *UserID*, *key*, *value*). * ID is the Primary Key, but * UserID can repea...
You've said "**Main table is find the IDs that are in the BAD table, and update the values from the value column of the GOOD table, based on a match of UserID AND a LIKE match with the key column, into the MAIN table.**" so your sample result is wrong... We will update the 2 and 5 ID from MainTable right? because it i...
You can use the Coalesce function, which returns the first non-null argument, giving it the value column from both tables, e.g. ``` UPDATE MainTable SET value = (SELECT COALESCE(GoodTable.value, MainTable.value) FROM GoodTable WHERE MainTable.UserID = GoodTable.UserID AND MainTable.key LIKE "some%key%specifics"); ```...
SQL to update selected fields in table from view
[ "", "mysql", "sql", "select", "vlookup", "" ]
I have a table as follows ``` -------------------------------- ChildId | ChildName | ParentId | -------------------------------- 1 | A | 0 | -------------------------------- 2 | B | 1 | -------------------------------- 3 | C | 1 | ----------------...
Something like this? ``` SELECT ChildId AS Id, ChildName as Name, (SELECT COUNT(*) FROM TestCountOver T WHERE T.ParentID = O.ChildID) FROM TestCountOver O ``` but that would give you all the nodes plus children who shouldn't be part of the hierarchy If you want only nodes with children then use a cte ``` ;WITH CTE...
This will do the trick: ``` select t1.childid, t1.childname, count(*) as childs from table t1 join table t2 on t1.childid = t2.parentid group by t1.childid, t1.childname ```
SQL Select and Count Statement
[ "", "sql", "sql-server", "" ]
I am interested to pull a data where a task was completed in last six months. The problem is I am interested to look only at the data which is completed between 06:00 AM to 09:00 PM. I am not sure how can I incorporate the time condition within my SQL statement. Can someone help me out here? My simple SQL Code is lik...
Just use the [DATEPART function](https://msdn.microsoft.com/en-us/library/ms174420.aspx): ``` Select TimeTaskCompleted, Task From Task Where TimeTaskCompleted between ‘07/01/2015’ and ‘09/30/2015’ AND DATEPART(hh,TimeTaskCompleted) between 6 and 20 --24 hour time ``` [SQLFiddle](http://sqlfiddle.com/#!3/9eecb7/6121/...
Some comments. You shouldn't use `between` with date/time columns, because it is confusing. Your expression does not find tasks that are completed on 2015-09-30. I assume the intention is to include the last day of September. A better way to write the query is with explicit inequalities and to use ISO standard date fo...
SQL Server: How to bound a data pull to a specific time Interval?
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have prepared an SQL query that I will have to run on several databases (Oracle and Sybase) where some data might be stored differently. I have noticed that one of the differences in data storage is the blank string. For example, in the column `PRODUCT_TYPE` below, please have a look at the second record: [![enter ...
You can use `trim` on the column. ``` where trim(product_type) is null ``` The above is not DBMS-independent, since Sybase does not provide the `trim` function. However, the below approach will work both in Sybase and Oracle: ``` where rtrim(ltrim(product_type)) is null ```
You can use the replace statement you've tried but you should test for "is null" instead of ='' ``` WHERE REPLACE(PRODUCT_TYPE,' ','') is null ``` See also: [null vs empty string in Oracle](https://stackoverflow.com/questions/13278773/null-vs-empty-string-in-oracle)
SQL string comparison -how to ignore blank spaces
[ "", "sql", "oracle", "" ]
Can I put `like` expression into `SQL` statement like this? ``` select @Count = SUM(cast(Value as int)) from tTag where Name like '[Car],[Truck],[Bike]' ```
If you are searching for whole words use: ``` where Name = 'Car' or Name = 'Truck' or Name = 'Bike' --or where Name = '[Car]' or Name = '[Truck]' or Name = '[Bike]' --or where Name in ('Car', 'Truck', 'Bike') --or where Name in ('[Car]', '[Truck]', '[Bike]') ``` If you are searching as parts of words then use: ``` w...
I hope you will add *wildcards* in `like` operator else you can use `IN` operator. Try this. ``` Select @Count = SUM(cast(Value as int)) from tTag where Name like '[Car]' or Name like '[Truck]' or Name like '[Bike]' ```
sql "like" expression
[ "", "sql", "sql-server", "t-sql", "" ]
Is it possible to select distinct company names from the customer table but also displaying the iD's related? at the minute I'm using ``` SELECT company,id, COUNT(*) as count FROM customers GROUP BY company HAVING COUNT(*) > 1; ``` which returns ``` MyDuplicateCompany1 64 2 MyDuplicateCompany2 20 3 MyDuplicateCom...
You can use `GROUP_CONCAT(id)` to concat your id by comma, your query should be: ``` SELECT company, GROUP_CONCAT(id) as ids, COUNT(id) as cant FROM customers GROUP BY company HAVING cant > 1 ``` You can test the query with this ``` CREATE TABLE IF NOT EXISTS `customers` ( `id` int(11) NOT NULL, `company` varcha...
Not sure if this would be acceptable but there's a function in mySQL which allows you to combine multiple rows into one [Group\_Concat(Field)](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat), but show the distinct values for each record for columns specified (like ID in this case) ...
How select data from distinct Companies in the same row?
[ "", "mysql", "sql", "database", "select", "" ]
Table of surnames in a reference list and I need to find the average number of times a surname appears in the list, I have used the command: ``` SELECT column5, COUNT(*) FROM table1 GROUP BY column5 ``` to get a list of occurrences but there are over 800 in my database so I can manually find an average So some author...
To find the "average number of books per author", you must select the total number of books divided by the total number of authors: ``` SELECT CAST(COUNT(*) AS DECIMAL) / COUNT(DISTINCT column5) FROM table1; ``` Note: I used the `CAST ... AS DECIMAL` syntax to make the result show as a decimal instead of being trunca...
It is allowed to compose (i.e. nest) aggregate functions, so why not simply this: ``` SELECT AVG(COUNT(*)) average_occurrences FROM table1 GROUP BY column5 ```
How to find average number of occurences (Oracle)
[ "", "sql", "oracle", "" ]
MS SQL Server 2008R2 Management Studio I am running a `SELECT` on two tables. I'll simplify it to the part where I'm having trouble. I need to modify the `SELECT` results to a certain format for a data import. My `CASE` statement works fine until I get to the point that I need to base the `WHEN ... THEN...` on a diffe...
You were close but I think this is what you are looking for. The fact that they are in different tables really doesn't matter to the CASE, just the JOIN: ``` SELECT name, Case WHEN Table1.tag = 'Y' then CODES.Desc ELSE 'Other String' END as description FROM TABLE1 join CODES on TABLE1.code = CODES.code ```
I can't comment on a post yet. But why have a code table with a code description if you're going to change the description anyways? Instead, you should just modify the current description in that table or add a column with the secondary description you need. Then the case statement is a lot less complex. ``` CASE ...
select CASE statement based on two tables
[ "", "sql", "sql-server", "select", "case", "" ]
I have a table where I have to get top 10 in each category based on the amount spent by a person in that category. My sample data is ``` person category amount roger perfume 20 jim perfume 50 joe tv 5 jim tv 25 kathy car 40 alicia perfume 100 ``` I gotta get this in one query. I k...
Use variables: ``` SELECT person, category, amount FROM ( SELECT person, category, amount, @rn := IF(@cat = category, @rn+1, IF(@cat := category, 1, 1)) AS rn FROM mytable CROSS JOIN (SELECT @rn := 0, @cat := '') AS vars ORDER BY category, amount DESC) AS t WHERE t.rn <= 10 ``` `@r...
since category appears multiple times, you will need to group by category, summing up the amounts. Then sort on it and keep the number of rows you want. I think the following will work: ``` SELECT category, SUM(amount) as amount FROM mytable GROUP BY category ORDER BY SUM(amount) DESC LIMIT 10 ```
top 10 by category mysql
[ "", "mysql", "sql", "mysql-variables", "" ]
As I tried to create new table from existing 2 table with specific column name in oracle. I tried below code ``` CREATE TABLE D_T1 AS SELECT a.col1, a.col2, a.col3, a.col4, a.col5, b.col6, b.col7, b.col8 FROM db1.table1 a INNER JOIN db1.table2 b ON (a.col1 = b.colNum AND a.col2 = b.colnum1) ``` But I get er...
Ignoring the other errors you seem to have introduced by retyping the code, you've shown that you do have a duplicate column, which is what the error is telling you: ``` a.VALIDFLAG, b.VALIDFLAG ``` You seem to be under the impression that the table (alias) prefix makes the column names in the projection unique. They...
To be completely honest, that query is a mess. You've got several errors in your SQL statement: ``` CREATE TABLE AS SELECT ``` The table name is missing - this should be ``` CREATE TABLE my_new_table AS SELECT ``` to create a new table named my\_new\_table. ``` a.ALIDFLAG,b,VALIDFLAG, ``` I've got a suspicion tha...
CREATE TABLE failed ORA 00957 Duplicate column name
[ "", "sql", "oracle", "oracle11g", "ddl", "" ]
I am trying to find a way to manipulate values that are returned as part of a query. Basically, if the value is less than 255 char, use this value but if value is more than 255 characters, need to return a string "value more than 255 characters" instead of actual value. I need to achieve this a part of SQL query. Appre...
Assuming SQL Server, try this which uses the [`LEN`](https://msdn.microsoft.com/en-us/library/ms190329.aspx) function combined with a [`CASE`](https://msdn.microsoft.com/en-us/library/ms181765.aspx): ``` SELECT CASE WHEN LEN(StringColumn) > 255 THEN 'value more than 255 characters' ELSE StringCo...
The following `CASE` pattern will work with most systems: ``` SELECT CASE WHEN LENGTH(someCol) <= 255 THEN someCol ELSE "value more than 255 characters" END AS ColName FROM TableName ``` Take note that string functions differ depending on your database software. See: * **[`CHARACTER_LENGTH`](https:/...
SQL for string more than 255 chars
[ "", "sql", "sql-server", "database", "oracle", "" ]
Hi i want to change the default datetime type in sql server. I have already table who has rows and i dont want to delete them. Now the datetime format that had rows is: `2015-11-16 09:04:06.000` and i want to change in `16.11.2015 09:04:06` and every new row that i insert i want to take this datetime format.
SQL Server does not store `DATETIME` values in the way you're thinking it does. The value that you see is simply what the DBMS is choosing to render the data as. If you wish to change the display of the `DATETIME` type, you can use the `FORMAT()` built-in function in `SQL Server 2012` or later versions, but keep in min...
There is no such thing as format of the `DATETIME` data type, it has no format by nature, formatted is the text representation you can set when converting to `VARCHAR` or some visualization settings of the client / IDE. If you, however, want to be able to insert dates using string representations that are alternativel...
Change Datetime format in Microsoft Sql Server 2012
[ "", "sql", "sql-server", "datetime", "sql-server-2012", "format", "" ]
``` SELECT CAST(‘2015-01-01 14:48:34.69’ AS DATETIME) FirstVal, CAST(‘2015-01-01 14:48:34:69’ AS DATETIME) SecondVal ``` When we look at the answer, there is a difference between the milliseconds part in the result set, whereas you can notice that in the `SELECT` statement I have specified different millisecon...
`DATETIME` has an accuracy of 3.33ms - you will **never** see a value with a `.069` stored in a `DATETIME` - you only ever get `.xx0`, `.xx3` and `.xx7`. If you need millisecond precision, use `DATETIME2(3)` (introduced in SQL Server **2008**) as your datatype instead.
you have selected Diff Value in First Value:-34.69 and Second Value :- 34:69. you can see both value diff so out put diff.
millisecond in sql tsql
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I want to create a **script** for my **oracle DB**, which **drops tables**. If the table does not exist, the script won't exit as fail, just print a text: "*does not exists*". The script is the following: ``` BEGIN EXECUTE IMMEDIATE 'DROP TABLE mytable'; DBMS_Output.Put_Line(' table dropped'); EXCEPTION WHEN ...
Yes, you can declare a "temporary" procedure in an anonymous PL/SQL block: ``` DECLARE PROCEDURE drop_if_exists(p_tablename VARCHAR) IS BEGIN EXECUTE IMMEDIATE 'DROP TABLE '||p_tablename; DBMS_Output.Put_Line(' table dropped'); EXCEPTION WHEN OTHERS THEN IF SQLCODE = -942 THEN DBM...
in `execute immediate` you need add name of database object. here's the script ``` create table t1 (col1 int); create table t2 (col1 int); create procedure drop_my_table(av_name varchar2) as begin EXECUTE IMMEDIATE 'DROP TABLE '||av_name; DBMS_Output.Put_Line(' table dropped'); EXCEPTION WHEN OTHERS THEN ...
How to create a procedure in an oracle sql script and use it inside the script?
[ "", "sql", "oracle", "function", "procedure", "sql-scripts", "" ]
At least with MariaDB v10.x, why truth clauses with left joins doesn't work as I expect when there is `NULL` return value? The below works: ``` SELECT u.id FROM user u INNER JOIN role r on r.user = u.id INNER JOIN customer c ON c.id = r.customer LEFT JOIN customer_subclass cs ON cs.customer = c.i...
The thing is that engine is build upon three-valued predicate logic. If predicate compares two non null values then it can be evaluated to `TRUE` or `FALSE`. If at least one of then is `NULL` then predicate evaluates to third logical value - `UNKNOWN`. Now what happens in `WHERE` clause? It is designed in such a way t...
Because comparing with `null` results in neither `true` nor `false`. It is **unknown**. And that is true for all DB engines I know. The `is` operator handles especially `null` values which you already use.
Left join weirdness
[ "", "sql", "left-join", "" ]
I am trying to create a query that displays the average attendance by conference when at least one team was in a game. [Relationships](https://i.stack.imgur.com/5FI8c.png) [![enter image description here](https://i.stack.imgur.com/5FI8c.png)](https://i.stack.imgur.com/5FI8c.png) this is very close to what im looking ...
Get a distinct list of the games by conference in a derived query, then do your average. ``` SELECT ConferenceName, AVG(Attendance) AS AVG_ATT FROM ( SELECT DISTINCT GameID, Conference.ConferenceName, Game.Attendance FROM ( Conference INNER JOIN Sc...
USE `UNION` to discard duplicated first before doing the average ``` SELECT Game.GameID Game.Attendance Conference.ConferenceName FROM ( Conference INNER JOIN School ON Conference.[ConferenceID] = School.[ConferenceID] ) INNER JOIN Game ON ( School.[SchoolID]...
SQL MS Access join help average not correct
[ "", "sql", "ms-access", "join", "average", "" ]
I have a table in Oracle which contains : ``` id | month | payment | rev ---------------------------- A | 1 | 10 | 0 A | 2 | 20 | 0 A | 2 | 30 | 1 A | 3 | 40 | 0 A | 4 | 50 | 0 A | 4 | 60 | 1 A | 4 | 70 | 2 ``` I want to calculate th...
This presupposes you don't have more than one value per rev. If that's not the case, then you probably want a `row_number` analytic instead of `max`. ``` with latest as ( select id, month, payment, rev, max (rev) over (partition by id, month) as max_rev from table1 ) select sum (payment) from latest where ...
You can also use below. ``` select id,sum(payment) as value from ( select id,month,max(payment) from table1 group by id,month ) group by id ``` `Edit`: for checking greatest rev value ``` select id,sum(payment) as value from ( select id,month,rev,payment ,row_number() over (partition by id,m...
Use SUM function in oracle
[ "", "sql", "oracle", "sum", "analytics", "" ]
I have a data frame like below ``` col1 col2 col3 A Z 10 A Y 8 A Z 15 B X 11 B Z 7 C Y 10 D Z 11 D Y 14 D L 16 ``` I have to select, for each `distinct col1` which of the `col2` have `max(col3)` Output d...
We can use `data.table`. We convert the 'data.frame' to 'data.table' (`setDT(df1)`), grouped by 'col1', we subset the data.table (`.SD`) based on the index of max value of 'col3' ``` library(data.table) setDT(df1)[, .SD[which.max(col3)], col1] # col1 col2 col3 #1: A Z 15 #2: B X 11 #3: C Y ...
Another way of doing in MySQL. Here is the [**SQLFiddle Demo**](http://sqlfiddle.com/#!9/d631f/1) **Output** : =>[![enter image description here](https://i.stack.imgur.com/Utli4.png)](https://i.stack.imgur.com/Utli4.png) ``` SELECT T1.* FROM table_name T1 INNER JOIN (SELECT col1,MAX(col3) AS Max_col3 FROM table_nam...
How to find the distinct of one column based on other columns
[ "", "mysql", "sql", "r", "groupwise-maximum", "" ]
I have a query like : ``` SELECT * FROM mytable WHERE (`field1` LIKE '%search%' OR `field2` LIKE '%search%' OR `field3` LIKE '%search%') ``` Keyword `search` can be any other words. How can i set priority to this query ? I want to search first in `field1`, after in `field2` and then in `field3`. So if I find my key...
You can do it with order by: ``` SELECT * FROM mytable WHERE (`field1` LIKE '%search%' OR `field2` LIKE '%search%' OR `field3` LIKE '%search%') ORDER BY CASE WHEN `field1` LIKE '%search%' THEN 1 WHEN `field2` LIKE '%search%' THEN 2 WHEN `field3` LIKE '%search%' THEN 3 ELSE 4 END ```
You'd better split query and union them. ``` select * from ( SELECT 1 as s, * FROM mytable WHERE ('field1' LIKE '%search%') union SELECT 2 as s, * FROM mytable WHERE ('field2' LIKE '%search%') union SELECT 3 as s, * FROM mytable WHERE ('field3' LIKE '%search%') ) a order by s ```
SQL priority condition
[ "", "sql", "" ]
I have a table like so. ``` ID Name Year 404 Matt 2015 406 Matt 1 2015 304 Matt 2 2015 334 Matt3 2015 655 Matt4 2015 923 Matt 5 2015 856 Banana 2015 274 Banana 2 2015 716 Banana7 2015 472 Orangutan 2015 844 OrangutanA 2015 159 Orangutan 2 2015 739 B...
**If** the rule you're trying to apply is simply that you want to remove a single digit or uppercase character at the end of the value, with or without a single preceding space; and your real data is less ambiguous than speculated in comments and the complications and edge cases really don't apply; then you can use a f...
The following query builds triples from the ids of records containing the base and the derived names and the short name (base and derived in terms of prefixes of "Name" values as defined below). The Assumptions (and these are restrictive !) are that: * any pair of derived Names have a common prefix * that common pref...
SQL Give fields a single name when there are multiple variances with numbers
[ "", "sql", "oracle", "" ]
I have below Oracle Command to insert a row but before that I am supposed to check whether that row exists in table and if exists do nothing. ``` IF NOT EXISTS(SELECT * FROM table1 WHERE Value1 ='Value 1' AND Value2='Value 2' AND Value3='Value 3' AND Value4='Value 4') BEGIN INSERT INTO table1 ( Value1, Value2, ...
The simplest possible approach (not the most efficient) would be to do something like ``` DECLARE l_cnt pls_integer; BEGIN SELECT COUNT(*) INTO l_cnt FROM table_name WHERE col1 = 'value1' AND col2 = 'value2' ... IF( l_cnt = 0 ) THEN <<your insert>> END IF; END; ``` You can do the `...
I usually use [MERGE](https://oracle-base.com/articles/9i/merge-statement) for this kind of problems. It is pure SQL, simple and straightforward. In your example, it would be like this: ``` MERGE table1 T1 USING (SELECT 'Value 1' Value1, 'Value 2' Value2, 'Value 3' Value3, 'Value 4' Value4 FROM DUAL) T2 ON (T1.Value1 ...
If Not Exists Insert fails with error Unknown command for If Not Exists statement
[ "", "sql", "oracle", "" ]
I am new with SQL in general and with Oracle in particular. I created a collection of dates => **dates** consisted of **date (i)** I have a table **table** with columns **date** and **revenue**. When I make query ``` select sum(revenue) from table where date between date(i) and date(i+1) ``` I cant get correct num...
The variables in your collection are already dates and you're converting them again into dates (that's something you should never do). When you convert a DATE into a DATE, the variable is previously converted into a string by Oracle using the default date format mask. You can see yours with: ``` SELECT value FROM nls_...
Why do you convert a `DATE` value into a `DATE` value? When you do `to_date(date(i),'dd-mm-yyyy')` then following happens: 1. Date value `date(i)` is converted implicitly to a string using the current `NLS_DATE_FORMAT` format. 2. Then this string is converted back to a `DATE` value using the format `dd-mm-yyyy` So, ...
Oracle SQL - how dates are compared
[ "", "sql", "oracle", "date", "comparison", "" ]
Currently my table structire for table SHIFT is as follow: ``` ID Name Start End 1 Shift1 06:00 14:00 2 Shift2 14:00 22:00 3 Shift3 22:00 06:00 ``` Now I pass parameter to this query in hour like 11 or 15 or 22 or 03 For that parameter, I would like to get the result that in...
``` SELECT * FROM shift WHERE ( left(START,2) > left(END,2) AND ('[Param.1]' >= left(START,2) OR '[Param.1]' < left(END,2)) ) OR ( left(START,2) < left(END,2) AND '[Param.1]' >= left(START,2) AND '[Param.1]' < left(END,2) ) ``` [![enter image description here](https://i.stack.img...
Simplest way is most likely to convert the times into dates, and if the end date is earlier than start, then add one day. You could use time datatype as input too, instead of just hour, but this is now an example with int: ``` declare @hour int, @date datetime set @hour = 3 set @date = convert(datetime, convert(varc...
Difficulty in getting Shift Value in SQL Query
[ "", "sql", "sql-server", "" ]
I have a table listing student grade, ``` AG T1 T2 T3 L0011001 A B A L0011002 A B B L0011003 A A C L0011004 A A C ``` I want output for AG like this: ``` L0011001 2A 1B L0011002 1A 2B L0011003 2A 1C L0...
Your data is in a really, really bad format. You should have one row per "T" and per student. However, sometimes we are stuck with bad data formats. You can do what you want with `iif()`: ``` select ag, (iif(t1 = 'A', 1, 0) + iif(t2 = 'A', 1, 0) + iif(t2 = 'A', 1, 0)) as A_s, (iif(t1 = 'B', 1, 0) + iif(...
You might like to consider a union query and a crosstab, the output is not exactly as you wish, but it does make sense. ``` TRANSFORM Count(qry.ag) AS countofag SELECT qry.ag FROM (SELECT tbl.ag, tbl.t1 FROM tbl UNION ALL SELECT tbl.ag, tbl.t2 FROM tb...
Group by and multiple colum count and sum
[ "", "sql", "ms-access", "count", "sum", "" ]
I am trying to figure out this question on a practice page online with the following tables: **Question:** For all cases in which the same customer rated the same product more than once, and in some point in time gave it a lower rating than before, return the customer name, the name of the product, and the lowest star...
Here is what I have so far (without sample data): ``` SELECT Customer.customer_name, Product.product_name, MIN(Rating.rating_stars) FROM Rating JOIN Product ON Rating.prod_id = Product.prod_id JOIN Customer ON Rating.cust_id = Customer.prod_id GROUP BY Customer.customer_name, Product.product_name HAVING CO...
This query will return the minimum rating stars of a product that has been reviewed more than once by the same customer, with any of the newer ratings lower than an older rating: ``` SELECT r1.prod_id, r1.cust_id, MIN(r1.rating_star) AS min_rating FROM rating r1 INNER JOIN rating r2 ON r1.prod_id=r2.prod_id ...
MySQL nested selection
[ "", "mysql", "sql", "database", "psql", "" ]
I am selecting the column names from a table with the following query. ``` SELECT column_name FROM all_tab_cols WHERE table_name = 'TBL1' AND column_name like 'INFORMATION%' order by column_name ``` The resultset is like ``` INFORMATION1 INFORMATION10 INFORMATION11 INFORMATION12 . . . INFORMATION2 INFORMATION20 `...
Order first by string length, then by string: ``` SELECT column_name FROM all_tab_cols WHERE table_name = 'TBL1' AND column_name LIKE 'INFORMATION%' ORDER BY LENGTH(column_name), column_name; ``` `SqlFiddleDemo`
> How to achieve this without being much cpu-intense? **REGEX** is CPU intensive and slower as compared to old **SUBSTR**. Use **SUBSTR** to get the digit part and use it in the **ORDER BY**. Also, since you are filtering rows only with `INFORMATION` string, you need only one ORDER BY on the digit part. ``` SELECT c...
Alphanumeric sorting in Oracle
[ "", "sql", "database", "oracle", "sorting", "" ]
Let's say I have a table t1 with only one column: `id`, and I have a table t2 with two columns: `id` and `Memo`. I need to select those `id` from t1, for which there is NO row in t2 that satisfies both of the following two conditions `t1.id = t2.id` and `t2.Memo = 'myText'`. How can I do that? I have tried using `join`...
``` SELECT * FROM t1 WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE t2.id = t1.id AND t2.Memo = 'myText') ```
One way to do it is using `LEFT JOIN`: ``` select id from t1 left join t2 on t1.id = t2.id and t2.Memo = 'myText' where t2.id is null ```
SQL: select from t1 all rows for which there's no corresponding in t2
[ "", "sql", "" ]
I have dates and I want to retrieve periods of dates. I have table LeaveMaster: ``` ID LeaveDate 1 23/09/2015 1 24/09/2015 1 25/09/2015 1 27/09/2015 1 29/09/2015 1 30/09/2015 1 01/10/2015 1 02/10/2015 1 04/10/2015 ``` The result should be: ``` ID StartDate EndDate 1 ...
The trick to find consecutive values is to build a group key by subtracting the records position from the value. Then group by that key and show its min and max value. ``` select id, min(leavedate) as startdate, max(leavedate) as enddate from ( select id, leavedate, dateadd(day, - row_number() over (pa...
You can use the following query: ``` SELECT ID, MIN(LeaveDate) AS StartDate, MAX(LeaveDate) AS EndDate FROM ( SELECT ID, LeaveDate, DATEDIFF(d, '19000101', LeaveDate) - ROW_NUMBER() OVER (ORDER BY LeaveDate) AS grp FROM mytable ) AS t GROUP BY ID, grp ``` `grp` is used to identify...
Get Periods of dates from SQL Query
[ "", "sql", "sql-server", "database", "datetime", "" ]
Consider the simple table representing the history of a race: ``` laphistory(race_id integer,lap_number integer,pos_number integer, driver_label text,id integer NOT NULL,CONSTRAINT id PRIMARY KEY (id) ...) ``` Now, consider the following example: ``` race_id;lap_number;pos_number;driver_label;id 1 ;1 ...
PostgreSQL's [`window function`](http://www.postgresql.org/docs/9.4/static/tutorial-window.html) can be apply to get the desired output: ``` SELECT * FROM ( SELECT * ,row_number() OVER ( PARTITION BY driver_label ORDER BY lap_number DESC ) AS rank FROM race ) t WHERE rank = ...
Simple GROUP BY should do what you need: ``` select race_id, lap_number, min(id) from foo group by race_id, lap_number order by race_id asc, lap_number desc ```
SQL - Remove tuples from a select based on occurences on a specific column
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I am using the Mondial database schema and am trying to find: For each country, find city that has the highest population and the city's population. Right now I have: ``` SELECT Country.Name, city.name, MAX(city.population) Population FROM city Join Country On Country.Code=City.Country WHERE city.population IS NOT NU...
Use analytical functions. Something like this should work (untested): ``` select country.name, city.name, city.population from country join ( select country, name, population, row_number() over ( partition by population desc) as rn from city ) city on city.country = country.code and...
Don't know in oracle but if done in SQL Server it can be done like this: ``` Select * from (select Country.Name, city.name, city.population, ROW_NUMBER() over(partition by Country.Name order by Country.Name,city.population desc) RowNum from Country inner join city city ...
For each country, find city that has the highest population and the city's population
[ "", "sql", "database", "oracle", "" ]
I want to update a table column with row number. Each row in `empid` column should update with related row number. I tried following query. ``` UPDATE employee SET empid = row_number(); ``` But this is not working. Any idea?
First, this is not the correct syntax for the `row_number()` function, since you're missing the `over` clause (resulting in an ORA-30484 error). Even if it was, this would not work, as you cannot directly use window functions in a `set` clause (resulting in an ORA-30483 error). For this usecase, however, you could jus...
You could do something like the following. You can change the ORDER BY order the rows if needed. ``` UPDATE emp SET empid = emp.RowNum FROM (SELECT empid, ROW_NUMBER() OVER (ORDER BY empid) AS rowNum FROM employee) emp ```
Update Oracle table column with row number
[ "", "sql", "oracle", "sql-update", "oracle10g", "" ]
Cannot truncate a table referenced in a foreign key constraint. What should i do first to enable truncate? details: ``` ( `guacamole`.`guacamole_connection_history`, CONSTRAINT `guacamole_connection_history_ibfk_2` FOREIGN KEY (`connection_id`) REFERENCES `guacamole`.`guacamole_connection` (`connec...
Why not add a constraint adding `ON DELETE CASCADE` and `ON UPDATE CASCADE`? Then all you need to do is `TRUNCATE guacamole_connection CASCADE` Example: ``` ALTER TABLE guacamole_connection_history ADD CONSTRAINT guacamole_connection_history_cascade_delete FOREIGN KEY (connection_id) REFERENCES g...
You can do truncate by skipping foreign key checks. ``` SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table1; SET FOREIGN_KEY_CHECKS = 1; ```
Cannot truncate a table referenced in a foreign key constraint
[ "", "mysql", "sql", "" ]
When i run my query i receive the following message: ``` Invalid column name 'column1' ``` query: ``` SELECT TOP 1 * From ( (select Top 2 convert(datetime,column1,101) AS TEST from table1 ORDER BY column1 DESC) X ORDER BY column1) ```
``` SELECT TOP 1 TEST From ( SELECT Top 2 convert(datetime,column1,101) AS TEST, column1 // <- include column1 FROM table1 ORDER BY column1 DESC ) X ORDER BY column1 ASC ```
Perhaps the simplest way is to move the conversion out of the subquery: ``` SELECT TOP 1 convert(datetime, column1, 101) as test From (select Top 2 t.* from table1 order by column1 desc ) X ORDER BY column1; ``` Or, if your database supports it, use the ANSI standard `FETCH`/`OFFS...
"Invalid column name" ORDER BY
[ "", "sql", "" ]
there is a table column message value is ``` Command triggerEvent started Command stopService stopped Command startService started Command executeCommand running ...... ``` Now I want to select the command name, i.e. triggerEvent, stopService, startService I try to use oracle substr and instr to get them but failed....
You could do it with shorter code using **REGEXP\_SUBSTR**. For example, ``` SQL> WITH sample_data AS( 2 SELECT 'Command triggerEvent started' str FROM dual UNION ALL 3 SELECT 'Command stopService stopped' str FROM dual UNION ALL 4 SELECT 'Command startService started' str FROM dual UNION ALL 5 SELECT 'Co...
This will give you the second word from your message ``` with event(message) as ( select 'command triggerEvent started' from dual union select 'Command stopService stopped' from dual) --recreate table --query start select trim(regexp_substr(message,'[[:alpha:]]+ ',1,2)) command FROM event ```
How to use substr in Oracle ?
[ "", "sql", "database", "oracle", "" ]
I am trying to create a view in SQL Server 2012 that excludes columns where the entry is null (represent by 0 here so it's easier to read). My base data is this ``` ╔════╦══════╦══════╦══════╦══════╦══════╗ ║ ID ║ Col1 ║ Col2 ║ Col3 ║ Col4 ║ Col5 ║ ╠════╬══════╬══════╬══════╬══════╬══════╣ ║ 1 ║ 1 ║ 0 ║ 0 ║ ...
You cannot really do what you want to do. Queries, views, and user-defined functions returns a specific set of columns. The set of columns is defined in advance. So, you cannot remove them. You *could* create a dynamic query that only included columns that are currently not `NULL`. Or, you could create an XML data str...
If you drop the requirement where the result excludes columns where it is all null, you can do this with an [UNPIVOT and then a PIVOT](https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx).
Exclude columns with Null
[ "", "sql", "sql-server", "" ]
I am trying to update a table with two column first is **marketplace\_fee** and other is s**ettlment\_value**, for updating **marketplace\_fee**, need to calculate some column and for calculate **settlment\_value** need marketplace\_fee. The problem is: When run the update query first time it only update marketplac...
Your bracketsfull expression can be written down in much simpler form. Use it twice in both assignments: ``` update fk_pay_cal set marketplace_fee = (totalprice * commission/100 + shippingcharge + fixed_fee) * (service_tax /100+ 1), settlment_value = totalprice - (totalprice *...
One method is to do the calculation in a CTE. This is most helpful if you have a unique id or primary key on the data: ``` with newvals as ( select pc.*, (((((totalprice * commission )/100) + shippingcharge + fixed_fee))+ ((((totalprice * commission )/100) + shippingcharge + ...
update multiple column in table using same table data in postgres?
[ "", "sql", "postgresql", "sql-update", "" ]
I'm trying to find an object by checking for several of its relations. ``` Loan.joins(:credit_memo_attributes) .where(credit_memo_attributes: {name: 'pr2_gtx1_y', value: '2014'}) .where(credit_memo_attributes: {name: 'pr1_gtx1_y', value: '2013'}) .where(credit_memo_attributes: {name: 'tx1_y', value: '2014'...
# Update: Based on comments I believe you want multiple joins in your criteria. You can do that like this: ``` attr_1 = {name: 'pr2_gtx1_y', value: '2014'} attr_2 = {name: 'pr1_gtx1_y', value: '2013'} attr_3 = {name: 'tx1_y', value: '2014'} Loan.something_cool(attr_1, attr_2, attr_3) class Loan < ActiveRecord::Base...
You can put all names and values into array like ids and years and pass those into where clause like this. Active Record will query all the values in the array. ``` Loan.joins(:credit_memo_attributes) .where(credit_memo_attributes: {name: ids, value: years}) ``` Personally I'm still learning active record, in thi...
ActiveRecord has_many with multiple conditions
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
Is it possible to create a lock for a specific value in an INSERT-statement in PostgreSQL? Lets say, I have this table: ``` CREATE TABLE IF NOT EXISTS bookings ( bookingID SERIAL PRIMARY KEY, tableID integer REFERENCES tables ON DELETE CASCADE, startTime timestamp NOT NULL, endTime timestamp NOT NULL, ); ...
The question is, why do you want to block other inserts for this table? For me it looks like you want to be sure there are no intersecting intervals for the same tableID. Probably you check this in Java code and you don't want other inserts to interfere with the check. If so, you need no locks at all: use [EXCLUDE](h...
What you want is called predicate locking. It is not directly supported by PostgreSQL, but advisory locking as described by @stas.yaranov is a good way around that. As @EgorRogov points out, if possible you should remove the need for locking entirely by using appropriate constraints. Another option nobody's mentioned ...
PostgreSQL lock INSERTS with specific values possible?
[ "", "sql", "postgresql", "sql-insert", "" ]
I have table something like this: ``` date|status|value ``` date is date, status is 1 for pending, 2 to confirmed and value is value of order I want to get 3 columns: ``` date|#status pending|#status pending+confirmed ``` example of data: ``` +------------+-----------------+-----------------+ | date | statu...
You can use `CASE WHEN`, To get the expected output,you have given. ``` SELECT `date`, (SUM(CASE WHEN `status`=1 THEN 1 ELSE 0 END)) AS Confirmed, (SUM(CASE WHEN `status`=1 OR `status`=2 THEN 1 ELSE 0 END)) AS Confirmed_Pending FROM table_name GROUP BY DATE(`date`) DESC ``` Hope this helps.
You are missing an `ON` clause in your `INNER JOIN`. Or, since in your case the column you join on is the same on both sides, you can use `USING`: ``` SELECT array1.DATE ,array1.confirmed ,array2.total FROM ( SELECT DATE (DATE) AS DATE ,count(value) AS confirmed FROM Orders WHERE STATUS = '...
How merge two select with different WHERE and special conditions
[ "", "mysql", "sql", "inner-join", "" ]
How would you go about transferring data into an object table? Say you have a table: ``` create table thisTable( column1 varchar2(20), column2 varchar2(20), column3 varchar2(20) ) / ``` And you have a new object table: ``` create table oo_thisTable( object1 object1_t ) / create type object1_t as obj...
No need of using **PL/SQL**, you could do it in pure **SQL**. ``` INSERT INTO oo_thistable SELECT object1_t(column1, column2, column3) FROM thistable; ``` **Demo** **Create** the required **type** and **tables**: ``` SQL> create table thisTable( 2 column1 varchar2(20), 3 column2 varchar2(20), 4 ...
I have written some sequential steps for the issue described. Please try this and let me know if this helps. ``` SQL> set sqlbl on; SQL> set define off; SQL> set timing on; SQL> DROP TYPE TEST_TAB; Type dropped. Elapsed: 00:00:00.90 SQL> SQL> DROP TYPE Test_oo; Type dropped. Elapsed: 00:00:00.58 SQL> CREATE OR RE...
Store data from table into object table
[ "", "sql", "database", "oracle", "plsql", "object-oriented-database", "" ]
I have some big tables (30+ columns) with `NOT NULL` constraints. I would like to change all those constraints to `NULL`. To do it for a single column I can use ``` ALTER TABLE <your table> MODIFY <column name> NULL; ``` Is there a way to do it for all columns in one request ? Or should I copy/paste this line for all...
> Is there a way to do it for all columns in one request ? Yes. By (ab)using **EXECUTE IMMEDIATE** in **PL/SQL**. Loop through all the columns by querying **USER\_TAB\_COLUMNS** view. For example, ``` FOR i IN ( SELECT * FROM user_tab_columns WHERE table_name = '<TABLE_NAME>' AND NULLABLE='N' ) LOOP EXECUTE IMMEDI...
For a single table you can issue a single `alter table` command to set the listed columns to allow `null`, which is a little more efficient than running one at a time, but you still have to list every column. ``` alter table ... modify ( col1 null, col1 null, col3 null); ``` If you were applying `not null` cons...
How to change Null constraint for all columns ?
[ "", "sql", "oracle", "" ]
I have data that looks like this: **Nodes** ``` Name Attribute Date 14 A1 11-OCT-2015 14 A2 7-Nov-2015 12 B1 11-Nov-2015 ``` **Vectors** ``` Node V_NAME color Date 14 V1 blue 11-OCT-2015 14 V1 red 10-Nov-2015 14 V2 ...
I use two cte to calculate the most recent row in each category. Then join both. **[SqlFiddleDemo](http://sqlfiddle.com/#!4/8b18c/28)** ``` WITH n_node as ( SELECT "Name", "Attribute", row_number() over (partition by "Name" order by "Date" DESC) rn FROM Nodes ), n_vector as ( SELECT "Node", "...
``` SELECT v.Node, n.Attribute, v.V_NAME, v.color from Nodes n inner join Vector v on n.Name = v.Node and n.Date = v.Date ``` <http://sqlfiddle.com/#!4/d3464/1>
How do I join the most recent row in one table to most recent row in another table (oracle)
[ "", "sql", "oracle", "" ]
I have a select on a table which selects a number ``` SELECT * FROM table ``` And I generates something that looks like ``` | column | | 2 | | 5 | ``` I am wondering if there is a way to turn that 2 and 5 into multiple rows of 2 and 5. So basically ``` | column | | 2 | | 2 | | 5 | | 5 ...
You can do it using a numbers (aka tally) table: ``` SELECT col FROM mytable AS t1 INNER JOIN ( SELECT @rn := @rn + 1 AS num FROM ( SELECT 0 AS n UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNI...
You can grow it exponentially with repeated joins to itself. But what are you really trying to accomplish? ``` select a.* from table a left join table b on 1=1 left join table c on 1=1 ```
Select Number Into Multiple Rows
[ "", "mysql", "sql", "" ]
I have two columns: GRP\_ACCT\_NO, TRANS\_DATE Data is about the transactions made by different accounts. So, GRP\_ACCT\_NO has recurring values and the TRANS\_DATE gives the date, that particular account made a transaction on. I have about 1.5 million records in the data set but only 97k unique accounts. I want to f...
SQL has no concept of order of observations. Use a DATA step. If your data is not already sorted then sort it (create an index). If you just want the second record, even if there are ties then you can just count the records for each account. ``` data second_latest_trans; set project.spend; by GRP_ACCT_NO TRANS_DA...
Your query (apart from the formatting) looks reasonable. I wonder if the `group by` in the subquery is throwing things off. Try this version: ``` proc sql; create table second_latest_trans as Select GRP_ACCT_NO, Max(TRANS_DATE) from project.spend ps where TRANS_DATE < (SELECT max(ps2.TRANS_DATE) ...
Finding the second latest date in SAS
[ "", "sql", "sas", "" ]
So lets say that i have this table ``` language | offer chinese | 1 chinese | 1 english | 1 spanish | 2 spanish | 2 italian | 2 french | 3 ``` and I want the languange that appears most times for each different offer,like this ``` language | offer chinese | 1 spanish | 2 french | 3 ``...
This is one way to do it using `common table expression`s. [SQL Fiddle](http://www.sqlfiddle.com/#!4/ac11a/4) In the first cte, you calculate the counts grouped by offer and language. In the next cte, use `rank` or `row_number` to assign `1` to the offer with the highest language count. Finally, select from the 1st r...
You can use row\_number in oracle for your output. ``` SELECT LANGUAGE ,offer FROM ( SELECT LANGUAGE ,offer ,row_number() OVER ( PARTITION BY offer ORDER BY count(offer) DESC ) AS rno FROM table1 GROUP BY LANGUAGE ...
Oracle Sql getting the value that appears most times for each different value of another column
[ "", "sql", "database", "oracle", "" ]
How to add `minutes(INT)` to the time part of `datetime` ? For example : If I have datetime variable like this : ``` @shift_start_time = 2015-11-01 08:00:00.000 @increase = 30 ``` How to get this result? ``` 2015-11-01 08:30:00.000 ```
Use **[`DATEADD`](https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-2017)**: ``` SELECT DATEADD(mi, @increase, @shift_start_time); ``` **[db<>fiddle demo](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=a2787bd91f6984645276b795aa7f09fe)**
Using dateadd: ``` DATEADD(minute,@increase,@shift_start_time) ``` the first argument can be chosen among: year quarter month dayofyear day week weekday hour minute second millisecond microsecond nanosecond please check <https://learn.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?redirectedfrom=MSDN&v...
How to add minutes to the time part of datetime
[ "", "sql", "sql-server", "datetime", "time", "dateadd", "" ]
We have Non-`Identity` `Column` in our Database Which have a specific value . We have a requirement as below, Whenever a record `insert` into that column, value should be incremented by one. how to handle this in `sql server` ? Thanks for the help.
Well, you can use [`SEQUENCE`](https://msdn.microsoft.com/en-IN/library/ff878370.aspx) statement introduced in SQL Server 2012 brings the method of generating IDs To use it in insert statement, you need to first create sequence like this - ``` CREATE SEQUENCE dbo.Id_Sequence AS INT START WITH 1 INCREMENT ...
Try creating a TRIGGER ``` CREATE TRIGGER incrementValue ON Test FOR Insert AS Update Test set columnvalue = columnvalue +1 where id in (select id from inserted) GO ```
Auto Increment a non-identity Column in sql-server
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
My data looks like: ``` MEDIA_ID | CHANNEL_NAME EH/123A CH-1 EH/123A CH-4 EH/132A CH-5 ES/133B CH-1 ES/133B CH-2 ES/133B CH-5 ``` What i want is: ``` EH/123A | CH-1,CH-4,CH-5 ES/123B | CH-1,CH-2,CH-5 ``` I am using this SQL in Oracle: ``` SELECT DISTINCT PR.MEDIA_ID , LISTAGG(PR.CHANNE...
I think the query you want is: ``` SELECT PR.MEDIA_ID, LISTAGG(PR.CHANNEL_NAME, ', ') WITHIN GROUP (ORDER BY CHANNEL_NAME) AS PREM_CHAN FROM PREM_REPORT PR GROUP BY PR.MEDIA_ITEM; ``` That is, remove `PR.CHANNEL_NAME` from your query. I am not sure why you would get your results with the query you gave. Perhap...
You can remove `GROUP BY` and just add `PARTITION BY`: ``` SELECT DISTINCT PR.MEDIA_ID ,LISTAGG(PR.CHANNEL_NAME, ', ') WITHIN GROUP (ORDER BY CHANNEL_NAME) OVER (PARTITION BY PR.MEDIA_ID) AS PREM_CHAN FROM PREM_REPORT PR; ``` `SqlFiddleDemo` Output: ``` ╔═══════════╦══════════════════╗ ║ MEDIA_ID ║ PREM...
I cant get LISTAGG in Oracle to do as it should?
[ "", "sql", "oracle", "listagg", "" ]
Given an example table definition: ``` school: school_id | school_name -------------+------------ 1 | school1 2 | school2 3 | school3 classroom: classroom_id | has_projector | school_id -------------+---------------+------------- 1 | f | 1 2 ...
I think a simple aggregation with a `having` clause is a bit simpler: ``` select s.school_id from school s join classroom c on s.school_id = c.school_id group by s.school_id having sum(case when has_projector = 't' then 1 else 0 end) = count(*); ```
Left join school to classroom on the school id and has projector equal to false. Then only return the ones where the school id on the classroom table is null. ``` SELECT school_name FROM school LEFT JOIN classroom ON school.school_id = classroom.school_id AND classroom.has_projector = 'f' WHERE...
SQL query : how to select records which all records in related table have specific value of attribute
[ "", "sql", "" ]
I have the following exercise: > concatenate first, middle, last name and name suffix to form the > customer’s name in the following format: FirstName [MiddleName.] > LastName[, Suffix]. Note that NULL values should be omitted. I interpret this as the following scenario (created the table from the image and inserted ...
Something like this should work as well... ``` SELECT concat(firstname ,CASE WHEN ISNULL(middlename,'') <> '' THEN ' '+middlename+'.' WHEN ISNULL(middlename,'') <> '' AND ISNULL(suffix,'') = '' THEN '.' ELSE ' ' END ,lastname ,CASE WHEN ISNULL(suffix,'') <> '' THEN ', '+suffix END) FROM...
I cant see the error in you query, i know if one of the columns is null, all the others will be, but try this way: ``` SELECT COALESCE(c.FIRSTNAME,'') + ' ' + CASE WHEN COALESCE(c.MiddleName,'') = '' THEN '' ELSE c.MiddleName + '.' END + COALESCE(c.LASTNAME,'...
SQL-Server CONCAT case
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a field in SSRS that i need to filter on. For 3 table I can use a IN filter. But I am in need to use a NOT IN operator. The field contains numeric values. I need to be able to say not in `(30,31,32,33,34,35,36,37,38,39)` I can't do it within the dataset either, it needs to be a filter. How should I achieve it...
You can use an expression to determine which values are going to be filtered. Go to `Tablix properties`/ `Filters` In `expression` use: ``` =IIF(Array.IndexOf(split("30,31,32,33,34,35,36,37,38,39",","), CStr(Fields!YourField.Value))>-1,"Exclude","Include") ``` For Operator use: ``` = ``` For `Value` use: ``` ="I...
For a variation of the selected answer that I find easier to use, please see below. This is in a Visibility expression, but should be easily ported to a Filter expression by setting Expression type to Boolean and comparing if `Expression = False`: `=IIf(InStr("unwanted values here", Fields!fieldToCheck.Value), True, F...
How to implement 'Not In' Filter in SSRS?
[ "", "sql", "sql-server", "reporting-services", "ssrs-2008-r2", "" ]
I need to divide two tables, `nr1` and `nr2` like shown below ``` SELECT COUNT(candidate.id) as nr1 FROM candidate WHERE candidate.id=2 select count (candidate.id) as nr2 from candidate where candidate.id=2 or candidate.id = 3; select nr1/nr2 from nr1, nr2; ``` The problem is they don't existe outside the `selec...
You can do it in single query. `Aggregate` the data *conditionally* in `SELECT`. ``` SELECT COUNT(CASE WHEN id = 2 THEN 1 END) / COUNT(CASE WHEN id = 2 || id = 3 THEN 1 END) FROM candidate ```
In oracle you can create a cte. ``` With table1 as ( SELECT COUNT(candidate.id) as nr1 FROM candidate WHERE candidate.id=2 ), table2 as ( select count (candidate.id) as nr2 from candidate where candidate.id=2 or candidate.id = 3 ) SELECT table1.nr1 / table2.nr2 FROM table1 CROSS JOI...
How To Divide Two Values From Different Tables in Select
[ "", "sql", "oracle", "oracle12c", "" ]
I have two tables: rooms (all the rooms) ``` id | title | ... ----------------- 1 |Room 1 | 2 |Room 2 | 3 |Room 3 | ``` user\_rooms (in which room is every user, column user is user's id and it's primary column) ``` user | room | ... ------------------ 20 | 3 | 14 | 1 | 35 | 3 | ``` So I ...
``` select r.id, r.title, coalesce(t.cnt,0) from rooms r left join (select room, count(*) as cnt from user_rooms group by room) t on t.room = r.id order by t.cnt desc ```
This would often be done without a subquery: ``` select r.id, r.title, count(ur.room) as numusers from rooms r left join user_rooms ur on r.id = ur.room group by r.id, r.title order by numusers desc; ``` This would often be more efficient than a version using a subquery in the `from` clause because it can t...
Order data by data from another table
[ "", "mysql", "sql", "sql-order-by", "" ]
This is a different question then [sorting by time or distance](https://stackoverflow.com/questions/962998/sorting-a-string-that-could-contain-either-a-time-or-distance). Imagine a table storing track & field results. A result for a running event would be in seconds and a field event would be in meters. What is the pr...
The proper way to architect this is to stop thinking about entering data and start thinking about how you intend to use the data. If all you are going to do is to display the results, then storing it in an nvarchar field including the measurement is fine. Optimize for reporting whenever you are thinking something may n...
That seems fine to me, partly because any comparison or aggregation -- max, min, avg -- of values is only going to be valid in the context of a particular event type anyway. I'd assume that there would be another value to indicate the units in which the value is stored for that event, or event type. You'd probably wa...
Database Architecture: Storing time or distance in one column
[ "", "sql", "database-design", "decimal", "" ]
Assume I have a subscriptions table : ``` uid | subscription_type ------------------------ Alex | type1 Alex | type2 Alex | type3 Alex | type4 Ben | type2 Ben | type3 Ben | type4 ``` And want to select only the users that have more than 2 subscriptions but never subscribed with type 1 The expected result is s...
Try this query: ``` SELECT uid FROM subscribes GROUP BY uid HAVING COUNT(*) > 2 AND max( CASE "subscription_type" WHEN 'type1' THEN 1 ELSE 0 END ) = 0 ```
Create Sample Table: ``` CREATE TABLE subscribes ( uid NVARCHAR(MAX), subscription_type NVARCHAR(MAX) ) ``` Insert Values: ``` INSERT INTO subscribes VALUES ('Alex', 'type1'), ('Alex', 'type2'), ('Alex', 'type3'), ('Alex', 'type4'), ('Ben', 'type2'), ('Ben', 'type3'), ('Ben', 'type4') ``` SQL Query: ``` SELECT ui...
How to check if value exists in each group (after group by)
[ "", "sql", "postgresql", "" ]
I have a table like this: ``` EMPNO ENAME JOB MGR 7369 SMITH CLERK 7902 7499 ALLEN SALESMAN 7698 7521 WARD SALESMAN 7698 7566 JONES MANAGER 7839 7654 MARTIN SALESMAN 7698 7698 BLAKE MANAGER 7839 7782 CLARK MANAGER 7839 7788 SCOTT ANALYST ...
> Can I do it with PARTITION Sure. Analytics would certainly do it. Use **COUNT() OVER()**. For example, using standard EMP table in SCOTT schema: ``` SQL> WITH DATA AS( 2 SELECT e.*, count(empno) OVER(PARTITION BY mgr ORDER BY NULL) cnt 3 FROM emp e 4 ) 5 SELECT empno, ename, mgr 6 FROM DATA 7 WHE...
For example: ``` SELECT manager_id FROM employees GROUP BY manager_id HAVING count(employee_id)=2 ```
select managers with 2 employees
[ "", "sql", "oracle", "" ]
I have MS SQL 2012 database with ~80 tables. Each table has a column `UserID` that identifies the user who created or last edited the record. I would like to write the sql statement that would give me the number of created/edited records for some userID in all database tables. For example, user with UserID = 1 is the ...
I doubt "EXEC sp\_MSForEachTable" solution will not work, assuming the database has few more table, which don't have that User Id column, unless you are explicitly handling such failure using try catch block. In that case It will surely fail. Here the solution to consider only those table which have the required colum...
Try this, it builds a dynamic query for all tables in your database and then executes it: ``` DECLARE @sql NVARCHAR(MAX) SELECT @sql = '(SELECT COUNT(*) FROM QUOTENAME(TABLE_NAME) WHERE user_id = 1) +' FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES SELECT @sql = 'SELECT' + LEFT(@sql, LEN(@sql) - 1) -- remove the la...
How to count records in multiple tables containing the same column?
[ "", "sql", "sql-server", "" ]
I've got a table with a lot of entries per day. Each entry has got a "Level". Now what I'am trying to do is, to select foreach day how many records exists with a Level. The Levels can be different so first of all I need to select distinct all levels and the show for each day how many records foreach level are there. If...
try this: ``` SELECT T.[Date], T.[Level], COALESCE(COUNT(D.[Level]),0) AS CountOfRecords FROM ( SELECT DISTINCT B.Date, A.[Level] FROM tablename AS A INNER JOIN (SELECT DISTINCT [Date] FROM tablename) AS B ON 1=1 ...
Produce `cross join` of distinct `dates` and `levels` and then `left join` on actual table: ``` ;with cte1 as(select distinct level from tablename), cte2 as(select distinct date from tablename) select c1.level, c2.date, count(distinct t.RecId) as CountOfRecords from cte1 c1 cross join cte2 c2 lef...
SQL Server: Display 0 in Group by with Distinct values
[ "", "sql", "sql-server", "date", "group-by", "" ]
I need to select a set of data from a table (`TableA`), but only if it's not in another table (`TableB`). ``` SELECT thisData FROM dbo.TableA WHERE thisData is not existing in dbo.TableB ``` I'm not really well versed in SQL.
You can use a `not exists` condition: ``` SELECT thisData FROM dbo.TableA a WHERE NOT EXISTS ( SELECT * FROM TableB b WHERE a.thisData = b.thisData ) ```
You can do `EXCEPT`: ``` SELECT thisData FROM dbo.TableA except SELECT thisData FROM dbo.TableB ``` Or, a more general solution, `NOT EXISTS`: ``` select * from dbo.TableA ta where not exists (select 1 from dbo.TableB tb where tb.thiscolumn1 = ta.thiscolumn1 [ and tb.thiscolumn2...
How can I select a data if that data is not existing in another table?
[ "", "sql", "sql-server", "" ]
I am having a difficult time wrapping my head around the path for solving a problem in DB2. I have three tables that look like this... **PARENT** ``` id | label -------------- 1 | One 2 | Two 3 | Three ``` **TABLE1** ``` id | parentid | eventdate ------------------------- 1 | 1 | 2015-11-01 2 | ...
You are on the right track. Use a union in a subquery and then join PARENT and GROUP BY label to get the MAX date. ``` SELECT label, MAX(eventdate) AS maxeventdate FROM ( SELECT parentid, eventdate FROM TABLE1 UNION ALL SELECT parentid, eventdate FROM TABLE2) JOIN PARENT ON (id = parentid) GROUP BY label ```
``` SELECT label, CASE WHEN max(t1.eventdate) > max(t2.eventdate) THEN max(t1.eventdate) ELSE max(t2.eventdate) END as eventdate FROM PARENT p JOIN TABLE1 t1 ON p.id = t1.id JOIN TABLE2 t2 ON p.id = t2.id GROUP BY p.label ```
DB2 JOIN, UNION, and pull max value from each group
[ "", "sql", "db2", "union", "" ]
I have a number of months. I wish to represent them as a number of years and months in the format YYMM e.g. ``` 5 -> 0005 13 -> 0101 24 -> 0200 ``` Does anyone know of a non-convoluted way to do this in Oracle SQL?
A little bit of maths and some formatting are the way to go: ``` with sample_data as (select 5 num from dual union all select 13 num from dual union all select 24 num from dual union all select 1400 num from dual) select to_char(floor(num/12), 'fm9999909')...
``` select lpad(trunc(yourValue/12),2,'0')||lpad(mod(yourValue,12),2,'0') result from dual ```
Converting a number of months to date string
[ "", "sql", "oracle", "" ]
Take the following statement: ``` SELECT SUM( IF( talktime > 4 AND status = 'answer' , 1, 0 ) ) as count FROM table ``` The output should be count the rows that fulfill both conditions. Is the statement valid? EDIT: I'm interested in the multiple condition part in IF.
This statement: ``` SELECT SUM( IF( talktime > 4 AND status = 'answer' , 1, 0 ) ) as count FROM table ``` is kind of correct, with caveats: * `table` is not allowed as a table name, because it is a reserved word. It needs to be escaped. * `count` is a poor choice for a column name, because it is a built-in function ...
> **IF(expr1,expr2,expr3)** > > If expr1 is TRUE then IF() returns expr2; otherwise it returns expr3 So the above code will return `1` when the conditions satisfies otherwise return `0`. So the count will be the `No. of rows satisfying the condition`. --- For example, If you want to display `total no .of calls`,`to...
Multiple condition in IF in SELECT
[ "", "mysql", "sql", "" ]
(Caution: Newbie alert) I have to put a count of the subsections of a generated view along with the view itself. Is it possible? For example, this is the generated view from a SQL select: ``` Client Type Year 8963 Rural 2012 9044 City 2013 8963 Rural 2014 5145 Rural 2014 5145 City ...
First of all, I'd advise you to look into functions such as pivot. <https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/pivoting_tables56?lang=en> Secondly, if the fields you want to create are known in advance (meaning, you want to create fields for specific years), you can try to sum/count a cas...
Look into [Subqueries](http://www.tutorialspoint.com/sql/sql-sub-queries.htm) and the [Count](http://www.w3schools.com/sql/sql_functions.asp) function. You can wrap a query in another query and use aggregates to count, sum or even do standard deviations on the results.
show a SQL select along with a count of itself?
[ "", "sql", "count", "db2", "" ]
In PostgreSQL 9.3.4 release note it says: > Ensure that the planner sees equivalent VARIADIC and non-VARIADIC function calls as equivalent (Tom Lane) I searched the PostgreSQL manual and couldn't find a definition of what it is. I found that it's realated to the mode of function argument (IN, OUT, VARIADIC) but I di...
Variadic functions are those with an undefined number of arguments, they are present in many programming and query languages. In the case of PostgreSQL, you can find an example at <http://www.postgresql.org/docs/9.1/static/xfunc-sql.html> (35.4.5. SQL Functions with Variable Numbers of Arguments): > Effectively, all ...
When you are not sure about the number of parameters then we use Variadic. You can refer [VARIADIC FUNCTIONS IN POSTGRESQL](http://www.postgresonline.com/journal/archives/211-Variadic-Functions-in-PostgreSQL.html) for details. See the wiki about [Variadic functions](https://en.wikipedia.org/wiki/Variadic_function): ...
What does VARIADIC declarations mean in PostgreSQL?
[ "", "sql", "database", "postgresql", "variadic-functions", "variadic", "" ]
I'm working with a database containing customer orders. These orders contain the customer id, order month, order year, order half month( either first half 'FH' or last half 'LH' of the month), and quantity ordered. I want to query monthly totals for each customer for given month. Here's what I have so far. ``` SELECT...
First, generate all the rows, which you can do with a `cross join` of the customers and the time periods. Then, bring in the information for the aggregation: ``` select i.id, t.half_month, t.month, t.year, coalesce(sum(nbr_ord), 0) from (select distinct id from orders) i cross join (select distinct half_month, mo...
IF you know the entire dataset has an occurance of each half\_month, month, year combination you could use the listing of those 3 things as the left side of a left join. That would look like this: ``` Select t1.half_month, t1.month, t1.year, t2.ID, t2.nbr_ord from (Select half_month, month, year)t1 Left Join (SELE...
How can I return a row for each group even if there were no results?
[ "", "sql", "oracle", "" ]
I have a table in SQL that I would like to have a unique constraint so that any of two values cannot already exist. for example if I have 2 columns, I would like it to not insert if the value in column B does not exist in column A or column B. Is this possible and if so how is it done? example: ``` Column A | Colum...
Trigger with ROLLBACK TRANSACTION is the way to go. ``` create trigger dbo.something after insert as begin if exists ( select * from inserted where ...check here if your data already exists... ) begin rollback transaction raiserror ('some message', 16, 1) end end ```
You can create a function which takes in these values & create a check constraint on it (referencing your functions return values) to your table. ``` create table t11 (Code int, code2 int) create function fnCheckValues (@Val1 int, @Val2 int) Returns int /*YOu can write a better implementation*/ as Begin DECLARE @Cnt...
SQL unique constraint on either of 2 columns
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have seen some questions related to my issue, but never exactly the same structure, and as I am quite new to SAS/SQL I can't find a proper way out of my problem. I am trying for a couple of days to join multiple tables (about thirty) Basically, my problem boils down to this: Let say I have 3 tables: TAB, with 2 v...
You can do this with `proc sql` and some SQL cleverness: ``` proc sql; select tab.v1, tab.v2, coalesce(t1.v3, t2.v3) as v3 from tab left join t1 on tab.v2 = 1 left join t2 on tab.v2 = 2; ```
The data step solution is interesting: ``` data want; set tab; if v2=1 then do; do _n_ = 1 to nobs_t1; set t1 point=_n_ nobs=nobs_t1; output; end; end; else if v2=2 then do; do _n_=1 to nobs_t2; set t2 point=_n_ nobs=nobs_t2; output; end; end; run; ``` That's the stan...
Conditional combining of multiple datasets/tables based on a value of one variable
[ "", "sql", "join", "merge", "sas", "" ]
I have the following data ``` Activity | Indicator | Impact ------------------------------------------------ Payroll risk | Indicator A | Low Payroll risk | Indicator B | Low Payroll risk | Indicator C | Low Wrong selections | Indicator D | High Wrong selections...
You can do that by using CASE or PIVOT. Here is example of Pivot for your sample data: ``` SELECT Activity, Impact, [1], [2], [3] FROM ( SELECT Activity, Indicator, Impact ,ROW_NUMBER()OVER(PARTITION BY Activity ORDER BY Indicator) AS R FROM @T ) AS M PIVOT ( MAX(Indicator) FOR R IN ([1], [2], [3]) ) P ``` In case y...
One way of doing it - ``` select Activity , [Indicator] = max(case when RowID = 1 then Indicator end) , [Indicator] = max(case when RowID = 2 then Indicator end) , [Indicator] = max(case when RowID = 3 then Indicator end) ,Impact from ( select Activity , Indicator , Impact , RowID = row_number() over (pa...
How to select dynamic number of columns according to rows in sql
[ "", "sql", "sql-server", "" ]
I am trying to figure how can I calculate the number of days,the customer did not eat any candy. Assuming that the Customer eats 1 candy/day. If customer purchases more candy, it gets added to previous stock Eg. ``` Day Candy Puchased 0 30 40 30 65 30 110 30 125 40 170 30 ``...
You need a recursive CTE First I need create a `row_id` so I use `row_number` Now I need the base case for recursion. * `Day`: Mean how many day has pass. (0 from db) * `PrevD`: Is the Prev day amount so you can calculate `Day` (start at 0) * `Candy Puchased`: How many cadies bought (30 from db) * `Remaining`: How m...
Nice question. Check my answer and also try with different sample data. and please,if with different sample data it is not working then let me know. ``` declare @t table([Day] int, CandyPuchased int) insert into @t values (0, 30),(40,30),(65, 30) ,(110, 30),(125,40),(170,30) select * from @t ;With CTE as ( select *,...
calculate sum based on value of other row in another column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
When I try to restore a SQL Server database, I get: "An exception occured while executing a Transact-SQL statement or batch. Incorrect syntax near 's' Unclosed quotation mark near character string ". (Microsoft SQL Server, Error:102)" I am not using any script, just clicking "Restore Database", selecting the file (it...
This is due to permission problem.First you need to move the \*.bak file to the data-directory of the SQL-server .. then try again..
Make sure that you didn't name the directory using special characters. For example, I named my directory `SQLDB's\` and got that error. To resolve it, I removed the ' and it worked.
Can't restore a SQL Server database from a backup file - Error: 102
[ "", "sql", "sql-server", "" ]
I don't know enough about databases to find the right words to ask this question, so let me give an example to explain what I'm trying to do: Suppose I want the primary key for a table to be an ID I grab from an API, but the majority of those API requests result in 404 errors. As a result, my table would look like this...
No, there won't be any effect on efficiency if you have non-consecutive IDs. In fact, MySQL (and other databases) allow for you to set a variable [`auto_increment_increment`](https://dev.mysql.com/doc/refman/5.6/en/replication-options-master.html#sysvar_auto_increment_increment) to have the ID increment by more than 1....
It's fine to have IDs not sequential. I regularly use GUIDs for IDs when dealing with enterprise software where multiple business could share the same object and they're never sequential. The one thing to watch out for is if the numbers are the same. What's determining the ID value you're storing?
Is it okay to have non sequential ids as primary keys for a table in your database?
[ "", "mysql", "sql", "database", "indexing", "primary-key", "" ]
My SQL currently looks like this. ``` SELECT t1.field1, t1.field2, t1.field3, t1.field4, t1.field5, t1.field6, t1.field7, t1.field8, t2.field1, t2.field2, t2.field3, t2.field4, t2.field5, t2.field6, t2.field7, t2.f...
The main performance drain may be unnecessary columns in `GROUP BY`. This can happen if your `Table` refers to a denormalized table: ``` EMP (EMP_ID*, DEPT_ID, DEPT_NAME, SAL, THEDATE) ``` or if `Table` refers to a join, e.g. ``` EMP(EMP_ID*, DEPT_ID, SAL, THEDATE) DEPT(DEPT_ID*, DEPT_NAME) "Table" == EMP JOIN DEPT...
The syntax you posted isn't valid-- you can't `group by *` and you'd need to have an alias on the `select *` since you're selecting other columns. Assuming both of those are just artifacts of putting together a simplified example, you just need to use the `having` clause ``` SELECT a.*, sum(something), min(theDate) ...
Oracle select records based on a min date where min date between
[ "", "sql", "oracle", "aggregate-functions", "" ]
Im curious if there is a way to insert into MySQL and avoid duplicates. I know there are three primary ways of accomplishing it. Either Replace, insert ignore or insert on duplicate key. I believe that each of these rely on a unique primary key which for me is a auto increment id field. This id field does not have any ...
If the `id` field has no value for you, don't bother with it. The desired behavior you're describing is that of a [composite key](https://stackoverflow.com/questions/5835978/how-to-properly-create-composite-primary-keys-mysql), so make a composite key. First, scrap the one that exists and is of no value... `ALTER TAB...
You can create an `UNIQUE` constrain ``` ALTER TABLE `tableName` ADD UNIQUE `unique_idx`(`name`, `team`, `email`); ```
Insert ignore multiple columns data unique
[ "", "mysql", "sql", "" ]
i have example database, where i store relationships between males and females. The schema and some data are shown on image. [![enter image description here](https://i.stack.imgur.com/nmycH.png)](https://i.stack.imgur.com/nmycH.png) Is there a way to **select all man, which are not in BFF relationship**? On example t...
A question of this type suggests `not exists`. The tricky part is that the `not exists` subquery has a join: ``` select m.* from man m where not exists (select 1 from man_women_relationship mwr join type t on mwr.fk_type = t.id where mrw...
I'm new to sql, so I may be wrong. But this is what I would try: select Name from Man\_Women\_Relationship join Type on Man\_Women\_Relationship.FK\_Type = Type.ID AND Type.ID = 4
Select from data from A table, with no match in B table
[ "", "mysql", "sql", "database", "join", "" ]
I am trying to extract a data from an Excel through different Excel using `ADODB.Connection` but when I am trying to retrieve data between from date to system date I am getting an automation error in Excel. I have checked various articles but I'm unable to validate those condition because I don't have SQL Server so I ...
Finally found out the error cause... Actually the error was because of the quotes `'13-nov-15'` which I was using in coding but the same was replacing after with `#13-nov-15#`. It worked. As per the @Williams answer's there was a only one correction made for another date but for parameter date the quotes was coming b...
I think your problem is GetDate() Your approach to building the WHERE clause can also be much simpler: ``` Sub get_data() Dim strSQL As String, strWhere As String Dim cnn As New ADODB.Connection Dim rs As New ADODB.Recordset Dim DBPath As String Dim sconnect As String DBPath = "\\abc\Quality Report.xlsx" sc...
How to retrieve data between from date to system date using excel VBA (Automation Error)
[ "", "sql", "excel", "vba", "" ]
Let's say a have a table called people with the following columns: 1. person\_id 2. name 3. parent\_person\_id I'm trying to write a query to return the following: 1. person.person\_id as 'id' 2. person.name as 'name' 3. person.parent\_person\_id as 'parent id' 4. person.label (person.person\_id = person.person\_par...
You are quite close. You just need proper table aliases: ``` SELECT p.person_id as PersonID, p.name as PersonName, p.parent_person_id as ParentID, (SELECT parent.name FROM people parent WHERE p.parent_person_id = parent.person_id; ) as ParentName FROM people p; ``` Notes: ...
Just create an alias for each table ``` SELECT p1.person_id as 'Person ID', p1.name as 'Person Name', p1.parent_person_id as 'Parent ID', ( SELECT p2.name FROM people as p2 WHERE p2.parent_person_id = p1.person_id; ) as 'Parent Name' FROM ...
How do I make a reference to a table column from the parent query within the subquery in SQL?
[ "", "mysql", "sql", "database", "" ]
Table structure : table name : `DETAIL_BOX` ``` ----------------------------------------------------------------------------- | sn (Number) | name (varchar2) | date1 (date) | date2 (date) | ----------------------------------------------------------------------------- | 2 | Ram | 26....
I would put two answers (by BeanFrog and Prabhat Sharma) together. In my opinion it's good solution to update column to a new value or to itself in depend on criteria. ``` update detail_box set name = decode(sn, 2, 'Gita', 3, 'Krish', name), date1 = (case when sn = 2 and date2 is null then to_date('2015-10-16', ...
I'm not sure where sn comes in, but hopefully the general method will help. Update both fields in your update statement, but either set them to themselves or to the new date based on a case statement: ``` UPDATE DETAIL_BOX SET date2= case when date2 is null then date2 else to_date('2015-10-16', 'YYYY-MM-DD') end ...
How to set dynamic column name to set value in UPDATE statement of SQL Query on the basis of condition?
[ "", "sql", "oracle", "" ]
I have a query ``` select c.CommentId ,c.CommentText , c.CommenterId , c.CommentDate , u.first_name , u.last_name , i.ImageName , i.Format from comment c join users u on c.CommenterId = u.user_id join user_profile_image i on u.user_id = i.UserId where PostId = 76 order by CommentDate desc limit 10 ```...
`JOIN` defaults to `INNER JOIN` for MySQL - try changing `join user_profile_image i` to `LEFT join user_profile_image i` The accepted answer here has a good visual explanation: [Difference in MySQL JOIN vs LEFT JOIN](https://stackoverflow.com/questions/9770366/difference-in-mysql-join-vs-left-join)
To include the rows when the ImageName field is empty, use `LEFT JOIN`, like this: ``` SELECT c.CommentId,c.CommentText, c.CommenterId, c.CommentDate, u.first_name, u.last_name,i.ImageName,i.Format FROM comment c INNER JOIN users u ON c.CommenterId=u.user_id LEFT JOIN user_profile_image i ON u.user_id=i.UserId WHERE...
sql query is behaving strange
[ "", "mysql", "sql", "" ]
I have already given ranks in rank\_id column of top\_books and i want to update the same table according to count\_issue attribute while keeping the rank\_id as they are. Can this be done somehow? ``` DECLARE v_row NUMBER; CURSOR cur IS SELECT COUNT(transaction_id) counter, book_id FROM transaction_maste...
try this you can do it for update also but approach bit confusing just change your cursor; ``` DECLARE v_row NUMBER; CURSOR cur IS select * from (SELECT COUNT(transaction_id) counter, book_id FROM transaction_master GROUP BY book_id) order by counter desc; BEGIN -- truncate table execute immediat...
I wouldn't do this using a cursor for loop; instead, I'd do it in a single MERGE statement: ``` merge into top_books tgt using (select row_number() over (order by cnt desc, book_id) rn, book_id, cnt from (select book_id, count(transaction_id) cnt ...
How to sort data in a table using pl sql block
[ "", "sql", "database", "oracle", "plsql", "" ]
I have the following table named `population`: ``` ╔════════════╦════════════╦════════════════╗ ║ india ║ hyderabad ║ 50100 ║ ║ india ║ delhi ║ 75000 ║ ║ USA ║ NewYork ║ 25000 ║ ║ USA ║ california ║ 30000 ║ ║ india ║ delhi ║ 5000 ...
You can use: ``` SELECT * FROM ( SELECT country,city, SUM(pop) AS total FROM population GROUP BY country,city) AS sub WHERE (country, total) IN ( SELECT country, MAX(total) FROM (SELECT country,city, SUM(pop) AS total FROM po...
You could use a combination of GROUP\_CONCAT and FIND\_IN\_SET. This query will return a comma separated list of cities for every country, ordered by population DESC: ``` SELECT country, GROUP_CONCAT(city ORDER BY pop DESC) AS cities FROM population GROUP BY country ``` and it will return something like this: ``` | ...
how to write the following SQL query involving sub queries
[ "", "mysql", "sql", "" ]
I'm trying to create my database for a website and there seems to be an error I cannot solve. For some reason it's giving me an invalid syntax problem, but I have no idea why. I looked it up everwhere. ``` mysql> SELECT WebsiteDB -> CREATE Table `MasaTable`( -> `Username` varchar(255), -> `Password` varchar(255)...
Oh boy, was that a stupid mistake. I was using `SELECT <database>` instead of `USE <database>`, and I wasn't closing it with a semicolon. Thank you Mihai! This works just fine: ``` USE WebsiteDB; CREATE Table MasaTable( Username varchar(255), Password varchar(255), Email varchar(255)); ```
Remove last comma and use backticks to quote identifiers: ``` CREATE TABLE `MasaTable`( `Username` varchar(255), `Password` varchar(255), `Email` varchar(255) ); ``` `SqlFiddleDemo`
MySQL server table creation - "invalid syntax"
[ "", "mysql", "sql", "create-table", "" ]
I want the SIDS of suppliers who supply every part. I have trouble understanding the query answer the book has given. ``` Suppliers(sid: integer, sname: string, address: string) Parts(pid: integer, pname: string, color: string) Catalog(sid: integer, pid: integer, cost: real) ``` Suppose you're given a database as the...
A simple 'proof by contradiction' will demonstrate the query could never return S2. For the query to return S2, the first `NOT EXISTS` would demand the subquery on `Parts` to yield zero rows. Which is most certainly not the case, since that particular subquery returns all parts not supplied by S2 (i.e. P2 and P3).
You should read the query as: Give me suppliers for which there doesn't exist such a part that has no corresponding catalog for the **abovemensioned** supplier. You should read the query from top to bottom here. Imagine a loop on `Catalogs` table. Fetch first row(`S1,P1`). Do a inner loop for `Parts` and check if that...
SQL nested not exist understanding
[ "", "sql", "relational-division", "" ]
im trying to make an SQL table with custom date format ``` CREATE TABLE Basketbal.Bestuurslid ( `lidnummer` INT NOT NULL, `begin_datum` DATE NOT NULL, `eind_datum` DATE NULL, `functie` VARCHAR(45) NULL, PRIMARY KEY (`lidnummer`, `begin_datum`)); (I know it's in dutch) ``` im trying to make `begin_datum` & `eind_datum...
`date` is an internal format in the database. You can convert it to (or from) a string using `date_format()` (and `str_to_date()`). That controls the *character* representation of the value, not the value itself. So, when you select from the table: ``` select date_format(begin_datum, '%e-%b-%y') ``` If you really fee...
Once you have your data stored in your table you could pull your data in the format you want it, example: ``` CONVERT(VARCHAR(11),begin_datum,6) ```
SQL dateformat while creating table
[ "", "mysql", "sql", "create-table", "" ]
I have two tables that I’m trying to build a query with for our fundraising department but that I’m struggling with. Using SQL Server 2008. The Appeals table holds data about which members we are going to send an appeal for a donation to. The Yearly\_Gift table holds data about how much money a member donated on a ye...
``` WITH X AS ( SELECT A.[Appeal_ID], A.[Member_ID],Y.[FiscalYear], Y.[Amount] FROM [dbo].[Appeals] A LEFT JOIN [dbo].[Yearly_Gift] Y ON Y.[Member_ID] = A.[Member_ID] ) SELECT X.[Appeal_ID], X.[Member_ID],Y.[FiscalYear], X.[Amount] FROM X LEFT JOIN ( SELECT [Member_ID], MAX([FiscalYear]) AS [Fisc...
Well - this query is a bit long/ugly, but it works. If I had more time, I'd look into optimizations and code reduction. ``` SELECT target_members.Appeal_ID, target_members.Member_ID, FiscalYear, Amount FROM ( SELECT MAX( Appeal_ID ) AS Appeal_ID, Member_ID FROM Appeals GROUP BY ...
Join tables using max(column) with a with another column >0
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
**My table:** ``` CREATE TABLE [dbo].[Balance] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Balance] DECIMAL (18, 2) NOT NULL, [Today_Date] AS (CONVERT([char](10),getdate(),(126))), [Date_end] DATE NOT NULL, [Remaining_Days] AS ...
@Mahesh So, @Usedbyalready's answer seemed pretty overkill, I tried making it myself with case inside an update and it works perfectly. ``` UPDATE Months SET Months.Balance_monthly = CASE WHEN Balance.In_Months > 1 THEN Amount_Monthly END FROM Balance JOIN Months ON Months.Id <= Balance.In...
You need 12 rows each represents a Month number 1 to 12. I have used a simple union all query in a CTE for this but you may already have a table of numbers to use instead. Then join this where the month number is less than or equal to the [in\_Month] column. That join will automatically now multiply the rows of your ta...
Indexed views: How to insert value into other table with index views?
[ "", "sql", "sql-server", "indexing", "triggers", "indexed-views", "" ]