Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have two separate databases (MySQL and PostgreSQL) that maintain different data-sets from different departments in my organization-- this can't be changed. I need to connect to one to get a list of `symbols` or `ids` from the first DB with a DBAPI in python and request the other set and operate on it. (I've spent a ...
Use `RETURNS TABLE` instead of `RETURNS SETOF record`. This will simplify the function calls. You cannot use `IN` operator in that way. Use `ANY` instead. ``` CREATE FUNCTION get_results(text[]) RETURNS TABLE (fooname text, fooid int, foosubid int) AS $$ SELECT fooname, fooid, foosubid FROM foo WHERE ...
## Row vs Array constructor `('Joe', 'Ed')` is equivalent to `ROW('Joe', 'Ed')` and creates a new row. But your function accepts an array. To create one, call it with an Array constructor: ``` SELECT * FROM get_results(ARRAY['Joe', 'Ed']); ``` ## Variadic functions You can declare your input parameter as `VARIADIC...
PostgreSQL - Passing Array to Stored Function
[ "", "sql", "postgresql", "stored-procedures", "" ]
My table contains the details like with two fields: ``` ID DisplayName 1 Editor 1 Reviewer 7 EIC 7 Editor 7 Reviewer 7 Editor 19 EIC 19 Editor 19 Reviewer ``` I want get the unique details with DisplayName like `1 Editor,Reviewer 7 EIC,Editor,Reviewer`...
In *SQL-Server* you can do it in the following: **QUERY** ``` SELECT id, displayname = STUFF((SELECT DISTINCT ', ' + displayname FROM #t b WHERE b.id = a.id FOR XML PATH('')), 1, 2, '') FROM #t a GROUP BY id ``` **TEST DATA** ``` create table #t ( id int, displayname nvarchar...
**SQL Server 2017+ and SQL Azure: STRING\_AGG** Starting with the next version of SQL Server, we can finally concatenate across rows without having to resort to any variable or XML witchery. [STRING\_AGG (Transact-SQL)](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver1...
How to concatenate many rows with same id in sql?
[ "", "sql", "sql-server", "" ]
**QUERY:** I have a table consisting columns like UserId and FirstName What i want to do is: I want to fetch the FirstName while getting the max if UserId My novice attempt: ``` select FirstName from tblUsers where MAX(UserId)=@UserId ``` Which is showing the error of: > An aggregate may not appear in the WHERE ...
Try to use `HAVING` in following: ``` select FirstName from tblUsers group by FirstName having MAX(UserId)=@UserId ``` **UPDATE 1** If you want to get only 1 `FirstName` which have highest `UserId` you can use `TOP 1` in following: ``` select top 1 FirstName from tblUsers order by UserId desc ``` **UPDATE 2** I...
``` select FirstName from tblUsers group by FirstName having MAX(UserId)=@UserId ``` HAVING is like a where clause for aggregate expressions. But that doesn't seem to make sense to me. You'll only get a row if @UserId is the maximum user Id in the table, so I don't quite understand what you want.
Selecting a data from table while fetching the MAX value of a column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to select the amount of articles each author has on my table. Here's what I got so far: ``` SELECT (SELECT COUNT(*) FROM tb_artigos as b WHERE a.id_autores = b.id_autores) as total FROM tb_autores as a GROUP BY total ORDER BY total desc ``` I guess it wrong because it only return 19 rows and I ...
Normally, this would be done using an explicit `JOIN`. However, a correlated subquery is fine. The problem is your `GROUP BY` clause. The correct `GROUP BY` is on the author id: ``` SELECT a.id_autores, (SELECT COUNT(*) FROM tb_artigos as b WHERE a.id_autores = b.id_autores) as total FROM tb_autores a GROUP BY...
Some authors may not have any article which means you won't get anything out of a simple JOIN. Use this LEFT OUTER JOIN and the authors will be 24: ``` SELECT tb_autores.id_autores, COUNT(*) FROM tb_autores LEFT OUTER JOIN tb_artigos ON tb_autores.id_autores = tb_artigos.id_autores GROUP BY tb_autores.id_autor...
Trying to get the number of posts from authors with a subquery
[ "", "mysql", "sql", "" ]
Say I got a meeting room named niagara. I want to find who occupied this room given a start and end time range. The table name is "niagara". Lets just keep the search for today. ``` Person InTime OutTime A 9AM 1PM B 10AM 12PM C 10:25AM 1:30PM D 9AM 9:00 PM E ...
The basic logic is that someone is in the room if the `in_time` is less than the period end and the `out_time` is after the period start. So, that would be: ``` SELECT PERSON FROM NIAGARA WHERE OUT_TIME > START_TIME AND IN_TIME < END_TIME; ``` How you actually express this in Oracle depends on how the values are stor...
The common logic to check for overlapping ranges is this: ``` (start#1,end#2) overlaps (start#2,end#2) start#1 <= end#2 AND end#1>= start#2 ``` Depending on your logic (both start & end inclusive or only one) you might need to change the comparison to ``` start#1 < end#2 AND end#1>= start#2 ```
SQL query: identify who occupied room in a specific time range
[ "", "sql", "oracle", "" ]
I'm working on Visual Studio 2015 and whenever I try to add a table from the server explorer menu, it only shows two options **Properties** and **Refresh**. There have been answers for [this](https://i.stack.imgur.com/8WEhm.png) problem, but I have already tried them, like, adding SQL data tools and repairing visual s...
Thanks for the comments, but i solved the problem. Open the command prompt and type the command: ``` C:\sqllocaldb create "MyInstance" ``` *MyInstance* refers to your sql server instance, it can be **v11.0** but for me it was **mssqllocaldb** . If it runs successfully, it will show you result stating 'Instance crea...
1. Close your visual studio. 2. [Download SQL Server Data Tools](https://download.microsoft.com/download/3/4/6/346DB3B9-B7BB-4997-A582-6D6008796846/Dev12/EN/SSDTSetup.exe) 3. Install it in your pc 4. Then Close if successfully installation. 5. Now Open your visual studio. Hope this will help. Enjoy :)
"Add new table" option missing - Visual Studio 2015
[ "", "sql", "visual-studio", "" ]
I have the following table: ``` CREATE TABLE orders ( id INT PRIMARY KEY IDENTITY, oDate DATE NOT NULL, oName VARCHAR(32) NOT NULL, oItem INT, oQty INT -- ... ); INSERT INTO orders VALUES (1, '2016-01-01', 'A', 1, 2), (2, '2016-01-01', 'A', 2, 1), (3, '2016-01-01', 'B', 1, 3), (4, '2016-01-...
The [`rank`](https://msdn.microsoft.com/en-us/library/ms176102.aspx) window clause allows you to, well, rank rows according to some partitioning, and then you could just select the top ones: ``` SELECT oDate, oName, oItem, oQty, oRemarks FROM (SELECT oDate, oName, oItem, oQty, oRemarks, RANK() OVER (P...
This is a generic query without using analytical function. `SQLFiddle Demo` ``` SELECT a.* FROM table1 a INNER JOIN (SELECT max(odate) modate, oname, oItem FROM table1 GROUP BY oName, oItem ) b ON a.oname=b.oname AND a.oitem=b.oitem AND a.odate=b.modate ```
Get the latest records per Group By SQL
[ "", "sql", "sql-server", "select", "sql-server-2008-r2", "groupwise-maximum", "" ]
I have a table with two different stamps. Let's call them oristamp and tarstamp. I need to find only the records that for the same oristamp have different tarstamps. It is possible to do that with a simple query? I think should be used a cursor but I'm not familiar with that. Any help?
Use a sub-query to find oristamp values having at least two different tarstamp values. Join with that sub-query: ``` select t1.* from tablename t1 join (select oristamp from tablename group by oristamp having count(distinct tarstamp) >= 2) t2 on t1.oristamp = t2.oristamp ```
I hope I understand the question. I am assuming you want all rows where more than 1 distinct value for tarstamp exists for each oristamp. ``` DECLARE @t table(tarstamp int, oristamp int) INSERT @t values (1,1), (1,1), (1,2), (2,2) ;WITH CTE as ( SELECT *, max(tarstamp) over (partition by oristamp) mx, min...
SQL query or cursor?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table which contains the following columns: ``` ProductName copmanyname arianame bno mrp exp_date Date qty DANZEN DS HELIX PHARMA CITY 1 J026 215 01-Feb-16 30-Oct-19 41 DANZEN DS HELIX PHARMA CITY 2 J026 215 01-Feb-16 30-Aug-19 2 HIPRO HELIX PHARMA CIT...
The query in your question greatly differs from what you are asking to get as a result. Additionally your desired output seems to be off in quantity. If you want the sum of the quantity, where Productname, companyname,bno and mrp are identical, then it is wrong to group by exp\_date and date as well. If you take a lo...
to make the other comments clear: ``` ProductName copmanyname arianame bno mrp exp_date Date qty DANZEN DS HELIX PHARMA CITY 1 J026 215 01-Feb-16 30-Oct-19 41 DANZEN DS HELIX PHARMA CITY 2 J026 215 01-Feb-16 30-Aug-19 2 ^ can you see the diffe...
How we sum the value of unique record in sql
[ "", "sql", "group-by", "" ]
my table looks like this ``` +--------+--------+--------------+--------------+ | CPI_id | Weight | score_100_UB | score_100_LB | +--------+--------+--------------+--------------+ | 1.1 | 10 | 100 | 90 | +--------+--------+--------------+--------------+ ``` while executing the insert query th...
For MySQL use: ``` insert into table values (CPI_id , Weight ,IFNULL(score_100_UB ,100), score_100_LB ) ``` or: ``` insert into table values (CPI_id , Weight ,COALESCE(score_100_UB ,100), score_100_LB ) ``` SQL Server: ``` insert into table values (CPI_id , Weight ,ISNULL(score_100_UB ,100), score_100_LB ) ``` Or...
Alter your table and set the field `score_100_UB` to have some default value like below ``` ALTER TABLE t1 MODIFY score_100_UB INT UNSIGNED DEFAULT 100; ``` After this, whenever you try to insert a NULL value in this column, it will be replaced by 100
how to replace NULL value during insertion in sql
[ "", "mysql", "sql", "" ]
I have a table where I store details about the chapters, I have to show data in following order of Table of Index > 1. Chapter One > > 1.1 Chapter One Page 1 > > 1.2 Chapter One Page 2 > 2. Chapter Two > > 2.1 Chapter Two Page 1 > > 2.2 Chapter Two Page 2 > 3. Chapter Three > > Title One > > Title Tw...
Use `PageOrder` instead of `ID` to build `SortCol`, also cast to `VARCHAR(MAX)` instead of `VARBINARY(MAX)`: ``` WITH CTE(ID, parentID, Chapter, PageOrder, Depth, SortCol) AS ( SELECT ID, parentID, Chapter,PageOrder, 0, CAST(PageOrder AS varchar(max)) FROM Book WHERE parentID = 0 UNION ALL ...
The Complete Solution like ``` SELECT * FROM ( SELECT p.CategoryID , p.Category_Name , p.IsParent , p.ParentID , p.Active , p.Sort_Order AS Primary_Sort_Order , CASE WHEN p.IsParent = 0 THEN (SELECT Sort_Order FROM tbl_Category WHERE CategoryID = p.ParentID) ELS...
Sort data in SQL Server based on parent child relation
[ "", "sql", "sql-server", "sql-server-2008", "" ]
[![View Design](https://i.stack.imgur.com/A5E95.jpg)](https://i.stack.imgur.com/A5E95.jpg) When I select all rows from table zvw\_test it return 145 rows. Table Customer\_Class\_Price have 160 rows. When I try to join this 2 table with 2 condition it return 122 rows. I don't understand why it not return all rows from ...
I had this problem before, I used a CTE to solve this, like: ``` WITH A AS ( SELECT Customer_Class_Price.Goods_ID, Customer_Class_Price.UM, Customer_Class_Price.ListPrice FROM Customer_Class_Price WHERE Customer_Class_Price.ClassCode = '444-666' ) SELECT zvw_test.Goods_ID, zvw_test.Thai_Name, zvw_test.UM...
By putting one of your columns from the `LEFT OUTER JOIN` table in your `WHERE` clause, you have effectively turned it into an `INNER JOIN`. You need to move that up to the `JOIN` clause.
Left outer join with 2 column missing some output rows
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am selecting a date column which is in the format "YYYY-MM-DD". I want to cast it to a timestamp such that it will be "YYYY-MM-DD HH:MM:SS:MS" I attempted: ``` select CAST(mycolumn as timestamp) from mytable; ``` but this resulted in the format YYYY-MM-DD HH:MM:SS I also tried ``` select TO_TIMESTAMP(mycolumn,Y...
It seems that the functions `to_timestamp()` and `to_char()` are unfortunately not perfect. If you cannot find anything better, use these workarounds: ``` with example_data(d) as ( values ('2016-02-02') ) select d, d::timestamp || '.0' tstamp from example_data; d | tstamp -----------...
``` SELECT to_char(current_timestamp, 'YYYY-MM-DD HH:MI:SS:MS'); ``` prints ``` 2016-02-05 03:21:18:346 ```
Two questions for formatting timestamp and number using postgresql
[ "", "sql", "postgresql", "timestamp", "rounding", "greenplum", "" ]
I'm trying to group sales data based on a sellers' name. The name is available in another table. My tables look like this: **InvoiceRow:** ``` +-----------+----------+-----+----------+ | InvoiceNr | Title | Row | Amount | +-----------+----------+-----+----------+ | 1 | Chair | 1 | 2000.00 | | 2 ...
Try This ``` SELECT seller, SUM(amount) FROM InvoiceRow JOIN InvoiceHead ON InvoiceRow.InvoiceNr = InvoiceHead.InvoiceNr GROUP BY InvoiceHead.seller; ``` OR If you want to between two date. Try This ``` SELECT seller, SUM(amount) FROM InvoiceRow JOIN InvoiceHead ON InvoiceRow.InvoiceNr = InvoiceHead.InvoiceNr WH...
You just need to join the tables, filter result by date as you need and then make grouping: ``` select H.Seller, sum(R.Amount) as Amount from InvoiceHead as H left outer join InvoiceRow as R on R.InvoiceNr = H.InvoiceNr where H. Date >= '2016-01-01' AND H.Date < '2016-02-01' group by H.Seller ```
SQL sum and group values from two tables
[ "", "sql", "" ]
I want to select second highest value from tblTasks(JobID, ItemName, ContentTypeID) That's what I though of. I bet it can be done easier but I don't know how. ``` SELECT Max(JobID) AS maxjobid, Max(ItemName) AS maxitemname, ContentTypeID FROM (SELECT JobID, ItemName, ContentTypeID FROM...
I'm guessing you'd want something like this. ``` SELECT JobID AS maxjobid, ItemName AS maxitemname, ContentTypeID FROM (SELECT JobID, ItemName, ContentTypeID, ROW_NUMBER() OVER (PARTITION BY ContentTypeID ORDER BY JobID DESC) Rn FROM tblTas...
I would suggest `DENSE_RANK()`, if you want the second `JobID`: ``` SELECT tb.* FROM (SELECT tb.*, DENSE_RANK() OVER (ORDER BY JobID DESC) as seqnum FROM tblTasks Tb ) tb WHERE seqnum = 2; ``` If there are no duplicates, then `OFFSET`/`FETCH` is easier: ``` SELECT tb.* from tblTasks ORDER BY JobId OFFSET ...
Select second MAX value
[ "", "sql", "sql-server", "max", "" ]
In my table each row has some data columns `Priority` column (for example, timestamp or just an integer). I want to group my data by ID and then in each group take latest not-null column. For example I have following table: ``` id A B C Priority 1 NULL 3 4 1 1 5 6 NULL...
This should do the trick, everything raised to the power 0 will return 1 except null: ``` DECLARE @t table(id int,A int,B int,C int,Priority int) INSERT @t VALUES (1,NULL,3 ,4 ,1), (1,5 ,6 ,NULL,2),(1,8 ,NULL,NULL,3), (2,634 ,346 ,359 ,1),(2,34 ,NULL,734 ,2) ;WITH CTE as ( SELECT id, CASE WHEN row_nu...
One alternative that might be faster is a multiple join approach. Get the priority for each column and then join back to the original table. For the first part: ``` select id, max(case when a is not null then priority end) as pa, max(case when b is not null then priority end) as pb, max(case when ...
Aggregate data from multiple rows into single row
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have a component that retrieves data from database based on the keys provided. However I want my java application to get all the data for all keys in a single database hit to fasten up things. I can use 'in' clause when I have only one key. While working on more than one key I can use below query in oracle ``` SELE...
This syntax doesn't exist in SQL Server. Use a combination of `And` and `Or`. ``` SELECT * FROM <table_name> WHERE (value_type = 1 and CODE1 = 'COMM') OR (value_type = 1 and CODE1 = 'CORE') ``` (In this case, you could make it shorter, because value\_type is compared to the same value in both combinations. I j...
If you have under 1000 tuples you want to check against and you're using SQL Server 2008+, you can use a [table values constructor](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008/dd776382(v=sql.100)?redirectedfrom=MSDN), and perform a join against it. You can only specify up to 1000 rows in a t...
'In' clause in SQL server with multiple columns
[ "", "sql", "sql-server", "oracle", "" ]
Consider a table: ``` ╔══════╦════════════╦═════════╦════════════════════╦═════════╗ ║ Name ║ License No ║ Status ║ Status_update_date ║ Address ║ ╠══════╬════════════╬═════════╬════════════════════╬═════════╣ ║ Jon ║ 1234 ║ Active ║ 01/01/2016 ║ aaaa ║ ║ Rick ║ 5678 ║ Expired ║ 31/11/2015...
You need an `OR` condition for **status** and **Status\_update\_date** as they can't occur at same time. ``` SELECT * FROM table_name WHERE status = 'Active' OR ( status = 'Expired' AND Status_update_date >= SYSDATE -30 ); ``` To get the current date, you could use `SYSDATE` or `CURRENT_DATE` given that t...
You can try this: ``` SELECT * FROM myatble WHERE Stauts = 'Active' OR Expiration_DT > sysdate-30 ```
Filtering a query on a particular criteria like records for last 30 days
[ "", "sql", "oracle", "" ]
Here is my sample table with only a bit of info. ``` select * from juniper_fpc'; id | router | part_name -----------+-----------+-------------------- 722830939 | BBBB-ZZZ1 | MPC-3D-16XGE-SFPP 722830940 | BBBB-ZZZ1 | MPC-3D-16XGE-SFPP 723103163 | AAAA-ZZZ1 | DPCE-R-40GE-SFP 72310316...
This should perform well: ``` SELECT j1.router FROM ( SELECT router FROM juniper_fpc WHERE part_name LIKE 'MPC%' GROUP BY router ) j1 LEFT JOIN juniper_fpc j2 ON j2.router = j1.router AND j2.part_name NOT LIKE 'MPC%' WHERE j2.router IS NULL ORDER BY j1.router; ...
Assuming you want the routers that only have part\_name like 'MPC%', you can use a conditional count: ``` select * from ( select router, count(case when part_name like 'MPC%' then 1 else null end) as cnt_mpc, count(*) as cnt_overall from juniper_fpc group by router) v_inner where cnt_mpc = cnt_overall...
GROUP BY isn't working as expected
[ "", "sql", "postgresql", "aggregate", "" ]
How can I get a RANK that restarts at partition change? I have this table: ``` ID Date Value 1 2015-01-01 1 2 2015-01-02 1 <redundant 3 2015-01-03 2 4 2015-01-05 2 <redundant 5 2015-01-06 1 6 2015-01-08 1 <redundant 7 2015-01-09 1 <redundant 8 2015-01-10...
``` select * from ( select ID, Date, Value, lag(Value, 1, 0) over (order by ID) as ValueLag from table ) tt where ValueLag is null or ValueLag <> Value ``` if the order is Date then over (order by Date) this should show you good and bad - it is based on ID - it you need date then revise it may look like ...
Here is a somewhat convoluted way to do it: ``` WITH CTE AS ( SELECT *, ROW_NUMBER() OVER(ORDER BY [Date]) RN1, ROW_NUMBER() OVER(PARTITION BY Value ORDER BY [Date]) RN2 FROM dbo.YourTable ), CTE2 AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY Value, RN1 - RN2 ORDER BY [Date]) N ...
RANK() OVER PARTITION with RANK resetting
[ "", "sql", "sql-server", "window-functions", "" ]
I have two tables - Client and Banquet ``` Client Table ---------------------------- ID NAME 1 John 2 Jigar 3 Jiten ---------------------------- Banquet Table ---------------------------- ID CLIENT_ID DATED 1 1 2016.2.3 2 2 2016.2.5 3 2 2016.2....
For this query, I suggest applying your `WHERE` condition `>= CURDATE()` and then `SELECT` the `MIN(dated)` with `GROUP BY client_id`: ``` SELECT b.client_id, MIN(b.dated) FROM banquet b WHERE b.dated >= CURDATE() GROUP BY b.client_id; ``` From this, you can add the necessary `JOIN` to the client table to get the cli...
One approach uses a correlated subquery: ``` select c.*, (select max(dated) from banquet b where b.client_id = c.id and b.dated >= CURDATE() ) as dated from client c; ``` Then, I would recommend an index on `banquet(client_id, dated)`. The advantage of this approach is per...
MySQL get the nearest future date to given date, from the dates located in different table having Common ID
[ "", "mysql", "sql", "join", "" ]
I need to split a date like '01/12/15' and replace the year part from 15 to 2015 (ie; 01-12-2015). I get the year by the sql query: ``` select YEAR('10/12/15') ``` It returns the year 2015. but I have to replace 15 to 2015. how do i achieve this. Anyone here please help me. thanks in advance.. Edited: I've tried fo...
As you said your column is in `varchar` type, try the following **Query** ``` CREATE TABLE #temp ( dt VARCHAR(50) ); INSERT INTO #temp VALUES ('01/12/15'), ('02/12/15'), ('03/12/15'), ('04/12/15'), ('05/12/15'); UPDATE #temp SET dt = REPLACE(LEFT(dt, LEN(dt) - 2) + CAST(YEAR(CAST(dt AS DATE)) AS VARCHAR(...
Problem with your query is that you haven't specified length for `varchar` datatype: ``` declare @date varchar(12)='10/12/2015' declare @datenew date SELECT @datenew=CONVERT(nvarchar(10), CAST(@date AS DATETIME), 103) print @datenew ```
Splitting a datetime and replace the year part
[ "", "sql", "sql-server-2008", "datetime", "" ]
I need some help for a problem that i am struggling to solve. Example table: ``` ID |Identifier1 | Identifier2 --------------------------------- 1 | a | c 2 | b | f 3 | a | g 4 | c | h 5 | b | j 6 | d | f ...
Here is a variant that doesn't use cursor, but uses a single recursive query. Essentially, it treats the data as edges in a graph and traverses recursively all edges of the graph, stopping when the loop is detected. Then it puts all found loops in groups and gives each group a number. See the detailed explanations of...
This script produces the outputs for test sets 1, 2 and 3 as required. Notes on the algorithm as comments in the script. Be aware: * This algorithm **destroys** the input set. In the script the input set is `#tree`. So using this script requires inserting the source data into `#tree` * This algorithm does not work fo...
How to find all connected subgraphs of an undirected graph
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table of ward ``` ward_number | class | capacity ________________________________________ 1 | A1 | 1 2 | A1 | 2 3 | B1 | 3 4 | C | 4 5 | B2 | 5 ``` *capacity = how many beds there is in the ward* I also have a table called ward\_stay: ``` wa...
``` select w.ward_number, w.capacity - count(ws.ward_number) AS "result" from ward as w left join ward_stay as ws on ws.ward_number = w.ward_number and date '2015-05-19' between ws.from_date and ws.to_date where w.class = 'B1' -- which class -- bed not occupied on that date group by w.ward_number, w.capacity ...
**[SQL Fiddle Demo](http://sqlfiddle.com/#!15/2ab55/12)** Using `2015-01-17` instead I calculate the total of `occupied` bed on that day. Then join back to substract from original `capacity`. in case all bed are free the `LEFT JOIN` will return `NULL`, so `COALESCE` will put `0` ``` SELECT w."ward_number", "capacity"...
How to subtract two columns in different table
[ "", "sql", "" ]
I Get the following error when i try to update my table although there's n't any sub query : ``` Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. ``` --- MY QUERY : ``` UPDATE t1 SET t1.modified = 2 FROM TransA...
Triggers are executed per **statement**, not per **row**, that's the source of your error. Your trigger assumes that the inserted and deleted tables will only ever have one row, however that is simply wrong. The number of rows in the inserted / deleted tables is the number of rows effected by the DML statement (updat...
Your query is ok. The problem is the trigger. `inserted` and `deleted` are tables (well, really views but that is irrelevant), so they can contain multiple rows. Assuming that `transactions` has a primary key, you can check the update by doing ``` declare @userid int , @date date ; if (exists (select 1 f...
Update fails because Subquery returned more than 1 value
[ "", "sql", "sql-server", "sql-update", "subquery", "inner-join", "" ]
Basically I get this from a simple select query: ``` SELECT Site.RefID, SiteName, Dates.Date, Dates.Type FROM Site, Dates WHERE Site.RefID = Dates.RefID; RefID | SiteName | Date | Type 1 Sydney 06-12-15 OPENED 1 Sydney 08-12-15 CLOSED 2 Mel 17-12-15 OPENED 2 ...
Try the following approach, using `case` expression: ``` select s.RefID , s.Name , min(case when d.Type == 'OPENED' then d.Date end) as DateOPENED , min(case when d.Type == 'CLOSED' then d.Date end) as DateCLOSED from Site s join Dates d on s.RefID = d.RefID group by s.RefID, s.Name ```
``` SELECT A.RefId, A.SiteName, A.Date DateOpened, B.Date DateClosed FROM #tbl A JOIN #tbl B ON A.RefId = B.RefID AND A.Type = 'OPENED' AND B.Type = 'CLOSED' ``` For the sake of simplicity, have replaced the query with `#tbl`(you can deal with it howsoever you'd like to).
SQL query: Separate column where IDs are the same but type is different
[ "", "mysql", "sql", "" ]
Is it possible to combine multiple CTEs in single query? I am looking for way to get result like this: ``` WITH cte1 AS ( ... ), WITH RECURSIVE cte2 AS ( ... ), WITH cte3 AS ( ... ) SELECT ... FROM cte3 WHERE ... ``` As you can see, I have one recursive CTE and two non recursive.
Use the key word `WITH` *once* at the top. If any of your Common Table Expressions (CTE) are recursive (rCTE) you have to add the keyword `RECURSIVE` at the top *once* also, even if not all CTEs are recursive: ``` WITH RECURSIVE cte1 AS (...) -- can still be non-recursive , cte2 AS (SELECT ... UNI...
Yes. You don't repeat the `WITH`. You just use a comma: ``` WITH cte1 AS ( ... ), cte2 AS ( ... ), cte3 AS ( ... ) SELECT ... FROM 'cte3' WHERE ... ``` And: Only use single quotes for string and date constants. Don't use them for column aliases. They are not allowed for CTE names anyway.
How to use multiple CTEs in a single SQL query?
[ "", "sql", "postgresql", "common-table-expression", "recursive-cte", "" ]
I've a simple SQL table which looks like this- ``` CREATE TABLE msg ( from_person character varying(10), from_location character varying(10), to_person character varying(10), to_location character varying(10), msglength integer, ts timestamp without time zone ); ``` [![sample data](https://i.s...
As is well known, every table in Postgres has a primary key. Or should have at least. It would be great if you had a primary key defining expected order of rows. Example data: ``` create table msg ( id int primary key, from_person text, to_person text, ts timestamp without time zone ); insert into ms...
**Building on your *actual* question**, this would be a correct answer: ``` SELECT count(m2.to_person) AS ct_3min FROM msg m1 LEFT JOIN msg m2 ON m2.to_person = m1.to_person AND (m2.from_person, m2.from_location) <> (m1.from_person, m1.from_location) AND m2.ts <= m1.ts -- including same timestamp (?)...
In SQL how to select previous rows based on the current row values?
[ "", "sql", "postgresql", "window-functions", "" ]
I have a table like this: ``` +----+-----------+------+-------+--+ | id | Part | Seq | Model | | +----+-----------+------+-------+--+ | 1 | Head | 0 | 3 | | | 2 | Neck | 1 | 3 | | | 3 | Shoulders | 2 | 29 | | | 4 | Shoulders | 2 | 3 | | | 5 | Stomach | 5 | 3 ...
If you do not maintain a counter table, there are two options. Within a transaction, first select the `MAX(seq_id)` with one of the following table hints: 1. `WITH(TABLOCKX, HOLDLOCK)` 2. `WITH(ROWLOCK, XLOCK, HOLDLOCK)` `TABLOCKX + HOLDLOCK` is a bit overkill. It blocks regular select statements, which can be consid...
The correct way to handle such insertions is to use an `identity` column or, if you prefer, a sequence and a default value for the column. However, you have a `NULL` value for the `seq` column, which does not seem correct. The problem with a query such as: ``` Insert into yourtable(id, Part, Seq, Model) Select 6...
How to get the next number in a sequence
[ "", "sql", "sql-server", "sql-server-2014", "" ]
I need help with this task: I have a table in a MsSql database where I store inter users messages. I need a query to select the last message for each of the user conversation (WhatApp like list of conversations for a user). Table structure (**x is the message ID, GUID, and is unique for each message, txtMsg is the tex...
You can use `row_nubmer` with case logic to get the smallest and largest user ids: ``` select m.* from (select m.*, row_number() over (partition by (case when fromuserid < touserid then fromuserid else touserid end), (case when fromuserid < touserid then tous...
Pretty much the same as answer by Gordon Linoff. I just added a filter for user id = 1 (either `from` or `to`). And I put the query in your [SQL Fiddle](http://sqlfiddle.com/#!3/6ffbe/17/15). The `ROW_NUMBER` partitions all rows into conversations and then assigns sequential numbers to each row in the conversation sta...
sql query to group data by conversation
[ "", "sql", "sql-server", "t-sql", "" ]
I got three tables. I want to query the badges table to get the badge if all the missions exists for the `badge_id` in the `badge_requirements` table. In the case below, the badge would be returned because for `badge_id = 1`, all missions exist. But if, for example, one record in the `finished_missions` table would n...
There are many ways. This should be one: ``` SELECT badge_id FROM ( -- count missions per badge for the given user SELECT br.badge_id, count(*) AS ct FROM finished_missions fm JOIN badge_requirements br USING (mission_id) WHERE fm.user_id = 221 GROUP BY 1 ) u -- count missions per badge tot...
One method is a counting method: ``` select br.badge_id from badge_requirements br group by br.badge_id having count(distinct mission_id) = (select count(*) from missions); ``` This returns the `badge_id`. If you want more information, join back to the `badges` table or use `in`. And, if there are no duplicates in `...
Select badges from table only if all requirements rows exist
[ "", "sql", "postgresql", "relational-division", "" ]
``` select distinct account_num from account order by account_num; ``` The above query gave the below result ``` account_num 1 2 4 7 12 18 24 ...
This is another solution. ``` SELECT * FROM (SELECT DISTINCT MIN(val) over(PARTITION BY gr) min_, MAX(val) over(PARTITION BY gr) max_ FROM (SELECT val, decode(trunc(rn / 3), rn / 3, rn / 3, ceil(rn / 3)) gr ...
You can use the example below as a scratch, this is only based on information you have provided so far. For further documentation, you can consult Oracle's [analytical functions](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm#SQLRF06174) docs: ``` with src as( --create a source data select 1 ...
Split a column into multiple columns
[ "", "sql", "oracle", "plsql", "oracle11g", "" ]
[![enter image description here](https://i.stack.imgur.com/hhtMw.png)](https://i.stack.imgur.com/hhtMw.png) In SQL Server 2008 R2 I have a table (database size is 450 GB) with over a billion rows, which I'd like to purge by deleting all records older than 180 days counting from the current date. Any help here would be...
One approach that might save you some time: * Start off with taking a backup (you never know) * Insert the rows you want to keep into a temporary table (make sure you have enough room on disk for `tempdb`) * `TRUNCATE` the table to remove all rows quickly (this statement will execute instantly) * Insert the rows from ...
It's taking a long time because (in part) all of those deletes are going into one gargantuan transaction. You need to break it down into smaller chunks (transactions) and periodically commit. It'll still take a long time but the impact on your server will be lessened. See <https://stackoverflow.com/a/28324562/1324345> ...
Purge by deleting all records older than 180 days from the current date in SQL Server
[ "", "sql", "sql-server", "sql-delete", "" ]
I need to run a query in SQL Server, where I have a particular number of values stored individually on separate lines in a text file, and I need to run a query in SQL server to check if a value in a column of the table matches any one of the value stored in the txt file. How should I go about doing this ? I am aware ...
One option would be to use BULK INSERT and a temp table. Once in the temp table, you can parse the values. This is likely not the exact answer you need, but based on your experience, I'm sure you could tweak as needed. Thanks... ``` SET NOCOUNT ON; USE Your_DB; GO CREATE TABLE dbo.t ( i int, n varchar(10)...
1. Bulk import the data from text file into a temporary table. 2. Execute the query to do the comparison between your actual physical table & temporary table.
SQL Server : Query using data from a file
[ "", "sql", "sql-server", "" ]
Dear friends on Stackoverflow, I recently started learning SQL and I'm currently trying to add ' as a value into MYSQL Community edition. For example, In order to add the letter A id' put ``` INSERT INTO symbols (test_chars) VALUES ('A'); ``` But If I wanted to add the ' itself how would go about doing that? ''' I...
The [documentation](http://dev.mysql.com/doc/refman/5.7/en/string-literals.html) is your best friend. [It says](http://dev.mysql.com/doc/refman/5.7/en/string-literals.html#idm140153918913264): > There are several ways to include quote characters within a string: > > * A `'` inside a string quoted with `'` may be writ...
You use a lot of single quotes. Doubling a single quote in a string is a single quote. So, four single quotes in a row defines a string with one single quote: ``` INSERT INTO symbols (test_chars) VALUES (''''); ``` The quotes at the beginning and end delimit the string. The two quotes in the middle are the single quo...
How to add ' as a value into SQL
[ "", "mysql", "sql", "" ]
I have two `tables` have Account-Codes As Below, ``` table 1: account 50000 50006 50015 50105 50150 50155 50165 table 2: Account 50000 50010 50140 50105 50150 50155 50165 ``` I need to Join these two `tables`. If any account codes of `table-1` is not matching with `table-2`, then I have implicitly change table...
use `CASE` then `DISTINCT` the data, that will give you generic solution ``` -- table1 declare @table1 table (account bigint) insert into @table1 values (50000) insert into @table1 values (50006) insert into @table1 values (50015) insert into @table1 values (50105) insert into @table1 values (50150) insert into @ta...
Try this [SQL Fiddle](http://sqlfiddle.com/#!3/c7671/5) ``` SELECT T1.Account, T2.Account FROM table1 t1 INNER JOIN table2 t2 on (t1.account = CASE t1 .account WHEN 50015 THEN t2 .account+5 WHEN 50006 THEN t2 .account-134 ELSE t2 .account ...
Inner Join with CASE statement is not working in SQL SERVER
[ "", "sql", "sql-server", "t-sql", "" ]
I have a column in SQL where in the data is stored as 102915, 060315 and so on. The data type of the column is `nvarchar(50)`. I want to convert the above data to a date format. It should look like 10-29-15 or 10/29/15. How can I convert the above in SQL Server Management Studio 2008? Tried quite a few things: One o...
You can try this: ``` DECLARE @date VARCHAR(50) = '102915' SELECT CAST( CAST( '20'+ --prefix for the year 2000 SUBSTRING( @date,5,2)+ --year SUBSTRING( @date,1,2)+ --month SUBSTRING( @date,3,2) --day AS VARCHAR(10)...
This is a lot simpler: ``` select convert(nvarchar(50), convert(date, RIGHT('102915',2) + LEFT('102915',4), 112), 110) ``` and respectively: ``` create view v1 as Select convert(nvarchar(50), convert(date, RIGHT([ISSUE],2) + LEFT([ISSUE],4), 112), 110) as ISSUE, convert(nvarchar(50), convert(dat...
Converting nvarchar to DATE
[ "", "sql", "sql-server", "sql-server-2008", "ssms", "" ]
there is need to compare two column value find and want to find out difference between this two column value and at the end , want to display all the values present in that table where we find out maximum difference ``` companyname open close date A 10 9.8 2015-01-01 A 1...
As an alternative to the self-join in [@TimBiegeleisen's answer](https://stackoverflow.com/a/35286110/44853), you can use a windowing function to order by the difference partitioned by `companyname`, then select the first row from each partition: ``` select [companyname] as [company name], [open], [close], [difference...
A simple `INNER JOIN` of your original table to a subquery obtaining the maximum differences for each company is all you need. ``` SELECT c1.companyname, c1.open, c1.close, c2.maxTime AS difference, c1.date FROM companies c1 INNER JOIN ( SELECT companyname, MAX(open - close) AS maxTime FROM companies GROUP...
maximum differenence between two column
[ "", "sql", "sql-server-2012", "" ]
I want to pass a temp table from one execution path to another one nested in side it What I have tried is this: ``` DECLARE @SQLQuery AS NVARCHAR(MAX) SET @SQLQuery = ' --populate #tempTable with values EXECUTE('SELECT TOP (100) * FROM ' + tempdb..#tempTable) EXECUTE sp_executesql @SQL...
Your temp table will be visible inside the dynamic sql with no problem. I am not sure if you are creating the temp table inside the dynamic sql or before. Here it is with the table created BEFORE the dynamic sql. ``` create table #Temp(SomeValue varchar(10)) insert #Temp select 'made it' exec sp_executesql N'select ...
You can create a global temp table using the `##tablename` syntax (double hash). The difference is explained [on the TechNet site](https://technet.microsoft.com/en-us/library/ms177399(v=sql.105).aspx): > There are two types of temporary tables: local and global. They differ from each other in their names, their visibi...
Passing temp table from one execution to another
[ "", "sql", "sql-server", "sql-server-2012", "" ]
To perform good performance with Spark. I'm a wondering if it is good to use sql queries via `SQLContext` or if this is better to do queries via DataFrame functions like `df.select()`. Any idea? :)
There is no performance difference whatsoever. Both methods use exactly the same execution engine and internal data structures. At the end of the day, all boils down to personal preferences. * Arguably `DataFrame` queries are much easier to construct programmatically and provide a minimal type safety. * Plain SQL quer...
Ideally, the Spark's catalyzer should optimize both calls to the same execution plan and the performance should be the same. How to call is just a matter of your style. In reality, there is a difference accordingly to the report by Hortonworks (<https://community.hortonworks.com/articles/42027/rdd-vs-dataframe-vs-spark...
Spark sql queries vs dataframe functions
[ "", "sql", "performance", "apache-spark", "dataframe", "apache-spark-sql", "" ]
How to make stored procedure dynamic search with `SQL Server` with name table and name filed and value filed ``` select * from @nametable where @filedname = @valuename ```
``` 1. DECLARE @value AS SMALLINT 2. DECLARE @SQLQuery AS NVARCHAR(500) 3. DECLARE @NameTable AS NVARCHAR(500) 4. DECLARE @field AS NVARCHAR(500) 5. SET @value = 2 6. SET @NameTable = 'Suppliers' 7. SET @field = 'Id' 8. SET @SQLQuery = 'SELECT * FROM '+@NameTable+' WHERE '+@field+' = ' + CAST(@value AS NVARCHAR(10)...
You can use dynamic SQL Example: ``` DECLARE @nametable VARCHAR(150)='MyTable' --You can change the name here DECLARE @fieldname VARCHAR(150)='MyField' DECLARE @valuename INT=4 --You must be careful here because you have to know the datatype of field to determine data type of parameter DECLARE @sqlT...
How to make stored procedure dynamic search with SQL Server
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have two tables that almost have identical columns. The first table contains the "current" state of a particular record and the second table contains all the previous stats of that records (it's a history table). The second table has a FK to the first table. I'd like to query both tables so I get the entire records ...
To accomplish this, you could use a `UNION` between two `SELECT` statements. I would also suggest selecting from a *derived table* in the following manner so that you can sort by columns in your result set. Suppose we wanted to combine results from the following two queries: ``` SELECT FieldA, FieldB FROM table1; SELE...
UNION. ``` Select colA, colB From TblA UNION Select colA, colB From TblB ```
Query Two Tables - but not trying to JOIN?
[ "", "mysql", "sql", "database", "" ]
I want to merge two tables with different columns mysql. For e.g. Table 1 : ``` ------------------------------------------------------------- item_id title slug type views updatedAt createdAt ------------------------------------------------------------- 1 sometitle someslg 1 43454 timestamp ...
Just add the column in: ``` SELECT t3.* FROM ((SELECT t1.item_id, t1.title, t1.slug, t1.type, t1.views, t1.updatedAt, t1.createdAt, 't1' as from_tbl FROM table1 t1 ) UNION ALL (SELECT t2.id, t2.ptitle, t2.slug, '', t2.pviews, t2.updatedAt, t2.createdAt, 't2' ) ) t3 ORDER BY t3.item_id ASC...
try this way ``` SELECT t3.* FROM ((SELECT t1.item_id, t1.title, t1.slug, t1.type, t1.views, t1.updatedAt, t1.createdAt, '1' as from_tbl FROM table1 t1 ) UNION ALL (SELECT t2.id, t2.ptitle, t2.slug, '', t2.pviews, t2.updatedAt, t2.createdAt, '2' FROM table2 t2 ) ) t3 ORDER BY t3.item_id ...
merge two tables with different columns mysql
[ "", "mysql", "sql", "" ]
Expected Output: [![enter image description here](https://i.stack.imgur.com/nOVEN.png)](https://i.stack.imgur.com/nOVEN.png) How can we run a query that returns "Robot" followed by a year between 2000 and 2099? (So 2015 is a valid value at the end, but 2123 is not.) [![enter image description here](https://i.stack.i...
Got the answer: ``` SELECT id, name FROM robots WHERE name LIKE '%Robot 20%_%' ```
``` SELECT name FROM robots WHERE name LIKE '%Robot 20__%' ``` If there might be other characters after `20` you need `REGEXP`: ``` SELECT name FROM robots WHERE name REGEXP 'Robot 20[0-9][0-9]' ```
SQL Like Operator
[ "", "mysql", "sql", "select", "where-clause", "sql-like", "" ]
I have to modify a big pricelist table so that there is only one valid price for every article. Sometimes the sales employees insert new prices and forgot to change the old infinite validTo dates. So I have to write a sql-query to change all validTo dates to the next validFrom date minus one day, when the validTo date...
In order to update an end date you can simply select the minimum of all higher start dates. ``` update mytable upd set enddate = coalesce( ( select min(startdate) - 1 from mytable later where later.startdate > upd.startdate and later.anr = upd.anr -- same product ), date'9999-12-31') -- coalesce for the case t...
Oracle provides an analytic function `LEAD` that references the current-plus-n-th record given a sort criterion. This function may serve the purpose of selecting the proper date value in an update statement as follows ( let `test_prices` be the table name, `ppk` its PK ): ``` update test_prices p set p.vali...
sql-query that change all validTo dates to the next validFrom date minus one Day
[ "", "sql", "oracle", "" ]
I need to build SQL query to get all users metadata (`meta`) from `signup` table which `id` is in `courses_history` table. The problem is that `signup` table don't have `user_id` but does have `user_login` and `courses_history` have only `user_id`. There is the third table - `users`, which holds `user_id` and `user_l...
``` SELECT ch.id, u.user_login, su.meta FROM signups su INNER JOIN users u ON su.user_login = u.user_login INNER JOIN courses_history ch ON u.user_id = ch.user_id ```
``` SELECT s.meta FROM signups AS s INNER JOIN courses_history AS ch ON s.id = ch.id INNER JOIN users AS u ON ch.user_id = u.user_id ``` You can pull whatever data you want out of all three of the tables with this, but I believe this illustrates the point well enough.
How connect two SQL tables that don't have common columns using third table, which contains columns of those both
[ "", "mysql", "sql", "" ]
I have a Package table in BigQuery as follows: ``` Packageid Scanid dispatchid timestamp status p1 s1 null t1 'in' p2 s1 xxx t2 'in' p1 s2 yyy t3 'pkin' p1 s3 sss t4 'iwi' p1 ...
One method uses windows functions and conditional aggregation: ``` select packageid, max(case when seqnum = 1 then dispatchid end) as dispatchid, min(case when dispatchid is not null then timestamp end) as first_dispatchid, max(case when dispatchid is not null then timestamp end) as last_dispatchi...
I will note that this is for SQL Server and may or may not work in MYSQL. ``` SELECT Packageid, MAX(Scanid) [Latest_Scanid], MIN(timestamp) [First-Dispatch-time], MAX(timestamp) [Last-Dispatch-time], (SELECT status FROM Package p WHERE p.timestamp = Package.timestamp AND p.Packageid = Package.Packag...
Querying in BigQuery?
[ "", "sql", "database", "google-bigquery", "user-defined-functions", "" ]
I need to add to columns in a row. Table Data | id | Col1 | Col2 | | --- | --- | --- | | 1 | 10 | 20 | | 2 | 11 | 20 | | 3 | 12 | 20 | Result expected | id | Sum | | --- | --- | | 1 | 30 | | 2 | 31 | | 3 | 32 | I tried `sum(col1 + col2)`, but that gives the sum of all the columns together.
`sum()` is a *aggregating* function (one that give a single result for a group of rows), not a *algebraic* one: You want the *addition* (the *mathematical* sum) of the two columns: ``` select id, col1 + col2 as sum from mytable ```
we have two type of columns in group clause (Aggregation column and Group column) in this query ``` select id, col1 + col2 as sum from mytable group by id ``` we have to insert `id`, `col1` and `col2` in front of `group by`, otherwise we get this error > Column 'TEST.COL1' is invalid in the select list because it i...
DB2, SQL query to SUM 2 columns
[ "", "sql", "oracle", "" ]
I have following query (`BOCRTNTIME - varchar e.g 2015-02-28 12:21:45, VIEW_BASE_MARIX_T - some view`): ``` select BOCRTNTIME from VIEW_BASE_MARIX_T where to_date(substr(BOCRTNTIME,1,10),'YYYY-MM-DD') between (to_date ('2016-01-01', 'YYYY-MM-DD')) and (to_date ('2016-02-01', 'YYYY-MM-DD')) ...
I think that what might be happening is that Oracle is pushing the predicate to the underlying tables of the view. Have you tried to run the query ``` select to_date(substr(BOCRTNTIME,1,10),'YYYY-MM-DD') BOCRTNTIME from MY_TABLE ``` instead of querying the view? you can also confirm this by using the NO\_PUSH\_PRED...
A bit too long for a comment - create a simple function to test the dates: ``` CREATE FUNCTION is_Valid_Date( in_string VARCHAR2, in_format VARCHAR2 DEFAULT 'YYYY-MM-DD' ) RETURN NUMBER DETERMINISTIC AS dt DATE; BEGIN dt := TO_DATE( in_string, in_format ); RETURN 1; EXCEPTION WHEN OTHERS THEN RETURN 0;...
ORA-01839 "date not valid for month specified" for to_date in where clause
[ "", "sql", "oracle", "date-format", "to-date", "" ]
I dont know how to freame this question. But read the description. I have two tables as below, EntityProgress table- ``` EntityID CurrentStateID 101 1154 201 1155 301 1155 ``` EnityApprovar Table ``` EntityID StateID ActorID 201 1154 ...
Here is my attempt to answer you. **Query** ``` DECLARE @ActorID int = 2 DECLARE @EntityProgress table ( EntityID int, CurrentStateID int ) DECLARE @EnityApprovar table ( EntityID int, StateID int, ActorID int ) INSERT into @EntityProgress values (101, 1154), (201, 1155), ...
You'd have to include a `not exists` in the query as the row that you are trying to exclude when passing in 9 has no information to determine that there are other rows in the table that match. i.e. ``` SELECT E.EntityID, E.CurrentStateID FROM EntityProgress E LEFT JOIN EnityApprovar EP ON E...
Left Join and conditional where not giving desired result?
[ "", "sql", "sql-server", "join", "where-clause", "" ]
This may be a stupid question and very easy but i am very distracted right now, and didn't find any solution. I have a table like this: ``` ID | Value | Gr_Id | Gr_Value ------------------------------ a |0 |1 |Null b |2 |2 |Null c |4 |2 |Null d |1 |3 |Null e |3 |4 ...
I think this will solve your problem: ``` SELECT ID, Value, Gr_Id, ( SELECT MAX(Value) FROM tableName t2 WHERE t1.Gr_Id = t2.Gr_Id ) as Gr_Value FROM tableName t1 ``` Try it; hope it helps
Using `OUTER APPLY` you can do this ``` SELECT ID,Value,Gr_Id,M.Gr_Value FROM URTable OUTER APPLY ( SELECT MAX (Value) as Gr_Value FROM URTable tmp WHERE tmp.Gr_Id=URTable.Gr_Id )M ```
Set the maximum value of the group to each group id
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I would like to label quantities (in the `quantity table`) using the labels assigned (see `label assignment` table) until the quantity goes to 0. Then I know that I am done labeling that particular ID. `label assignment` table is as follows: ``` ID | Label | Quantity 1 aaa 10 1 bbb 20 2 ...
Simplest answer I think, after getting ideas from the other answers: Just create a "FAKE" label for the missing amount: ``` DECLARE @PerLabelQuantity TABLE(Id int, Label varchar(10), Quantity int); INSERT INTO @PerLabelQuantity VALUES (1, 'aaa', 10), (1, 'bbb', 20), (2, 'ccc', 20); SELECT * FROM @PerLabelQuantity D...
You can do it with a simple `JOIN` and `UNION` operation so as to include 'not covered' quantities: ``` SELECT la.ID, la.Label, la.Quantity FROM label_assignment AS la INNER JOIN quantity AS q ON la.ID = q.ID UNION SELECT q.ID, NULL AS Label, q.TotalQuantity - la.TotalQuantity FROM quantity AS q INNER JOIN ( S...
How would l write SQL to label quantities until they run out?
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Suppose you have a query that returns a record set like the following: ``` Date | Code | Val 1 | Val 2 1/1/2016 A 1 2 1/1/2016 B 3 4 1/2/2016 A 5 6 1/2/2016 B 7 8 1/2/2016 C 9 10 ``` And a second table that contain...
Sample Data: ``` CREATE TABLE #temp (DateField DATE , Code CHAR , Val1 INT, Val2 INT) INSERT INTO #temp VALUES ('1/1/2016','A','1','2'), ('1/1/2016','B','3','4'), ('1/2/2016','A','5','6'), ('1/2/2016','B','7','8'), ('1/2/2016','C','9','10') CREATE TABLE #Code (Code CHAR ) INSERT INTO #Code VALUES('A'), ('B')...
You don't say which database you are using; if you don't have CTE available you can also use a `Calendar` table. *I've assumed your data is a table of `Orders`, just to give the table a name.* ``` CREATE TABLE Orders (order_date date ,code varchar(1) ,val_1 int ,val_2 int); INSERT INTO Orders ([order_date], [...
How to Outer Join a Table onto a Subset of a Query
[ "", "sql", "" ]
Can anyone plese help me how can i join these table, i have used outer join but i am not sured what should i put in select statement. i don't want to put wildcard. Please help. Table ``` DECLARE @MASTER TABLE ( SKU VARCHAR (30), Resistor_ID VARCHAR (30), Capacitor_ID VARCHAR (30), Inductor_ID VARCHAR (30) ) INSERT @...
You need left outer joins like this: ``` SELECT distinct t1.sku,t2.resistor_id,t2.resistor_value,t3.capacitor_id,t4.inductor_id FROM master t1 LEFT OUTER JOIN resistor_child t2 ON(t1.resistor_id = t2.resistor_id) LEFT OUTER JOIN CAPACITOR_child t3 on(t1.capacitor_id = t3.capacitor_id) LEFT OUTER JOIN inductor_child t4...
This is a pretty basic left join. Left joins return all records from the table on the LEFT and only those that match from those on the right. So in this example: return all records from master and only those that match in each of the other tables. Thus you get the null values on those records where no matching record ...
Complexity in a join
[ "", "sql", "" ]
I am doing a report, and one of the tables called `tblProduct` has a calculation triggered in SQL Server that calculates cost on a column. I am having trouble locating the formula. Is there a way to determine what or where the formula is being pulled from ?
By the sounds of it you are looking for a calculated column. So if you are looking for the logic within a calculated column you can get this by simply doing the folowing: 1. Right click on the table 2. Go to script table as 3. Click on CREATE to. Within the definition then you should see the calculated column definit...
I figured it out , it maybe for someone in the future. It was in the server agent under Jobs and there were jobs that calculated another sp.
Where is the SQL Server 2012 formula stored?
[ "", "sql", "sql-server-2012", "" ]
I have 2 tables: 1) et\_pics - here information about employees: * ob\_no, int, key, e.g. 2020 * c\_name, varchar, e.g. Dribbler D.E. * e\_post, varchar, e.g. Chairman SELECT \* FROM et\_pics: > ob\_no | c\_name | e\_post > > 2020 | Dribbler D.E. | Chairman 2) et\_vacations – here information about vacation is s...
I believe your problem needs a bit more definition around what is considered the date of the vacation (the beginning date?, the end date?) you are interested in but here is a start. Note I left the join to division in since you had it but you are not using the data in that table in any of the select field or where clau...
I guess you need to output employees with nearest planed vacation(?). Then you should JOIN already prepared `et_vacations` table using LEFT JOIN in case of empty vacations records for some of employees: ``` WITH T_vac as ( select et_vacations.*, ROW_NUMBER() OVER (PARTITION BY e_pic ORDER BY e_dateTo) as RowNum ...
Problem with joining two tables on subquery condition
[ "", "sql", "sql-server", "sql-server-2005", "" ]
``` SELECT TO_CHAR((select logical_date -1 from logical_date where logical_date_type='B'),'DD/MM/YYYY HH24:MI:SS') FROM DUAL; ``` This Query returns `23/04/2016 00:00:00` ``` o/p of select logical_date -1 from logical_date where logical_date_type='B' :4/23/2016 SELECT TO_DATE((select logical_date -1 from logical_da...
Dates do not have any intrinsic format. Oracle has an internal representation which doesn't look like anything you'd recognise as a date. The client or application decides how to display the date (e.g. using NLS\_DATE\_FORMAT), or you can use `TO_CHAR` to convert the date to a string with a format you specify, as you'r...
The problem is related to the default date format for your session that is configured in your oracle client settings To check the NLS\_DATE\_FORMAT settings for your Session ``` SELECT value FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT' ``` here's how you can change this setting for your session ...
TO_CHAR and TO_DATE giving different results.How to achieve the TO_CHAR functionality using TO_DATE?
[ "", "sql", "oracle", "date-formatting", "to-date", "to-char", "" ]
Is there a way to convert the first letter uppercase in Oracle SQl without using the Initcap Function? I have the problem, that I must work with the DISTINCT keyword in SQL clause and the Initcap function doesn´t work. Heres is my SQL example: ``` select distinct p.nr, initcap(p.firstname), initcap(p.lastname), ill....
When `SELECT DISTINCT`, you can't `ORDER BY` columns that aren't selected. Use column aliases instead, as: ``` select distinct p.nr, initcap(p.firstname) fname, initcap(p.lastname) lname, ill.describtion from patient p left join illness ill on p.id = ill.id where p.deleted = 0 order by lname, fname ```
this would do it, but i think you need to post your query as there may be a better solution ``` select upper(substr(<column>,1,1)) || substr(<column>,2,9999) from dual ```
How to convert only first letter uppercase without using Initcap in Oracle?
[ "", "sql", "oracle", "" ]
I have no idea where to even start with this, but here's what i need to do... We have a table with addresses and telephone numbers in. But i need to reduce the 6 telephone number columns from 6 to 3. Moving the numbers along from right to left, into any empty cells. Example below - **What the table looks like** ![Wh...
`PIVOT` and `UNPIVOT` will be able to do the job. The idea: 1. `UNPIVOT` to get the data into rows 2. Clean out empty rows and calculate what the new column will be 3. `PIVOT` to get the cleaned data back into columns. Here's one way of doing it using a bunch of CTEs in one statement. Note I've assumed there is an ID...
There are a few different ways you can do this, the best choice depends on the database engine you're using, and/or what other tools are available. The dirtiest method might be to write 64 different sql statements fetching out the data in each of the 64 possible combinations (including where 6 fields are all blank, an...
SQL moving data along columns
[ "", "sql", "sql-server", "sql-server-2012", "" ]
This seems really trivial, but for the life of me I cannot understand why this is not working. Any ideas would be great! ``` USE [ACCTQA] GO INSERT INTO [dbo].[glacct] ([Company] ,[Account] ,[Description]) VALUES ('E096','191802','INVESTMENT IN SUBS') ,('E096','320007','COMMON S...
Try this ``` USE [ACCTQA] GO INSERT INTO [dbo].[glacct] ([Company] ,[Account] ,[Description]) SELECT * FROM ( SELECT 'E096','191802','INVESTMENT IN SUBS' UNION ALL SELECT 'E096','320007','COMMON STOCK' UNION ALL SELECT 'E096','330013','SURPLUS' UNION ALL SELECT 'E096','340003','RET...
Your query won't work if you are using SQL Server 2005 or below. On those version you have to try like ``` INSERT INTO glacct ([Company],[Account],[Description]) SELECT 'E096','191802','INVESTMENT IN SUBS' UNION ALL SELECT 'E096','320007','COMMON STOCK' UNION ALL SELECT 'E096','330013','SURPLUS' ``` Your query wil...
SQL Insert statement with multiple rows
[ "", "sql", "sql-server", "" ]
``` select name, (regexp_split_to_array(name, '')) from table ``` The result is `{a,b,c,d,e}`. Is it possible to split that up to individual rows and group by name so that it looks like: ``` a 1 b 2 c 3 d 4 e 5 ```
If you are on 9.4 or later you can use `with ordinality`: ``` SELECT name, u.* FROM the_table cross join lateral unnest(regexp_split_to_array(name,'')) with ordinality as u(ch, nr) ```
You are looking for the [unnest](http://www.postgresql.org/docs/9.3/static/functions-array.html) function: ``` select name, unnest(regexp_split_to_array(name, '')) from table ```
Splitting characters after regexp_split_to_array
[ "", "sql", "postgresql", "unnest", "" ]
The tables will build, but every time I try to insert values into the table I get a 1452 error of foreign key constraints fails. I wonder if the problem has to do with EMPLOYEE table has a foreign key for STORE\_CODE in the STORE table, and STORE table has a foreign key for EMP\_CODE in EMPLOYEE table. Is the circular ...
In my experience with relational databases, I think you should create an intermediate table to conect "store" with "employee" (lets name it (store\_has\_employee) with the atributes(idstore(fk), idemployee(fk) and isManager(boolean)). Then you should insert the "regions" first, so you can insert a "store", then when y...
It's not possible to have mutual foreign keys unless you allow at least one of the columns to be `NULL`. Otherwise you can never have a consistent set of tables: If you add the store first, it will refer to a nonexistent employee; if you add the employee first, it will refer to a nonexistent store. So you need to allo...
What is the correct way of have foreign keys in tables that reference each other
[ "", "mysql", "sql", "" ]
I have a problem. I need to take the newly created table column (Field) I had just name "ID" and INDEX it (Unique). I have tried several ways with no success. All I'm asking is for someone to offer a fresh perspective. ~ Shaw ``` Public Sub OrcleJEtoUnmatched() Dim db As Database Dim tdf As DAO.TableDef Dim fld1 As DA...
If you want to stick with the DAO object model to create your field and index it, look at the *Index.CreateField Method* in Access' help system. But I think it's easier to do both by executing an `ALTER TABLE` statement ... ``` CurrentDb.Execute "ALTER TABLE Unmatched ADD COLUMN ID TEXT(255) UNIQUE;" ```
To add an index to a DAO tabledef object, use the createindex method. Here's the basic documentation; <https://msdn.microsoft.com/EN-US/library/office/ff196791.aspx>
How to INDEX a new DAO CreateField on the Fly - MS Access
[ "", "sql", "ms-access", "vba", "dao", "unique-index", "" ]
I have a column named "Date of Payment" ( a nvarchar(50) ) and I am trying to select all the rows which the date is in the year 2015. ``` Select ID,[Date of Payment] From mytable WHERE ('Date of Payment' BETWEEN '2015/01/1' AND '2015/12/31') ``` When I run the select statement above it doesn't return any rows. Th...
You can't use between because your date field is not type DATETIME. ``` Select ID,[Date of Payment] From mytable WHERE [Date of Payment] like '%2015%' ```
There is an error in the Where clause If I understood well, you use MS-SQL and in this dialect the field names are enclosed in square brackets , not in single quote marks. ``` Select [ID],[Date of Payment] From [mytable] WHERE ([Date of Payment] BETWEEN '2015/01/01' AND '2015/12/31' ) ```
SQL select between 2 dates not working
[ "", "sql", "" ]
I have a table with strings: ``` Orig_Value ----------- Abc_abc_1.2.3 PQRST.abc_1 XY.143_z ``` I want to split this using `_` and `.` with the desired output: ``` Original_Value Col1 Col2 Col3 Col4 Col5 ------------- ---- ---- ---- ---- ---- Abc_abc_1.2.3 Abc abc 1 2 3 ...
Here is one way to do it in `SQL Server` ``` ;WITH cte AS (SELECT Replace(col, '_', '.') + '.' AS col FROM (VALUES ('Abc_abc_1.2.3'), ('PQRST.abc_1'), ('XY.143_z')) tc (col)) SELECT original_col = col, column_1=COALESCE(LEFT(col, Charindex('.', col...
**`PostgreSQL`** Following as an exampple, ``` CREATE TABLE foo (org_val TEXT); INSERT INTO foo VALUES ('Abc_abc_1.2.3') ,('PQRST.abc_1') ,('XY.143_z'); ``` using [`regexp_split_to_array()`](http://www.postgresql.org/docs/9.5/static/functions-string.html) ``` SELECT org_val ,a [1] col1 ,a [2] c...
How to split value using underscore (_) and period (.)?
[ "", "mysql", "sql", "postgresql", "" ]
I know this question has been asked, but I have a slightly different flavour of it. I have a use case where the only thing I have control over is the WHERE clause of the query, and I have 2 tables. Using simple example: Table1 contains 1 column named "FULLNAME" with hundreds of values Table2 contains 1 column name...
One possible approach is to use `EXISTS` in combination with `LIKE` in the subquery: ``` select * from table1 t1 where exists (select null from table2 t2 where t1.fullname like '%' || t2.pattern || '%'); ```
If the patterns are always two characters and only have to match the start of the full name, like the examples you showed, you could do: ``` Select * from Table1 where substr(FULLNAME, 1, 2) IN (Select Pattern from Table2) ``` Which prevents any index on Table1 being used, and your real case may need to be more flexi...
Combine LIKE and IN using only WHERE clause
[ "", "sql", "oracle", "where-in", "" ]
I want to drop my tables in my database. But, when I use, for example, `DROP TABLE if exists users;` I receive this message: > cannot drop table users because other objects depend on it I found the solution is to drop all tables. But, anyway, how to solve this problem without total data removal?
Use the `cascade` option: ``` DROP TABLE if exists users cascade; ``` this will drop any foreign key that is referencing the `users` table or any view using it. It will not drop other *tables* (or delete rows from them).
If it was really necessary to drop that specific table with or without recreating it, then first find the object(s) that depends on it. ``` CREATE OR REPLACE VIEW admin.v_view_dependency AS SELECT DISTINCT srcobj.oid AS src_oid , srcnsp.nspname AS src_schemaname , srcobj.relname AS src_objectname , tgtobj.oid A...
Cannot drop table users because other objects depend on it
[ "", "sql", "database", "postgresql", "sql-drop", "drop-table", "" ]
I've two tables: **users** and **friendship**. For example: **users** table: ``` id | user | email | website 1 | Igor | i@o.com | stack.com 2 | Lucas | a@i.com | overflow.com 3 | John | j@w.com | www.com ``` **friendship** table (when `status = 2` means that they are friends): ``` id | friend1 | friend2 | s...
This is easily done with a simple `JOIN` that just includes your logic: ``` SELECT U.id, U.user, U.email, U.website FROM Friendship F INNER JOIN Users U ON (U.user = F.friend1 AND F.friend1 <> '$user') OR (U.user = F.friend2 AND F.friend2 <> '$user') WHERE F.friend1 = '$user' OR F.frien...
i think you can use ``` select * from user where user in ( select friends1 from friendship where friend2='$user' and status=2 union all select friends2 from friendship where friend1='$user' and status=2 ) ``` I added left join example ``` select u.* from ( select friends1 f from friendship where fri...
LEFT JOIN with relative value from main query
[ "", "mysql", "sql", "join", "left-join", "" ]
I have 3 possible delay categories for each gate. I am trying to find the Tot\_Delay\_Min at certain gates for each category, therefor I need to find a way to combine these Delay Categories into one Column and the total minutes for that category into another. DLY1MIN, DLY2MIN, and DLY3MIN correspond with DLY1CAT, DLY2C...
This is untested, and I'm sure there is a better way to do this, but this should work: ``` SELECT Gate, Category, SUM("Delay Minutes") AS "Delay Minutes" FROM ( SELECT Gate AS Gate, Dly1Cat AS Category, DLY1Min AS "Delay Minutes" FROM YourTable UNION ALL SELECT Gate AS Gate, ...
Try this one and let me know if it is working or not. ``` Select Gate, DLYCAT AS DLYCAT, SUM(DLYMIN) AS DLYMIN FROM (Select Gate, DLY1CAT AS DLYCAT, SUM(DLY1MIN) AS DLYMIN FROM [ExperimentalDatabase].[dbo].[Table_1] GROUP BY GATE, DLY1CAT UNION ALL Select Gate, DLY2CAT AS DLYCAT, SUM(DLY2MIN) AS DLYMIN FROM [Exper...
How to combine similar columns in SQL?
[ "", "sql", "oracle", "" ]
Suppose I have a table like the one below: ``` +----+-----------+ | ID | TIME | +----+-----------+ | 1 | 12-MAR-15 | | 2 | 23-APR-14 | | 2 | 01-DEC-14 | | 1 | 01-DEC-15 | | 3 | 05-NOV-15 | +----+-----------+ ``` What I want to do is for each year ( the year is defined as DATE), list the ID that has the high...
Starting with your sample query, the first change is simply to group by the ID as well as by the year. ``` SELECT EXTRACT(year from time) "YEAR" , id, COUNT(*) "TOTAL" FROM table GROUP BY EXTRACT(year from time), id ORDER BY EXTRACT(year from time) DESC, COUNT(*) DESC ``` With that, you could find the rows you want b...
You need to count per id and then apply a RANK on that count: ``` SELECT * FROM ( SELECT EXTRACT(year from time) "YEAR" , ID, COUNT(*) AS cnt , RANK() OVER (PARTITION BY "YEAR" ORDER BY COUNT(*) DESC) AS rnk FROM table GROUP BY EXTRACT(year from time), ID ) dt WHERE rnk = 1 ``` If this return multipl...
Querying for an ID that has the most number of reads
[ "", "sql", "oracle", "" ]
im working in sql server 2008, i want to concatenate two strings, and the condition is ``` @str1 = 'A1,B1,C1' @str2 = 'A2,B2,C2' ``` i want the result as ``` @result = 'A1,A2,B1,B2,C1,C2' ``` Please help...
The way you are storing your data is really bad practice. However here is a solution for training purposes: ``` DECLARE @str1 varchar(30) = 'A1,B1,C1', @str2 varchar(30) = 'A2,B2,C2', @result varchar(60) ;WITH split as ( SELECT t.c.value('.', 'VARCHAR(2000)') x FROM ( SELECT x = CAST('<t>' + ...
First create a split function to get you items seperately: ``` CREATE FUNCTION [dbo].[Split] ( @String NVARCHAR(4000), @Delimiter NCHAR(1) ) RETURNS TABLE AS RETURN ( WITH Split(stpos,endpos) AS( SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos UNION ALL SELECT endpos+...
SQL concatenate strings
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to find maximum of a price column in SQL but the prices have a $ sign in front of them, so when I do Max(column\_name) it does not show me the right answer. How do I get rid of the $ sign? Thanks.
assuming you are using sql-server and your data is in a varchar or nvarchar column: ``` DECLARE @Data varchar(max) = '$565' SELECT MAX(CAST(REPLACE(@data,'$','') AS INT)) ``` result: [![enter image description here](https://i.stack.imgur.com/eLCDI.png)](https://i.stack.imgur.com/eLCDI.png) So what you can do is: ...
Assuming that the amounts are all formatted the same (that is, with or without cents), then you can do: ``` select price from t order by len(price) desc, price desc fetch first 1 row only; ``` Note that some databases spell `len()` as `length()`. And some spell `fetch first 1 row only` as `limit` -- or perhaps use an...
Removing prefix in numbers in SQL
[ "", "sql", "" ]
Is there a way to use extract from date in format `YYYY-MM-DD` how many days were in this month? example: for `2016-02-05` it will give `29` (Feb 2016 has 29 days) for `2016-03-12` it will give `31` for `2015-02-05` it will give `28` (Feb 2015 had 28 days) I'm using PostgreSQL **EDIT:** [LAST\_DAY function in po...
One way to achieve this would be to subtract the beginning of the following month from the beginning of the current month: ``` db=> SELECT DATE_TRUNC('MONTH', '2016-02-05'::DATE + INTERVAL '1 MONTH') - DATE_TRUNC('MONTH', '2016-02-05'::DATE); ?column? ---------- 29 days (1 row) ```
Just needed this today and seems that I came up with pretty much the same as Mureinik, just that I needed it numeric. (PostgreSQL couldn't convert from interval to number directly) **previous month**: ``` select CAST(to_char(date_trunc('month', current_date) - (date_trunc('month', current_date) - interval '1 month'),...
How to get number of days in month based on date?
[ "", "sql", "postgresql", "" ]
I have a simple table `Customers` with `fields id, name, rating, seller_id`. The result of query ``` select seller_id, MAX(rating) from Customer group by seller_id ``` is the customers grouped by `seller_id` with max values of the rating. Like this: ``` seller_id rating 2 17 3 20 4 17 `...
Try: ``` select t.id, t.seller_id, t.rating from Customer c join ( select seller_id, MAX(rating) rating from Customer group by seller_id ) x on x.seller_id = c.seller_id and x.rating = c.rating ```
**A dataset is divided into groups using the GROUP BY clause. The grouping attribute is common key shared by members of each group. The grouping attribute is usually a single column but may be multiple columns or an expression that cannot be based on group functions. Note that only grouping attributes and group functio...
Query to get results with the grouping
[ "", "mysql", "sql", "" ]
I need some help to fetch records having alternate set of entries associated with Unique value(ex: user\_id) [![enter image description here](https://i.stack.imgur.com/bEruA.png)](https://i.stack.imgur.com/bEruA.png) > I want output to be only (1111,2222,3333) **Here is the scenario:** user\_id 1111 attended .net co...
You can use two `INNER JOIN` operations: ``` SELECT DISTINCT user_id FROM mytable AS t1 INNER JOIN mytable AS t2 ON t1.user_id = t2.user_id AND t1.id < t2.id AND t1.course_name <> t2.course_name INNER JOIN mytable AS t3 ON t2.user_id = t3.user_id AND t2.id < t3.id AND t1.course_name = t3.course_name ``` I assu...
Same as Girogos Betsos' answer, only with select distinct to prevent duplicates. ``` SELECT DISTINCT user_id FROM mytable AS t1 INNER JOIN mytable AS t2 ON t1.user_id = t2.user_id AND t1.Start_Date < t2.Start_Date AND t1.course_name <> t2.course_name INNER JOIN mytable AS t3 ON t2.user_id = t3.user_id AN...
How to fetch records that have an alternate entry
[ "", "sql", "oracle", "plsql", "oracle11g", "group-by", "" ]
I sometimes want to test certain BQ functions and sql statements in the BQ console **without** creating a test table in my dataset. For example, I can test regexp\_match in the console with this: ``` Select Regexp_extract(StringToParse,r'\b(à)\b') as Extract, Regexp_match(StringToParse,r'\b(à)\b') as match, FROM (SEL...
Note: I am answering/focusing on the question - `I sometimes want to test certain BQ functions and sql statements in the BQ console without creating a test table in my dataset` I see few cases (it might be more but at least three below can make good start for you) > Case #1 – Super Simple - no record type fields invo...
Based on your example data, the output schema you want is: ``` [ { "name":"rowNumber", "type":"integer" }, { "name": "index", "type": "integer", "mode": "repeated" }, ] ``` Here's something that will work for your example, finding the `MAX` of each index. The "SELECT NULL" in the innermost...
Can an entire table (as a string) be included in a sql statement for bigquery?
[ "", "sql", "google-bigquery", "" ]
I have this two tables ``` TABLE_A TABLE_B id_user|name id_user | points | date ------------- ------------------------ 1 | A 1 | 10 | yesterday 2 | B 2 | 10 | today 3 | C 2 | 20 | today ...
You can do it using a `LEFT JOIN`: ``` SELECT t1.id_user, t1.name, COALESCE(SUM(t2.points), 0) AS points FROM TABLE_A AS t1 LEFT JOIN TABLE_B AS t2 ON t1.id_user = t2.id_user AND t2.date = 'today' GROUP BY t1.id_user, t1.name ``` The crucial part of the `LEFT JOIN` is the fact that it's `ON` clause also contains the...
You need to use left join: ``` SELECT a.id_user AS name, SUM(COALESCE(b.points, 0)) AS `sum(points)_today` FROM TABLE_A a LEFT JOIN TABLE_B b ON a.id_user = b.id_user AND b.date = 'today' GROUP BY a.id_user ```
MySQL statment, how to show when a column has not results
[ "", "mysql", "sql", "database", "" ]
I have two tables in my database. I want to compare the each row of `email` of `table-1` with the each row of `email2` of `table-2` if their content matches then I want to store the `mac` of `table-1` to `Mac` of `Result table`. This is table-1 ``` Email Mac value1 21321 value2 45666 ``` This is table-2 ``` Nam...
you can use a insert select with inner join ``` insert into result_table (mac) select table1.mac from table1 inner join table2 on table1.email = table2.email ```
This is Simple. First you Join your table using the common column, in your case the `email` column. Once they are joined, you collect the data required, in your case the `mac` column on table 1. One this is done you `insert` it to your table 3. This is my approach: ``` INSERT INTO tbl3(mac) SELECT t1.mac FROM tbl1 A...
Compare two tables and store result in third table
[ "", "mysql", "sql", "" ]
I have 3 queries, but I want to combine them into one (with three columns). [this are my results](https://i.stack.imgur.com/yt4lM.jpg) this is my code: ``` Select family = count(s.destiny) from rental inner join cars as s on s.number_car = ID_car where s.destiny in (select destiny from cars where destiny like 'kids'...
Conditional aggregation seems like this right approach: ``` Select sum(case when density = 'kids' then 1 else 0 end) as family, sum(case when density = 'lux' then 1 else 0 end) as luxury, sum(case when density = 'sport car' then 1 else 0 end) as sports from rental r inner join cars s on ...
The simple answer is: ``` SELECT ( Select family = count(s.destiny) from rental inner join cars as s on s.number_car = ID_car where s.destiny in (select destiny from cars where destiny like 'kids') ) as kids, ( Select lux = count(s.destiny) from rental inner join cars as s on s.number_car = ID_car where s.destiny i...
combining columns with different queries sql
[ "", "sql", "sql-server", "t-sql", "" ]
The following code returns a list of duplicate rows of a specific column. In this case I am trying to find duplicates of university name. And my problem is how could I delete the duplicates and leave just one copy for each different university\_name? ``` Select * from `university` where `university_name` in ( sele...
1) If you want to keep the row with the lowest id value: ``` DELETE a FROM university a, university b WHERE a.id > b.id AND b.university_name=a.university_name ``` 2) If you want to keep the row with the highest id value: ``` DELETE a FROM university a, university b WHERE a.id < b.id AND b.university_name=a.univer...
Try this: ``` DELETE u FROM university u LEFT JOIN ( SELECT MIN(ID) ID, university_name FROM university GROUP BY university_name ) v ON u.ID = v.ID AND u.university_name = v.university_name WHERE v.ID IS NULL ```
SQL How to delete duplicate rows of a specific column and keep one
[ "", "mysql", "sql", "phpmyadmin", "duplicates", "" ]
I have a table with a date field of lastDelivery, and I want to retrieve all records that are 6 months or more older than today's date, how do I do this?
Try this: ``` SELECT * FROM Table WHERE lastdelivery <= dateadd(month, -6, getdate()) ```
Use [`DATEADD`](https://msdn.microsoft.com/en-us/library/ms186819.aspx) **Query** ``` select * from your_table_name where lastDelivery <= dateadd(month, -6, getdate()); ```
How do I get all records where date is 6 months greater than today's date, using Microsoft SQL Server 2008?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
[![enter image description here](https://i.stack.imgur.com/uEEOf.jpg)](https://i.stack.imgur.com/uEEOf.jpg) I have a poll system. I use this query to get count of every answer of question. How can I get percentage of every answered option like this: ``` question 1 ---> option1=20.13 % ---> option2=79.87 % question 2...
I agree with the advice of doing calculations (like percentages) on the front end. Having said that, this might be helpful for you. Design limitations: this is suitable for relatively small data sets, and I find the "with()" syntax easier to work with than making temp tables and hoping I remember to clean them up. ...
The schema for the above case ``` CREATE TABLE #POLL_QUESTION (QUESTION_ID INT, QUESTION VARCHAR(50)) INSERT INTO #POLL_QUESTION SELECT 1,'WHAT?' UNION ALL SELECT 2,'WHEN?' UNION ALL SELECT 3,'WHY?' UNION ALL SELECT 4,'WHERE?' CREATE TABLE #POLL_OPTION(OPTION_ID INT , QUESTIO...
How can I get percentage of each answer in sql?
[ "", "sql", "sql-server", "t-sql", "" ]
I have client numbers that are three characters. '001' to '999'. Sometimes there will be gaps that can be reused. I am trying to fill this gaps. So I am searching for a way to find first available gap. ``` CREATE TABLE co ( co_clno varchar(3)); INSERT INTO co VALUES ('001'), ('002'), ('003'), ('005'), ('006'), ('007...
``` select substring(to_char(n,'000') from 2) as num from generate_series(1,9) gs(n) except select co_clno from co order by 1 limit 1 ```
You can use `lead()` to find where the gap starts: ``` select n.* from (select n.*, lead(co_clno) over (order by co_clno) as next_num from co n ) n where next_num is null or n. co_clno::int <> (next_num::int) - 1 order by co_clno limit 1; ``` You can get the next value with: ``` select to_char((n. ...
next available value - postgresql
[ "", "sql", "postgresql", "" ]
I have a table with multiple records for each account, each record has a unit# with a balance. I want to select the account if one of the units has a negative balance and return all records for that account including the record with the negative unit. for example: Acct # 1234 has two records (each having a different un...
A simple `IN` will do it in standard SQL; ``` SELECT * FROM myTable WHERE account_id IN ( SELECT account_id FROM myTable WHERE balance < 0 ) ```
Try this way: ``` Select * from yourAccountTable a where EXISTS (select 1 from yourAccountTable b where a.accID = b.accId and b.unitBalance < 0 ) ``` What the clause `exists` do is to validate in a boolean way if a given registry ( `a.accID = b.accId` ) follow s...
SQL query that will retrieve multiple records when only one meets the criteria
[ "", "sql", "" ]
Let says i've data like below. ``` Col1 Col2 A E C C C D G C ``` and output will be like below ``` Column A C C D G ``` So i want only take value that has a value, if that both columns has a value, take only from column1 only.
``` select nvl(col1,col2) from table1 ``` NVL will check whether col1 is null if not it will take col1 value. If null it will take second col2 value
Also you could use `CASE` for common approach. ``` SELECT CASE WHEN col1 IS NULL THEN col2 ELSE col1 END FROM table1; ```
Select data from 2 Field and use only 1 values
[ "", "sql", "oracle", "" ]
The current data in my table is: > ``` > a b > --------- > -1 5 > -11 2 > -5 32 > ``` My request is to convert every data of column a into negative value. But how to update the positive values into the negative selecting the entire column?
Try this: ``` Update table set a= 0-a where a >0 ```
`UPDATE mytable SET a = a * -1;` This multiplies all values in 'a' by -1. Now, if the value is already negative, it will become positive. You you want to make sure they are *always* negative, do this: `UPDATE mytable SET a = a * -1 WHERE a > 0;`
Convert positive data into negetive data (entire column) in Postgres Server
[ "", "sql", "postgresql", "" ]
I have a model that has two columns (`started_at` and `ended_at`). I want to add a custom validator that ensures that no other record exists with dates that overlap with the record I'm validating. So far I have: ``` # app/models/event.rb class Event < ActiveRecord::Base validates_with EventValidator end # app/vali...
I don't use Arel but I think the query should be: ``` constraints = arel_table[:started_at].lteq(ended_at) .and(arel_table[:ended_at].gteq(started_at)) ``` Two periods overlap when ``` period1.start < period2.end period1.end > period2.start ```
Have a look at [Validates Overlap gem](https://github.com/robinbortlik/validates_overlap) You can either use it instead your code or take [condition code](https://github.com/robinbortlik/validates_overlap/blob/master/lib/validates_overlap/overlap_validator.rb#L119) from it ``` # Return the condition string depend o...
Check for Dates Overlap in Ruby on Rails
[ "", "sql", "ruby-on-rails", "ruby", "" ]
I am trying to create a simple PostgreSQL function, where by using `INT` parameter I like to get array back. The example below will not work, but shall give idea of what I try to get back from a function. Thanks. ``` CREATE OR REPLACE FUNCTION contact_countries_array(INT) RETURNS ANYARRAY AS ' SELECT ARRAY[contact...
Per the docs: > It is permitted to have polymorphic arguments with a fixed return > type, but the converse is not. As such, I think your attempt to return `anyarray` won't work. Your fields look like text, so I think if you altered it to something like this, it would work: ``` CREATE OR REPLACE FUNCTION contact_cou...
**Declaring Array, Looping, Adding items to Array, Returning Array with Postgres Function,** You can declare `INTEGER` array instead of `TEXT` and avoid casting `(counter::TEXT)` as well as return type `TEXT[]`. *(Added those for reference.)* ``` CREATE OR REPLACE FUNCTION "GetNumbers"(maxNo INTEGER) RETURNS TEXT[] A...
How to return array of values from PostgreSQL function by INT id
[ "", "sql", "arrays", "database", "postgresql", "function", "" ]
I got a SQL statement which uses some parameters to filter the output. Looking like this: ``` ALTER PROCEDURE [dbo].[spGetPerson] @Vorname varchar(50), @Nachname varchar(50), @FirmaID int, @AbteilungID int, @ArbeitsortID int, @FunktionID int AS BEGIN SET NOCOUNT ON...
The typical way to do this is to use logic like this: ``` Where (p.Vorname = @Vorname or @Vorname is null) AND (p.Nachname = @Nachname or @Nachname is null) AND (fi.FirmaID = @FirmaID or @FirmaID is null) AND (ab.AbteilungID = @AbteilungID or @AbteilungID is null) AND (ar.ArbeitsortID = @Arbeit...
Another way that I have found coming to my rescue in these cases is as below. How it works is simple. If the needed parameter is not null it will be used else the column is matched with itself causing engine to ignore that join as WHERE 1=1 type joins are skipped. Hope this helps ``` Where p.Vorname = COALESCE(@Vorna...
SQL Server stored procedure: disable "where" filter if related parameter is not set
[ "", "sql", "sql-server", "stored-procedures", "" ]
If I have a simple User table in my database and a simple Item table with a User.id as a foreign key thus: ``` (id UNIQUEIDENTIFIER DEFAULT (NEWID()) NOT NULL, name NVARCHAR (MAX) NULL, email NVARCHAR (128) NULL, authenticationId NVARCHAR (128) NULL, createdAt DATETIME DEFAULT GETDATE() NOT NULL, PRIMARY KEY (id)) CR...
I prefer to **not** have automatic cascade operations, being it DELETE or UPDATE. Just for the sake of peace of mind. Imagine you've configured your cascade deletes and then your program due to some bug tries to delete the wrong user, even though the database has some data related to it. All related data in related tab...
Another thing to try is setting isolation level to SERIALIZABLE in your trigger when you delete a user/item/collection. Since you are possibly deleting many items/collections/collected items when deleting a user, having another transaction INSERT something during this run can cause problems. SERIALIZABLE solves that to...
Cascading diamond shaped deletes in SQL
[ "", "sql", "sql-server", "dml", "" ]
I've got the following tables in a database. We have Product which have multiple Products for a Series, and we have ProductVariation which has multiple product variations per product. We are wishing to perform a set of aggregate queries on the ProductVariation table for a set of products based on the ID of the series....
Ok, so my issue was that the above were all right, but it turns out I was looking for group by SeriesID, to return MIN and MAX of set fields per SeriesID. Many thanks for all the SQL statements, you guys have helped clear up a problem I've had many times before! :) In sql:- @Oliver's post was what made it trigger as ...
So essentially, you just want the one Maximum for the whole series? I think there are a bit too many MAX's around in the other solutions. Just use a join: ``` SELECT MAX(PV.X), MAX(PV.Y) FROM [Product] AS P JOIN [ProductVariation] AS PV ON P.ProductID = PV.ProductID WHERE P.SeriesID = 12 AND P.IsDeleted = 0 and P.IsEn...
T-SQL Select MAX from subquery
[ "", "sql", "sql-server", "database", "t-sql", "aggregate-functions", "" ]
I'm having some issues where I can't seem the like regex to match 3 or more a's or e's in the name. Find all managers that manage employees with at least 3 letters 'a' or 'e' in their name (both uppercase and lowercase). For instance having 2 'a' and 1 'e' in the name, will satisfy the selection criteria ``` select m...
You're looking for this instead ``` (.*[ae]){3,} ``` The `.*` accepts differents chars between those wanted So your query becomes: ``` select manager_name from manages where regexp_like(employee_name, '(.*[ae]){3,}', 'i'); ``` The `i` flag is for insensitive match, so capital `AE` are taken into account to....
If you want at least 3 `a`'s or `e`'s anywhere in the name then: ``` select manager_name from manages where regexp_like(employee_name, '(.*?[ae]){3,}', 'i' ); ``` If you want at least 3 consecutive `a`'s or `e`s then: ``` select manager_name from manages where regexp_like(employee_name, '.*[ae]{3,}', 'i' ); ``...
SQL using regular expression REGEXP_LIKE()
[ "", "sql", "oracle", "regexp-like", "" ]
I have a database containing two tables `Team` and `User`. Every team can have one or two users in it. I wish to select an output of the table `Team` such that information of the both the users from the table `User` are included. It'll be easier to understand once I define the table structures. Table `Team`: ``` +---...
A couple of `left join`s should do the trick: ``` SELECT team_name, user_one, u1.user_name, user_two, u2.user_name, team_note FROM team t LEFT JOIN user u1 ON t.user_one = u1.email LEFT JOIN user u2 ON t.user_one = u2.email ```
The answer is actually quite simple, as the comment says simply use a `LEFT join`, this could by saying `LEFT JOIN [TableName]` ``` SELECT * FROM [Team] LEFT JOIN [User] ``` Also take a look at <http://www.w3schools.com/sql/sql_join_left.asp> Edit: Your second option would be to do this: ``` SELECT * FROM [Team]...
Using Join, select values from multiple SQL tables without a foreign key
[ "", "sql", "postgresql", "select", "join", "" ]
I am using SQL Server 2012 on Windows7. I currently have 2 tables. The first table: ``` DeviceID DeviceSwVersion DeviceIPAddr 1 802 172.26.20.1 115 800 172.26.18.1 1234 264 172.26.18.3 4717 264 172.26.19.2 // <- new ...
You could write a **AFTER INSERT TRIGGER** something like bellow: ``` CREATE TRIGGER trigger_insert_table_1 ON table_1 AFTER INSERT AS BEGIN INSERT INTO table_2 ( DeviceIPAddr, Status, TimeStamp) VALUES ( NEW.DeviceIPAddr, 0, getdate() ); END; ```
Merge is another way.. ``` MERGE <[The second table]> t USING [The first table: ] s ON t.DeviceIPAddr = s.DeviceIPAddr WHEN NOT MATCHED INSERT (DeviceIPAddr, Status, Timestamp) VALUES (s.DeviceIPAddr,0, getutcdate()) ; ```
How to insert into a table new records based on info from another table?
[ "", "sql", "sql-server", "insert", "record", "" ]
I am reading an SQL query in Redshift and can't understand the last part: ``` ... LEFT JOIN (SELECT MIN(modified) AS first_modified FROM user) ue ON 1=1 ``` What does `ON 1=1` mean here?
It's simply doing a cross join, which selects all rows from the first table and all rows from the second table and shows as cartesian product, i.e. with all possibilities. JOIN (LEFT, INNER, RIGHT, etc.) statements normally require an 'ON ..." condition. Putting in 1=1 is like saying "1=1 is always true, do don't elim...
The intention is an *unconditional* `LEFT JOIN`, which is ***different*** from a `CROSS JOIN` in that all rows from the left table expression are returned, even if there is no match in the right table expression - while a `CROSS JOIN` drops such rows from the result. [More on joins in the manual.](https://www.postgresq...
JOIN (SELECT ... ) ue ON 1=1?
[ "", "sql", "postgresql", "join", "left-join", "amazon-redshift", "" ]
Assume a many-to-many relation between team and player. This is modelled by the following tables: ``` create table team ( identifier integer primary key ); create table player ( identifier integer primary key ); create table member ( team_identifier integer, player_identifier integer, primary ke...
ideal solution to settle your problem create after-delete trigger or update in membre: ``` CREATE FUNCTION delete_player_not_in_member() RETURNS trigger AS $delete_player_not_in_member$ BEGIN DELETE FROM player WHERE Identifier NOT IN (SELECT player_identifier FROM membre); RETURN OLD; END; $delete_player_not_...
Well not necessarily. The player could still be considered a player who needs a team if you plan on adding him to a team at a later time. Or, if you want a pull of available players. However, you could try using ``` DELETE FROM member WHERE team_identifier = 1 DELETE FROM member WHERE team_identifier = 2 DELETE FROM...
Many-to-many relation - automatically delete orphans
[ "", "sql", "postgresql", "many-to-many", "" ]
I have the following table: ``` +----+--------+-----+ | id | fk_did | pos | +----+--------+-----+ ``` This table contains hundreds of rows, each of them referencing another table with `fk_did`. The value in `pos` is currently always zero which I want to change. Basically, for each group of `fk_did`, the `pos`-column...
You can do this using a window function: ``` update the_table set pos = t.rn - 1 from ( select id, row_number() over (partition by fk_id) as rn from the_table ) t where t.id = the_table.id; ``` The ordering of `pos` will be more or less random, as there is no `order by`, but you said that doesn't ...
If `id` is the PK of your table, then you can use the following query to update your table: ``` UPDATE mytable SET pos = t.rn FROM ( SELECT id, fk_did, pos, ROW_NUMBER() OVER (PARTITION BY fk_did ORDER BY id) - 1 AS rn FROM mytable) AS t WHERE mytable.id = t.id ``` `ROW_NUMBER` window function, used with...
SQL query to create ascending values within groups
[ "", "sql", "postgresql", "sql-update", "" ]
I have a `Shipments` table which basicly contains Shipments data with dates id is `integer` dateshipped is `date` ``` id dateshipped 1 1-JAN-16 2 1-JAN-16 3 3-FEB-16 4 9-FEB-16 ``` I want to write a query which count all shipments based on Months. What I should get is: ``` Jan Feb March.... 2 ...
You need a pivot query to accomplish this: ``` SELECT SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 1 THEN 1 ELSE 0 END) AS Jan, SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 2 THEN 1 ELSE 0 END) AS Feb, SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 3 THEN 1 ELSE 0 END) AS Mar, ...
Since 9.4 you can use [FILTER](http://www.postgresql.org/docs/current/static/sql-expressions.html) ``` SELECT count(*) AS total, count(*) FILTER (WHERE Extract(MONTH FROM dateshipped)::int=1) AS JAN, count(*) FILTER (WHERE Extract(MONTH FROM dateshipped)::int=2) AS FEB, ... FROM Shipments WHERE Extract...
Is it possible to Count by diffrent condition in one query?
[ "", "sql", "postgresql", "" ]
I am trying to run this query in Oracle ``` SELECT A1.ID_USER,A1.CNAME, (SELECT CNAME FROM (SELECT CNAME,COUNTER FROM (SELECT id_Category AS IDCATEGORT,COUNT(*) AS COUNTER FROM gamescateg WHERE id_game IN (SELECT ID_GAME FROM UserGames WHERE id_user=UsersGamers....
I've expanded your query to make it more readable and commented the problem (invalid identifier). There's a reference to alias A2 where A2 can't be. ``` select A1.ID_USER, A1.CNAME, ( SELECT CNAME FROM ( SELECT CNAME, COUNTER FROM ( SELECT id_Category AS IDCATEGORT, ...
Essentially a superficial fix will not fix the query. So, please explain what you are trying to do. I suspect the query is much more complicated than it needs to be. And, it is very hard to decipher. Your problem is, superficially, that you are using the table name rather than the alias. So, one would think that writi...
Sql Subquery Not working "ORA-00904: "A2"."ID_USER": invalid identifier"
[ "", "sql", "oracle", "subquery", "" ]
I have many duplicate products that I need to delete. Is there a query to delete these "Duplicates" with the "lower price" and/or "Same Price" an just keep 1 of each product? The duplicates have duplicate "Product Name" I am using Opencart Version 2.1.0.1
According to the schema on <http://wiki.opencarthelp.com/doku.php?id=databse_schema> and only one language the folowing query should solve your issue: ``` delete p1 from product p1 join product_description d1 on d1.product_id = p1.product_id join product_description d2 on d2.product_id <> d1.product_id and d2.l...
Since you are using mysql, you need to use joins (partition by is not supported): The select: ``` select p.* from products as p join ( select name, min(price) as price from products group by name having count(price) = 2 ) as p2 on p2.name = p.name and p2.price = p.price; ``` Gets the lowest price for all...
Remove duplicate product with lower price using mysql query
[ "", "mysql", "sql", "opencart2.x", "" ]