Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a table like following: ``` id value date 1 5 2015-01-10 2 5 2015-06-13 3 5 2015-09-05 4 11 2015-02-11 5 11 2015-01-10 6 11 2015-01-25 ``` As can be seen, every `value` appears 3 times with different `date`. I want to write a query that returns the unique `value`s that has ...
You can use `row_number` to select the rows with the greatest date per value ``` select * from ( select t2.id2, t1.date, t2.data, row_number() over (partition by t2.data order by t1.date desc) rn from table1 t1 join table2 t2 on t1.id = t2.id2 ) t where rn = 1 ```
``` select a.id, a.value, a.date from mytable a, ( select id, max(date) maxdate from mytable b group by id) b where a.id = b.id and a.date = b.maxdate; ```
How do I need to change my sql to get what I want in this case?
[ "", "sql", "database", "oracle", "group-by", "" ]
I have table name xyz, in that I have 2 records as below. ``` Record Prod_available FromTime ToTime 1 Pizza 08:00 21:59 2 Beer 22:00 07:59 ``` Now I want to select record based on current hour. Kindly Help me in above case.
This should work. Retweeted @Gordon Linoff code. ``` where ( ((FromTime < ToTime) and @time between FromTime and ToTime) or ((FromTime > ToTime) and @time not between ToTime and FromTime) -- here swapped the totime and fromtime. ) ```
You can try something along these lines: ``` select * from xyz where dateadd (hour, datepart(hour, getdate()), '2000-01-01') between dateadd (hour, left(fromtime,2), '2000-01-01') and dateadd (hour, case when left(totime,2) < left(fromtime,2) then left(totime,2)+24 else left(totime,2) end, '2000-01-01') ```
Select record based on Current hour between hours stored in Sql server 2008 table
[ "", "sql", "" ]
I want to have some information available for any stored procedure, such as current user. Following the temporary table method indicated [here](https://stackoverflow.com/a/25582641/2780791), I have tried the following: 1) create temporary table when connection is opened ``` private void setConnectionContextIn...
MINOR ISSUE: I am going to assume for the moment that the code posted in the Question isn't the full piece of code that is running. Not only are there variables used that we don't see getting declared (e.g. `AllowInsertConnectionContextInfo`), but there is a glaring omission in the `setConnectionContextInfo` method: th...
As was shown in this [answer](https://dba.stackexchange.com/a/124053/57105), `ExecuteNonQuery` uses `sp_executesql` when `CommandType` is `CommandType.Text` and command has parameters. The C# code in this question doesn't set the `CommandType` explicitly and it is [`Text` by default](https://msdn.microsoft.com/en-us/l...
SQL Server connection context using temporary table cannot be used in stored procedures called with SqlDataAdapter.Fill
[ "", "sql", "sql-server", "stored-procedures", "ado.net", "temp-tables", "" ]
Let's say I have the following table: ``` First_Name Last_Name Age John Smith 50 Jane Smith 40 Bill Smith 12 Freda Jones 30 Fred Jones 35 David Williams 50 Sally Williams 20 Peter Williams 35 ``` H...
Simple answer, do a correlated sub-select to get the "current" families highest age: ``` select * from tablename t1 where t1.Age = (select max(t2.Age) from tablename t2 where t2.Last_Name = t1.Last_Name) ``` However, Tim Biegeleisen's query is probably a bit faster.
``` SELECT t1.First_Name, t1.Last_Name, t1.Age FROM family t1 INNER JOIN ( SELECT Last_Name, MAX(Age) AS maxAge FROM family GROUP BY Last_Name ) t2 ON t1.Last_Name = t2.Last_Name AND t1.Age = t2.maxAge ``` Note: This will give multiple records per family in the event of a tie.
How do I select the record with the largets X for each of a group of records
[ "", "sql", "ms-access", "" ]
I have tabA: ``` ________________________ |ID |EMPLOYEE|CODE | |49 |name1 |mobile | |393 |name2 |none | |3002|name3 |intranet| ________________________ ``` The ID column (tabA) is based on a counter in the below tabB: ``` _________________ |TYPE |ID | |intranet |3003| |mobile |50 | |no...
**I would suggest the following answer:** **the @tabA and @tabB I assume is your tabA and tabB above.** ``` declare @tabA table ( id integer, employee nvarchar(10), code nvarchar(10) ) insert into @tabA values (49, 'name1','mobile'); insert into @tabA values (393, 'name2','none'); insert into @tabA value...
This will solve your problem: (Assuming your ID is incremental) ``` INSERT INTO tabA (ID, EMPLOYEE, CODE) VALUES ((SELECT TOP 1 ID + 1 FROM tabA ORDER BY ID DESC),'name4', 'intranet') ```
SQL - Insert Into table based on a counter value
[ "", "sql", "sql-server", "sql-server-2008", "sql-update", "sql-insert", "" ]
In my SQL server query I want to always get 0 results. I only want to get the metadata. How to write an always false evaluation in TSql? Is there a built-in function, or a recommended way of doing so? Currently I use `WHERE 1 = 0`, but I'm looking for something like `WHERE 'false'`.
Although you can use `where 1 = 0` for this purpose, I think `top 0` is more common: ``` select top 0 . . . . . . ``` This also prevents an "accident" in the `where` clause. If you change this: ``` where condition x or condition y ``` to: ``` where 1 = 0 and condition x or condition y ``` The parentheses are wro...
Have a look at SET FMTONLY ON. If you set that and run your query only the metadata is returned ``` USE AdventureWorks2012; GO SET FMTONLY ON; GO SELECT * FROM HumanResources.Employee; GO SET FMTONLY OFF; GO ```
Readable "always false" evaluation in TSQL
[ "", "sql", "sql-server", "boolean", "" ]
``` select distinct TagName as new, *,(REPLACE(TagName,' ','-')) as SeoProduct_Name from dbo.tbl_Image_Master inner join dbo.tbl_size on tbl_size.Size_Id=tbl_Image_Master.Size_Id inner join tbl_category on tbl_category.Cat_Id = tbl_Image_Master.Cat_Id ``` I wan...
``` SELECT * FROM TBL WHERE TAGNAME IN ( SELECT DISTINCT TAGNAME FROM TBL) ``` OR ``` SELECT * FROM ( SELECT *,ROW_NUMBER() OVER (PARTITION BY TAGNAME ORDER BY (SELECT 1)) AS ROWNUM FROM TBL WHERE TAGNAME) WHERE ROWNUM =1 ``` Hope it solves the Purpose !!!
If you want to get all columns from a table in a query you can use this syntax : ``` TableName.* ``` Example : ``` Select Table1.Col1, Table1.* from Table1; ``` I would post what your query becomes, but I am not sure what table you want all columns from.
getting distinct value with all column sqlserver
[ "", "sql", "" ]
I've created a view to show the author who writes all the books within the database with the word 'python' in the title. The issue I'm having is making it return nothing if there's more than one author. This is the working code for the view, I know I need to either implement a subquery using aggregate functions (count)...
So only return a row if there's no other author? I think this matches your description: ``` SELECT min(a.first_name), min(a.last_name) FROM authors AS a JOIN books AS b ON a.author_id = b.author_id WHERE b.title LIKE '%Python%' HAVING COUNT (DISTINCT b.author_id) = 1; ```
``` CREATE VIEW sole_python_author(author_first_name, author_last_name) AS SELECT first_name, last_name FROM authors, books WHERE authors.author_id = books.author_id AND title LIKE '%Python%' GROUP BY first_name, last_name HAVING COUNT(*) = 1 ```
SQL - Select query to return only a unique answer or nothing
[ "", "sql", "postgresql", "subquery", "" ]
Please help me. I wrote the query ``` with cte as ( select *, row_number() over ( partition by product order by date desc ) as rownumber from saleslist where datediff( month, date, getdate() ) < 2 ) select product, ((max(case when rownumber ...
``` with cte as ( select *, row_number() over ( partition by product order by date desc ) as rownumber from saleslist where datediff( month, [date], getdate() ) < 2 ) select product, ( (max(case when rownumber = 1 then price end) - max(case when rownumber = maxn then price ...
SQL server 2014 supports FIRST/LAST\_VALUE ``` with cte as ( select *, product, price as first_price, row_number() over (partition by product order by date) as rownumber, last_value(price) -- price of the row with the latest date over (partition by p...
SQL Server : error MSG 102 and MSG 156
[ "", "sql", "sql-server", "" ]
The following code generates alter password statements to change all standard passwords in an Oracle Database. In version 12.1.0.2.0 it’s not possible anymore to change it to in invalid Password values. That’s why I had to build this switch case construct. Toad gives a warning (rule 5807) on the join construct at the e...
On my machine (a laptop with the free XE version of Oracle - simplest arrangement possible) the table PRODUCT\_COMPONENT\_VERSION has FOUR rows, not one. There are versions for different products, including the Oracle Database and PL/SQL. On my machine the version is the same in all four rows, but I don't see why that ...
Toad is simply giving you a warning about the fact that you are doing a join with no `JOIN` conditions. In this case, you are really doing that, but one of the involved entities (the query from `PRODUCT_COMPONENT_VERSION`) should return only one value, so the problem is a false one. You are doing a cartesian with an en...
Avoid cartesian queries - find a proper "where clause"
[ "", "sql", "oracle", "cartesian", "" ]
In our business we have a main base account and then subordinate accounts under the baseaccount. 1.) How do I get all the accounts into a single column including the base account (comma delimited)? I've used this code before on other datasets and it works great. I just can't figure out how to make this work with all...
Here's what I did to resolve this issue with my query to create a comma delimited list on a single string or in a single column. I had to write the code in a CTE with a substring using the XML Path. It works for what I need and I'll use the code within an SSRS report. ``` ;with t1 as ( SELECT b.relatedfirmaccountid, ...
You can right click the box in the top left (to the left of baseacctnbr and above 1) and Save Results As a csv file, and open it with Notepad to view it that way. Personally I use python a lot for this type of thing. With pyodbc (<https://code.google.com/archive/p/pyodbc/wikis/GettingStarted.wiki>) you can execute you...
SQL comma delimited list as a single string
[ "", "sql", "sql-server", "t-sql", "" ]
I am new to VBA in Access database, the following code tries to combine two columns in Table\_2, but one of the column name needs to be defined by a field value from Table\_1, I tried to run the code, but it returns "Error updating: Too few parameters. Expected 1." I am not sure where is the problem. Appreciate if som...
As advised by @adam-silenko, I used DLookup function and then "Too few parameters error" is fixed. Here is the codes I used. Tough it fixed the error, but it produces another issue, which I raised on another question [here](https://stackoverflow.com/questions/36581104/access-vba-concatenate-dynamic-columns-and-execute-...
try use [DLookup Function](https://support.office.com/en-us/article/DLookup-Function-8896cb03-e31f-45d1-86db-bed10dca5937) and concatenate result with your Update string to get expected command. edit: you can also open recordset, build your update dynamically and execute it in loop. For example: ``` Set rst = db.Op...
Acess VBA - Update Variable Column (Too few parameters error)
[ "", "sql", "ms-access", "vba", "" ]
im trying to insert an id depending on another table, but i dont know how to do so, i have to do it this way since i am inserting multiples values at the time. this is my failed attempt at doing so ``` INSERT INTO producto (NumeroEconomico, Order_Id,Marca,Modelo,ano,placas,Product_Id,Inventario_Id) values ('ad-101'...
You need to wrap your subqueries in parentheses. ``` INSERT INTO producto VALUES ('ad-101', '27', 'Nissan','NP300','2016','aer3457','1',(SELECT Id from Inventario WHERE Serie = '5161017293')), ('ad-102', '27', 'Nissan','NP300','2015','aer5647','1',(SELECT Id from Inventario WHERE Serie = '5161019329')) ```
Have you tried an INSERT INTO SELECT? ``` INSERT INTO producto (NumeroEconomico, Order_Id,Marca,Modelo,ano,placas,Product_Id,Inventario_Id) SELECT 'ad-101', '27', 'Nissan','NP300','2016','aer3457','1',Id FROM Inventario WHERE Serie = '5161017293' ```
inserting from select and static elements
[ "", "sql", "sql-server", "sql-insert", "" ]
I have `COLUMN1 CHAR(1)` in `MYTABLE` where all rows are `NULL` and here is my sql query: ``` SELECT COLUMN1 FROM MYTABLE WHERE COLUMN1 != 'A' ``` it returns nothing because all rows have `NULL` in `COLUMN1`. I suppose it should return everything. How do I make it work? I don't wanna use ``` COALESCE(NULLIF(COLUMN1,...
If you really want NULLs, then why not ``` SELECT COLUMN1 FROM MYTABLE WHERE (COLUMN1 != 'A' OR COLUMN1 IS NULL) ``` ???
Think to the semantic of `NULL`. You can use it the way you want, but it is meant to mean "unknown". Unknown = 'A'? Nope. But unknown != 'A'? Nope. We simply don't know what it is, so almost all comparisons will fail. You can use `IS NULL` and `IS NOT NULL`, two special operators designed to work with `NULL`. So you c...
DB2 Select where not equal to string that is NULL
[ "", "sql", "db2", "" ]
I want to select all of the unique Users where `coach is true` and `available is true` but if there are ANY Sessions for that user where `call_ends_at is null` I don't want to include that user. `call_ends_at` can be NULL or have any number of various dates. ## Users id:integer name:string coach: boolean avail...
``` -- I want to select all of the unique Users where coach is true and available is true SELECT * FROM users u WHERE u.coach = true AND u.available = true -- but if there are ANY Sessions for that user where call_ends_at is null -- I don't want to include that user. AND NOT EXISTS ( SELECT * FROM ses...
I think you can do what you want using `EXISTS` and `NOT EXISTS`: ``` SELECT u.* FROM "users" u WHERE u."coach" = true AND u."available" = true AND EXISTS (SELECT 1 FROM "sessions" s WHERE s."coach_id" = u."id" ) NOT EXISTS (SELECT 1 FROM "session...
How do I exclude results if ANY associated row from a join table has NULL for a specific column?
[ "", "sql", "postgresql", "" ]
I have a problem with `ISNUMERIC` Function in SQL-server. I have a table, which contains one column with `nvarchar` type. In this column I have such a values `123`, `241`, ... and sometimes string values like `LK` My Query: ``` WITH CTE AS ( SELECT * FROM MyTable WHERE ISNUMERIC([Column1]) = 1 ) SELECT * ...
This is actually no bug. The CTE is a temporary view (or acts like a temporary view). So think on our query like querying a view. Most likely SQL will try first to go through all rows and get results from both scalars (isnumeric and the cast) then proceed to the filtering. That being said, it will fail way before it ...
``` IF OBJECT_ID('dbo.tbl', 'U') IS NOT NULL DROP TABLE dbo.tbl GO CREATE TABLE dbo.tbl (val NVARCHAR(1000)) INSERT INTO dbo.tbl VALUES ('123'), ('234'), ('LK'), ('8001') ALTER TABLE dbo.tbl ADD val2 AS CASE WHEN ISNUMERIC(val) = 1 THEN CAST(val AS INT) END GO SELECT * FROM dbo.tbl WHERE val2 > 8000 ```
bug in ISNUMERIC function?
[ "", "sql", "sql-server", "sql-server-2014", "" ]
How I can filter SQL results with `!=` in PostgreSQL SQL query? Example ``` SELECT * FROM "A" WHERE "B" != 'C' ``` Working. But it's also filtered all record where `"B" IS NULL`. When I changed query to: ``` SELECT * FROM "A" WHERE "B" != 'C' OR "B" IS NULL ``` I'm got right result. O\_o. Always, when I need using ...
You can use the "null safe" operator `is distinct from` instead of `<>` ``` SELECT * FROM "A" WHERE "B" is distinct from 'C' ``` <http://www.postgresql.org/docs/current/static/functions-comparison.html> --- You should also avoid quoted identifiers. They are much more trouble then they are worth it
you can use case when in where clause: its treat null values as an empty string. So it will return the null data also. ``` select * from table_A where ( case when "column_a" is null then '' else "column_a" end !='yes') ``` It's pretty faster as well.
Not equal and null in Postgres
[ "", "sql", "database", "postgresql", "null", "comparison-operators", "" ]
I use a sql request to get the number message by user by forum. ``` SELECT count(idpost), iduser, idforum FROM post group by iduser, idforum ``` And I get this result: [![enter image description here](https://i.stack.imgur.com/9AWR2.png)](https://i.stack.imgur.com/9AWR2.png) But I want to get the better poster in ...
According to the edited question: Please try the query below. What we need is a subquery finding max(idpost) based on idforum. Think the query below: ``` select max(idpost) as IDPOST,idforum from post group by idforum ``` What this query is supposed to do is to find the number of posts by a user on a forum. So it s...
Well assuming you supply the idForum of the forum in question.........just get the top row of your query ordered by the count desc ``` SELECT TOP 1 * FROM ( SELECT count(idpost),iduser,idforum FROM post GROUP BY iduser,idforum ) PostsCount WHERE PostsCount.idForum = @theForumIdIamLookingFor ORDER BY co...
Get max with one count
[ "", "sql", "" ]
This is a simple question and I can't seem to think of a solution. I have this defined in my stored procedure: ``` @communityDesc varchar(255) = NULL ``` @communityDesc is "aaa,bbb,ccc" and in my actual query I am trying to use `IN` ``` WHERE AREA IN (@communityDesc) ``` but this will not work because my commas a...
at first you most create a function to split string some thing like this code ``` CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) ) RETURNS @returnList TABLE ([Name] [nvarchar] (500)) AS BEGIN DECLARE @name NVARCHAR(255) DECLARE @pos INT WHILE CHARINDEX(',', @stringToSplit) > 0 BEGIN SELECT @pos...
This article could help you by your problem: <http://sqlperformance.com/2012/07/t-sql-queries/split-strings> In this article Aaron Bertrand is writing about your problem. It's really long and very detailed. One Way would be this: ``` CREATE FUNCTION dbo.SplitStrings_XML ( @List NVARCHAR(MAX), @Delimiter...
SQL Stored Procedure LIKE
[ "", "sql", "" ]
I have data currently in my table like below under currently section. I need the selected column data which is comma delimited to be converted into the format marked in green (Read and write of a category together) [![enter image description here](https://i.stack.imgur.com/l7BTX.png)](https://i.stack.imgur.com/l7BTX.pn...
Using Jeff's [DelimitedSplit8K](http://www.sqlservercentral.com/articles/Tally+Table/72993/) ``` ; with cte as ( select id, prodlines, ItemNumber, Item = ltrim(Item), grp = dense_rank() over (partition by id order by replace(replace(ltrim(Item), '(Read)', ''), '(Write)', '')) from #prodLines pl ...
Take a look at [STRING\_SPLIT](https://msdn.microsoft.com/en-us/library/mt684588.aspx), You can do something like: ``` SELECT user_access FROM Product CROSS APPLY STRING_SPLIT(user_access, ','); ``` or what ever you care about.
Split column data into multiple rows
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have a table with two columns, number of maximum number of places (capacity) and number of places available (availablePlaces) I want to calculate the availablePlaces as a percentage of the capacity. ``` availablePlaces capacity 1 20 5 18 4 15 ``` Desired Result...
Try this: ``` SELECT availablePlaces, capacity, ROUND(availablePlaces * 100.0 / capacity, 1) AS Percent FROM mytable ``` You have to multiply by 100.0 instead of 100, so as to avoid integer division. Also, you have to use [**`ROUND`**](http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#functio...
The following SQL query will do this for you: ``` SELECT availablePlaces, capacity, (availablePlaces/capacity) as Percent from table_name; ```
Calculate percentage between two columns in SQL Query as another column
[ "", "sql", "percentage", "" ]
I'm trying to get a `diff_date` from Presto from this data. ``` timespent | 2016-04-09T00:09:07.232Z | 1000 | general timespent | 2016-04-09T00:09:17.217Z | 10000 | general timespent | 2016-04-09T00:13:27.123Z | 250000 | general timespent | 2016-04-09T00:44:21.166Z | 1144020654000 | general ```...
I think you want [`lag()`](https://prestosql.io/docs/current/functions/window.html#lag): ``` select _t, date_diff('second', from_iso8601_timestamp(_ts), lag(from_iso8601_timestamp(f._ts)) over (partition by uid order by dt) ) from logs d where _t = 'timespent' and dt = '2016-04-...
``` select date_diff('Day',from_iso8601_date(substr(od.order_date,1,10)),CURRENT_DATE) AS "diff_Days" from order od; ```
How to get date_diff from previous rows in Presto?
[ "", "sql", "presto", "" ]
In `SQL Server` you can do sum(field1) to get the sum of all fields that match the groupby clause. But I need to have the fields subtracted, not summed. Is there something like subtract(field1) that I can use in stead of sum(field1) ? For example, table1 has this content : ``` name field1 A 1 A 2 B 4 ``` Q...
Assuming that you have some column to indicate order, to select first element per group, you could use windowed functions to calculate your `substract`: ``` CREATE TABLE tab(ID INT IDENTITY(1,1) PRIMARY KEY, name CHAR(1), field1 INT); INSERT INTO tab(name, field1) VALUES ('A', 1), ('A', 2), ('B', 4); SELECT DISTINCT ...
So you want to subtract the sum of the second to last from the first value? You need a column to indicate the order. If you don't have a logical column like a `datetime` column you could use the primary-key. Here's an example which uses common table expression(CTE's) and the `ROW_NUMBER`-function: ``` WITH CTE AS ( ...
What is the counterpart for SUM() in SQL Server?
[ "", "sql", "sql-server", "t-sql", "aggregate-functions", "" ]
I have a table which contains data like this: ``` MinFormat(int) MaxFormat(int) Precision(nvarchar) -2 3 1/2 ``` The values in precision can be 1/2, 1/4, 1/8, 1/16, 1/32, 1/64 only. Now I want result from query as - ``` -2 -3/2 -1 -1/2 0 1/2 1 3/2 2 5/2 3 ``...
Note this will only work for Precision 1/1, 1/2, 1/4, 1/8, 1/16, 1/32 and 1/64 ``` DECLARE @t table(MinFormat int, MaxFormat int, Precision varchar(4)) INSERT @t values(-2, 3, '1/2') DECLARE @numerator INT, @denominator DECIMAL(9,7) DECLARE @MinFormat INT, @MaxFormat INT -- put a where clause on this to get the need...
Sorry, now I'm late, but this was my approach: I'd wrap this in a TVF actually and call it like ``` SELECT * FROM dbo.FractalStepper(-2,1,'1/4'); ``` or join it with your actual table like ``` SELECT * FROM SomeTable CROSS APPLY dbo.MyFractalSteller(MinFormat,MaxFormat,[Precision]) AS Steps ``` But anyway, this wa...
SQL Server 2008 - Query to get result in fraction format
[ "", "sql", "sql-server", "" ]
I am stuck a little bit with my SQLite3 query. I have following table, where I want to select only rows which are invalid. Table contains servers in various countries and each server can contain number of application instances. Each application instance can be valid (e.g. success check or so..) or invalid (if control w...
I would use aggregation: ``` select Country, ServerID, Application from t group by Country, ServerID, Application having sum(case when validation = 0 then 1 else 0 end) > 0; ``` This counts the number of rows where `validation = 0` and the `> 0` ensures that there is at least one. Assuming validation is a number tha...
How about just doing this? ``` select distinct Country, ServerID, Application from table where Validation = 0 ```
SQL level nested SELECT
[ "", "sql", "sqlite", "" ]
I Have 3 tables like: **ProductCategory** [1 - m] **Product** [1-m] **ProductPrice** a simple script like this : ``` select pc.CategoryId ,pp.LanguageId , pp.ProductId ,pp.Price from ProductCategory as pc inner join Product as p on pc.ProductId = p.Id inner join ProductPrice as pp on p.Id = pp.ProductId orde...
You could use windowed function like [`RANK()`](https://msdn.microsoft.com/en-us/library/ms176102.aspx): ``` WITH cte AS ( select pc.CategoryId, pp.LanguageId, pp.ProductId, pp.Price, rnk = RANK() OVER(PARTITION BY pc.CategoryId ,pp.LanguageId ORDER BY pp.Price) from ProductCategory as pc join Product as p...
You are not using the `Product` table in your query, so it doesn't seem necessary. I would right this as: ``` select ppc.* from (select pc.CategoryId, pp.LanguageId , pp.ProductId, pp.Price, row_number() over (partition by pc.CategoryId order by pp.Price) as seqnum from ProductCategory pc inner join...
T-Sql select and group by MIN()
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "greatest-n-per-group", "" ]
So, I have some data that needs to be count with RIGHT JOIN. The query look like this: ``` SELECT COUNT(trans_id) FROM database2..transaction a RIGHT JOIN database1..sellers b ON a.products = b.products GROUP BY sellers ORDER BY sellers ``` The result ends up perfectly like this one: [![enter image description here]...
I find it much easier to follow `left join` rather than `right join`. But your problem is that the `where` conditions should go in the `on` clause -- otherwise they turn the outer join in to an inner join: ``` SELECT COUNT(trans_id) FROM database1..sellers s LEFT JOIN database2..transaction t ON s.products =...
Your `WHERE` clause is applied after your `JOIN`. If you want the 0 counts to still show up, you should add it to your `JOIN` instead. ``` SELECT COUNT(trans_id) FROM database2..transaction a RIGHT JOIN database1..sellers b ON a.products = b.products AND trans_status = 'success' GROUP BY sellers ...
SQL RIGHT JOIN Won't Count Null Data
[ "", "sql", "sql-server", "" ]
i think its easier to explain on an example. so here are my tables ``` Table A id | Name 1 | row1 2 | row2 3 | row3 Table B id | A_id | date 1 | 1 | NULL 2 | 1 | NULL 3 | 2 | 2016-04-01 4 | 2 | 2016-04-01 5 | 3 | 2016-04-01 6 | 3 | NULL ``` What im trying to accomplish is for my se...
You can use `EXISTS`: ``` SELECT * FROM TableA a WHERE EXISTS( SELECT 1 FROM TableB b WHERE b.A_id = a.id AND b.date IS NULL ) ```
``` SELECT * FROM TableA a WHERE ID IN (SELECT ID_A FROM TableB WHERE date IS NULL ) ``` Subquery retrives IDs on null dates, what is in turn passed to the main query to have what you want
SQL where clause dependant on other table
[ "", "sql", "sql-server", "" ]
i have a table called stock with columns Tran\_id,Trancode,item\_id barcode prodqty made in sql as below. each time an item is sold , a row is added with a trancode of sales and each time an item is produced there is a row added with a trancode of production.i need to get the remaining stock for a particuclar item barc...
Sum the quantities, positive if production, negative if sales: ``` select sum(case when trancode = 'sales' then -prodqty else prodqty end) from stock where barcode = ? ```
Try this ``` select (qty1.Produced - qty2.Sold) as difference from (select sum(prodqty) as Produced from yourtable where barcode='xxxx') qty1, (select sum(prodqty) as Sold from yourtable where bardcode='xxxx')qty2 ```
how to get the difference between to columns in sql
[ "", "sql", "" ]
I am trying to insert data into a table, however I would like to select the ID which is auto incremented when the row is made, and then I would like to set it into a field within another table. For example 1. INSERT INTO playerdata (Username) VALUES ('%e') 2. SELECT ID FROM playerdata p WHERE Username = '%e' LIMIT 1 ...
you can use a trigger after insert like this ``` create trigger update_masterdata after insert on playerdata for each row begin UPDATE masterdata SET Slot = NEW.id; end/ ``` [sqlfiddle](http://sqlfiddle.com/#!9/d6a77/1)
Seems you only insert 1 rows. You can try [LAST\_INSERT\_ID](http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id) function
Using INSERT, SELECT and UPDATE in one query?
[ "", "mysql", "sql", "" ]
I am trying to combine this SQL backup script/query that I have with my power shell script and I'm not sure how to convert it as I don't know much about SQL only Powershell. I have been trying to use `invoke-sqlcmd` before every line in the script, but I don't think that's how you do it. I don't fully understand the sy...
Sqlcmd is designed to be replacement for sqlcmd command-line tool. > Much of what you can do with sqlcmd can also be done using > Invoke-Sqlcmd. Therefore you will execute your commands in one go. Either using external file or multi-line SQL string. See below for examples. ## External File Example Save your sql bac...
I wouldn't use powershell for doing a backup. I would recommend using a SQL stored procedure to schedule a job. ``` USE msdb ; GO -- creates a schedule named NightlyJobs. -- Jobs that use this schedule execute every day when the time on the server is 01:00. EXEC sp_add_schedule @schedule_name = N'NightlyJobs...
Combining a SQL database backup script/query with powershell
[ "", "sql", "sql-server", "powershell", "" ]
I have 3 tables with below format. ``` Table A Table B Table C id id1 id2 id name 1 1 null 1.1 john 2 1 1.1 2 ...
We can have a solution by using another table which store if there is at least on non null value on `id2` for `id1` in `Tableb`, and if so deletes when there is the null values. This table would be : ``` select sum(case when id2 is null then 0 else 1 end) as test, id1 from TableB group by id1 ``` And the query : ``...
If I'm understanding correctly, here's one option using `rank`: ``` select * from ( select a.id,b.id1,b.id2,c.id,c.name, rank() over (partition by b.id1 order by case when b.id2 is null then 1 else 0 end) rnk from TableA a join TableB b on a.id = b.id1 left join...
display data from 3 tables with conditional joining
[ "", "sql", "oracle11g", "oracle-sqldeveloper", "plsqldeveloper", "" ]
I hope somebody can help me I am new in sql database. I have the following table: ``` -------------------------------------- id from to version --------------------------------------- 0 01.01.70 31.12.79 v1 1 01.01.80 31.12.89 v2 ``` Now I would like to reach the fo...
You will need to pass a variable into the query - depending on your programming language this is easily accomplished. Substitute . ``` select version from versions_table where to_date('<myInputDate>', 'dd.mm.yy') between to_date('from', 'mm.dd.yy') and to_date('to', 'mm.dd.yy'); ``` Make sure to substitute the date y...
`from` could be a bad idea for a column name. You could test this SQL Query: ``` SELECT version FROM versions_table WHERE user_date between versions_table.from AND versions_table.to; ``` With this you indicates that you mean columns from table `versions_table` and not the keyword `FROM`
select a date between two dates
[ "", "sql", "oracle", "" ]
I have this: ``` SELECT * FROM history JOIN value WHERE history.the_date >= value.the_date ``` is it possible to somehow to ask this question like, where history.the\_date is bigger then or equal to biggest possible value of value.the\_date? ``` HISTORY the_date amount 2014-02-27 200 2015-02-26 2000 VALUE t...
So `value.the_date` is the date since when the interest is valid. Interest 2 was valid from 2010-02-10 till 2014-12-31, because since 2015-01-01 the new interest 3 applies. To get the current interest for a date you'd use a subquery where you select all interest records with a valid-from date up to then and only keep ...
use join condition after `ON` not in where clause... ``` SELECT * FROM history JOIN (select max(value.the_date) as d from value) as x on history.the_date >= x.d WHERE 1=1 ```
Joining two tables by date MySQL
[ "", "mysql", "sql", "" ]
Can you tell me how I can generate an ER diagram for my database1 (see below) created with VS 2015 [![enter image description here](https://i.stack.imgur.com/6wx9J.png)](https://i.stack.imgur.com/6wx9J.png) Thanks in advance
DB Objects in the editor will be related as in Diagram so Just relate objects in the Db and drag to editor.
Ensure you installed either Microsoft SQL Server Data Tools or Microsoft Web Developer Tools in order to get the Entity Data Model Designer. These are the steps to generate entity relationship diagram. It was tested in `VS2012` 1. Open `Visual Studio` 2. Create a project or open an existing project (must be Visual...
Generating entity relationship diagram in Visual Studio 2015
[ "", "sql", "database", "visual-studio", "visual-studio-2015", "entity-relationship", "" ]
I have the following tables in my database: **tags** ``` id | name --------- 1 | tag1 2 | tag2 3 | tag3 4 | tag4 ``` **map\_posts\_tags** ``` post_id | tag_id ---------------- 123 | 1 123 | 2 234 | 1 345 | 3 345 | 4 456 | 2 456 | 1 ``` Is it possible to get all the posts with the sa...
``` SELECT * FROM tags t INNER JOIN map_posts_tags mpt ON t.id = mpt.tag_id WHERE tag_id in ( select tag_id from map_posts_tags where post_id = 123) AND NOT post_it = 123 ```
This will give you what you want. You can join it with `tags` table to get `tag name` too `SQLFiddle Demo` ``` select distinct post_id from map_posts_tags where tag_id in (select tag_id from map_posts_tags where post_id = 123) and post_id <> 123 ```
Complex SQL query with JOIN
[ "", "mysql", "sql", "database", "join", "" ]
I have a table that looks like this ``` userid | eventid | description | date | starttime | endtime 1 1 Event 1 2016-02-02 09:30:00 11:00:00 1 2 Event 2 2016-02-02 13:30:00 15:00:00 1 3 Event 3 2016-02-02 17:30:00 21:0...
Given this sample data: ``` CREATE TABLE t (`userid` int, `eventid` int, `description` varchar(7), `date` date, `starttime` time, `endtime` time) ; INSERT INTO t (`userid`, `eventid`, `description`, `date`, `starttime`, `endtime`) VALUES (1, 1, 'Event 1', '2016-02-02', '09:30:00', '11:00:00'), (1, 2, ...
Here's one way you can get the `timeBetween` value in `SECONDS` ``` SELECT firsttable.userid, SEC_TO_TIME(SUM(TIME_TO_SEC(secondtable.starttime) - TIME_TO_SEC(firsttable.endtime))) timeBetween FROM ( SELECT *, IF(@prev = userid, @rn1 := @rn1 + 1, @rn1 := 1) rank, @prev := userid ...
Finding in between time in a list of times
[ "", "mysql", "sql", "" ]
I have a MySQL table that is filled with mails from a postfix mail log. The table is updated very often, some times multiple times per second. Here's the `SHOW CREATE TABLE` output: ``` Create Table postfix_mails CREATE TABLE `postfix_mails` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `mail_id` varchar(20) COLL...
If you need your query to be really fast, you'll need to materialize it. MySQL lacks a way to do that natively, so you'll have to create a table like that: ``` CREATE TABLE mails_host_day ( host VARCHAR(30) NOT NULL, day DATE NOT NULL, mails BIGINT NOT NULL, PRIMARY KEY (host, ...
`queued_at` is a datetime value. Don't use `LIKE`. That converts it to a string, preventing the use of indexes and imposing a full-table scan. Instead, you want an appropriate index and to fix the query. The query is: ``` SELECT COUNT(*) as `count` FROM `postfix_mails` WHERE `queued_at` >= '2016-04-11' AND `queued_at...
Is there any way to optimize this SELECT query any further?
[ "", "mysql", "sql", "" ]
I am new to SSRS and I am facing an issue in SSRS 2008. I am hiding and showing a table depending upon the condition, but after hiding its shows empty space/row.
It seems the table is reserved and you can't get rid of it. What you can do is display some message like 'no data' etc when you want to hide it. You can display the message in a text box in the table, the text expression will be based on the condition.
Are you saying that when your table is invisible, you're still seeing white space that the table would've occupied if it were visible? Have you tried setting the following in the Report properties? ``` ConsumeContainerWhitespace = True ```
SSRS dynamic rows
[ "", "sql", "reporting-services", "asp-classic", "report", "" ]
I need to return all values for: select...where IN (1,2,3,3,3,1) I have a table with unique IDs. I have the following query: ``` Select * From Table_1 Where ID IN (1,2,3,3,3,1); ``` So far I'm returning only 3 records for unique values (1,2,3) I want to return 6 records. I need to get result set shown on the pictu...
You cannot do this using the `IN` condition, because `IN` treats your items as a set (i.e. ensures uniqueness). You can produce the desired result by joining to a `UNION ALL`, like this: ``` SELECT t.* FROM Table_1 t JOIN ( -- This is your "IN" list SELECT 1 AS ID UNION ALL SELECT 2 AS ID UNION ALL SELECT 3...
You can't do that with the `IN` operator. You can create a temporary table and JOIN: ``` CREATE TABLE #TempIDs ( ID int ) INSERT INTO #TempIDs (1) INSERT INTO #TempIDs (2) INSERT INTO #TempIDs (3) INSERT INTO #TempIDs (3) INSERT INTO #TempIDs (3) INSERT INTO #TempIDs (1) Select Table_1.* From Table_1 INNER JOIN #Tem...
Return all for where IN (1,2,3,3,3,1) clause with duplicates in the IN condition
[ "", "sql", "sql-server", "duplicates", "" ]
Below is my query: ``` SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED] ``` It gives me following result: [![query result](https://i.stack.imgur.com/eyiu1.jpg)](https://i.stack.imgur.com/eyiu1.jpg) The problem is if I am doing `order by MonthCycle` then since it is a string it is using month's first letter to...
``` SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED] ORDER BY CASE WHEN LEFT(MONTHCYCLE,3) = 'Jan' then 1 WHEN LEFT(MONTHCYCLE,3) = 'Feb' then 2 WHEN LEFT(MONTHCYCLE,3) = 'Mar' then 3 WHEN LEFT(MONTHCYCLE,3) = 'Apr' then 4 WHEN LEFT(MONTHCYCLE,3) = 'May' then 5 WHEN LEFT(MONTHCYCLE,3) = 'Jun' then 6 ...
The question doesn't specify if the report will be spanning several years, but if so I'd use something like this: ``` ORDER BY CONVERT(DATETIME, '1 ' + REPLACE(monthCycle, '''', ' ')) ```
sql server order by clause
[ "", "sql", "sql-server", "" ]
I want to access another SQL Server to import and update data of that server's database through a stored procedure. For that I created linked server using `sp_addlinkedserver`. ``` EXEC sp_addlinkedserver @server = N'LINKEDSERVER' ,@srvproduct=N'' ,@provider=N'SQLOLEDB' ,@datasrc=N'[DB-Instance.cuprx...
I found the answer. The problem was an instance, I had created "Amazon RDS for SQL Server" which is currently not supporting to "Linked servers". So I create a new AWS EC2 instance for Windows Server 2012 R2 and then I create Linked servers in it and tried to assess remotely. Now its working fine as I wanted. Here is...
This article explains in detail how to link one AWS Sql Server to another (<https://aws.amazon.com/blogs/apn/running-sql-server-linked-servers-on-aws/>). I am not certain what is wrong in your case, but this has a lot of steps that I do not see in your description. And the one thing that does jump out at me is that yo...
Access another SQL Server through stored procedure
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2012", "linked-server", "" ]
I have this structure of table Diary: ``` CREATE TABLE Diary ( [IdDiary] bigint, [IdDay] numeric(18,0) ); INSERT INTO Diary ([IdDiary], [IdDay]) values (51, 1), (52, 2), (53, 5); ``` And this other structure for table DiaryTimetable: ``` CREATE TABLE DiaryTimetable ( [IdDiary] bigint, [Hour...
You use a `GROUP BY` clause: ``` SELECT d.IdDiary, d.IdDay, MIN(Hour), MAX(Hour) FROM Diary AS d LEFT JOIN DiaryTimetable AS dt ON d.IdDiary = dt.IdDiary GROUP BY d.IdDiary, d.IdDay ``` [**Demo here**](http://sqlfiddle.com/#!6/5ca9c9/7)
You just missed `Group by` in your query. ``` SELECT b.IdDiary,a.IdDay, MIN(b.Hour), MAX(b.hour) from Diary A INNER JOIN DiaryTimetable B ON A.IdDiary=B.IdDiary GROUP by B.IdDiary ,a.IdDay ```
How to get the MAX(Hour) and The MIN(Hour) for each day in this query?
[ "", "sql", "sql-server", "max", "min", "hour", "" ]
How to replace characters other than specified without using Regular Expression in oracle sql? For Example: ``` select replace ('rhythm','^h') from dual; Expected result: hh ```
Seems like a non-problem since regular expressions exist, but you could do something like: ``` select listagg(c) within group (order by lvl) from ( select level as lvl, case when substr('rhythm', level, 1) in ('h', 'H') then substr('rhythm', level, 1) end as c from dual connect by level <= length('rhyt...
You can use [TRANSLATE](https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions196.htm) ``` SELECT TRANSLATE('rhythm', 'hHABCDEFGIJKLMNOPQRSTUVWXYZabcdefgijklmnopqrstuvwxyz', 'hH') FROM DUAL; ``` And this here is for @Aleksej ;) ``` WITH t1 AS (SELECT 'rhythm bythm dubidah' s, 'ht' c FROM DUAL), t2 ...
How to replace characters other than specified without using Regex in oracle sql?
[ "", "sql", "oracle", "" ]
I have into col1 value as below: [![enter image description here](https://i.stack.imgur.com/1Rw0p.png)](https://i.stack.imgur.com/1Rw0p.png) If I'm doing select: ``` select col1 from table1 ``` How to instead of NULL display **X**? It's possible then to join other table using values from col1? (A, B and X) like: ...
Try, ``` Select x.Col1 FROM Table1 x INNER JOIN Table2 y ON (x.Col1 = y.Col1 or x.Col1 is NULL and y.Col1 is NULL) ```
Use ISNULL(col1,'X'), this will return the value of col1 if it is not null , else it will return the default value 'X' ``` select ISNULL(col1,'X') from table1 ```
Display and join table using column with null values
[ "", "sql", "sql-server", "sql-server-2008", "join", "null", "" ]
I have this query: ``` SELECT * FROM Schedule_OverdueTasks WHERE Job_No LIKE ( SELECT DISTINCT AREA_ID FROM V_CONSTAT_PROJ_DATES WHERE AREA_DESC IN ('aaa', 'bbb') + '%' ``` but this gives me this error: `Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=...
I would recommend that you use `exists`: ``` SELECT ot.* FROM Schedule_OverdueTasks ot WHERE EXISTS (SELECT 1 FROM V_CONSTAT_PROJ_DATES pd WHERE ot.Job_No LIKE pd.area_id + '%' AND AREA_DESC IN ('aaa', 'bbb') ); ```
I can't comment so I need to use the answer section, but `like` takes a `scalar` `data type` not a `table valued data type Meaning you can only compare it to 1 value so without knowing your data structure the best I would be able to recommend at the moment is ``` SELECT * FROM Schedule_OverdueTasks INNER JOIN ( ...
SQL Subquery returned more than 1 value. This is not permitted when the subquery
[ "", "sql", "sql-server", "" ]
I have this problem, I've got database table that looks like this: ``` "63";"CLINICAL...";"Please...";Blah...;"2014-09-23 13:15:59";37;8 "64";"CLINICAL...";"Please...";Blah...;"2014-09-23 13:22:51";37;9 ``` The values that matter are the second to last and last one. As you can see, the second to last (abstract\_categ...
We can create a scope to select the `category` with max `version_number` like this: ``` scope :with_max_version_number, -> { joins("JOIN ( SELECT abstract_category_id, max(version_number) AS max_version FROM categories GROUP BY abstract_category_id ) AS temp ON...
Scopes are suppose to return an array of values even if there is only 1 record. If you want to ALWAYS return 1 value, use a static method instead. ``` def self.max_abstract_category <your_scope>.max_by{ |obj| obj.version_number } end ```
Rails: Need to scope by max version
[ "", "sql", "ruby-on-rails", "scope", "" ]
How can I make a check constraint that checks if last\_name has the last 2 letters capitalized? ``` alter table clienti modify (nume_client constraint che_d check(nume_client=upper(substr(nume_client, -2, 1)))); ``` I did like this, but I am getting the following error: > 1. 00000 - "cannot validate (%s.%s) - check ...
Your constraint is comparing the whole name to the upper-cased second-to-last character. It's only looking at one character, because you're supplying the [third argument](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions181.htm#SQLRF06114) `substring_length` as 1. You need to check the last two characters...
You might already have records there in table, that do not pass the check constraint. If it's OK to have the check only for future transactions you can use NOVALIDATE clause to constraint. E.g. ``` CREATE TABLE names (last_name VARCHAR2(100)); --Table created INSERT INTO names VALUES ('Rambo'); --1 row inserted INSERT...
Check constraint last_name capitalized
[ "", "sql", "oracle", "" ]
I'm trying to do something similar to this: ``` SELECT SUM( CASE WHEN (<some_condition> AND EXISTS(SELECT 1 FROM <tableA> as tA WHERE tA.Id = tB.tAId and <some_other_condition> ...
``` SELECT SUM( CASE WHEN (<some_condition> AND tA.Id IS NOT NULL ) THEN 1 ELSE 0 END ) as <column_name> FROM <tableB> as tB JOIN (SELECT DISTINCT ta.Id FROM <tableA>) as tA ON tA.Id = tB.Id AND <some_other_condition> ```
Since, as the message says, you cannot use a subquery in an aggregate function (`SUM()`), consider using a join similar to the following: ``` SELECT SUM( CASE WHEN (<some_condition> AND tA.<matching_column> IS NOT NULL ) THEN 1 ELSE 0 END ) as <column_name>...
EXISTS inside CASE inside AGGREGATE FUNCTION
[ "", "sql", "case", "aggregate-functions", "exists", "" ]
I have two tables, as follows: **People**: ``` First_Name Last_Name Bill Smith David Williams Fred Jones Freda Jones Jane Smith John Smith Peter Williams Sally Williams ``` **Pets**: ``` Species Title Owner Dog Fido Jones Cat Tibs Jones Do...
EDIT: The left join syntax in Access causes trouble, which means that for access we need to involve a subquery. This will look something like (the untested); ``` SELECT People.*, Pets.Title FROM People LEFT JOIN [SELECT Pets.* FROM Pets WHERE Pets.Species = 'Cat']. AS Pets ON People.Last_Name = Pets.Owner ``` ...
> this doesn't list any rows for the Williams family because they own a Dog That's because of the `WHERE` clause: ``` WHERE Pets.Species IS NULL OR Pets.Species = "Cat" ``` If `Pets.Species` is `"Dog"` then this would evaluate to false, so those records are not shown. First remove the clause entirely: ``` SELECT Pe...
How to get the Joins right in a SQL query
[ "", "sql", "ms-access", "" ]
I have column of 24 hr and i need to change it to 12 hr, Please help . ``` Start time 174300 035800 023100 ``` The result should be ``` Start time 05.43 PM 03.58 AM 02.31 AM ```
Use `STUFF` function to convert string to `Time` format ``` SELECT CONVERT(VARCHAR,CAST(STUFF(STUFF(ColumnName,3,0,':'),6,0,':') AS TIME),100) ```
Using one of the examples above - the following will work. You need to split the data into hours/minutes and cast it to time format, than convert it to the relevant type: ``` declare @data int set @data = 174300 select convert(VARCHAR(15),cast(cast(left(@data, 2 )as varchar(2)) + ':' + cast(substring(cast(@data as ...
how to convert the 24 hr to 12 hr in sql
[ "", "sql", "sql-server", "database", "" ]
I have four tables: `Books`, `Magazine`, `Member` and `Transaction` and each has a column `Title`. **Books** table ``` BookId, Title, author, edition, no_of_books 1, Harry Potter, Jk rowling, 5, 11 ``` **Magazine** table: ``` MagazineId, Title, Publisher, editi...
Try this: ``` SELECT t.tran_id, case when t.category = 'books' then b.title else t.title end AS title, u.name, t.issue_date, t.receive_date FROM transaction t INNER JOIN member u ON t.trans_mem_id = u.memberid LEFT JOIN books b ON t.trans_item_id = b.bookid AND t.category = 'books' LEFT JOIN magazines m ON...
select t.trans\_item\_id as tran\_id, coalesce(b.title, ma.title), m.name, t.issue\_date, t.receive\_date from transaction t inner join member m on m.memberid = t.trans\_mem\_id left join books b on t.trans\_item\_id = b.bookid left join magazine ma on t.trans\_item\_id = ma.Magazineid
How to get data from two table that using same primary key
[ "", "sql", "database", "" ]
I have to fetch duplicate record if date difference between duplicate record is more than 96 hours or 4 days otherwise ignore the duplicate entry and return record with first entry or oldest date. My table look like this : ``` ID SDATE ----------- ----------------------- 1 2016-04-13 14:54:18.983 1...
The below query returns the expected result, added the inline comments: ``` -- Simply grouping each ID and get unique row with minimum date SELECT MIN(SDATE) [SDate], ID FROM tt GROUP BY ID UNION -- Get the row with each ID's difference is more than 96 hours SELECT D.MaxDate [SDate], D.ID FROM ( SELECT MIN(SDA...
``` declare @table table ( ID int, SDATE datetime) insert into @table ( ID ,SDATE ) values (1,'2016-04-13 14:54:18'), (1,'2016-04-08 12:55:47'), (2,'2016-04-13 14:54:18'), (3,'2016-04-13 14:54:18'), (4,'2016-04-13 14:54:18'), (5,'2016-04-13 14:54:18'), (5,'2016-04-11 12:55:47'), (6,'2016-04-13 14:54:18'...
how to return duplicate rows if date difference is equal or more than 4 days or 96 hours
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "group-by", "" ]
I have the following data: ``` CREATE TABLE offer ( id INTEGER, product_id VARCHAR, created_at TIMESTAMP, amount INTEGER, PRIMARY KEY (id)); INSERT INTO offer (id, product_id, created_at, amount) VALUES (1, '123', '2016-03-12', 990), (2, '136', '2016-02-01', 105...
If I understand correctly, you can use `distinct on`: ``` select distinct on (product_id) o.* from offers o order by product_id, amount desc; ``` `distinct on` is a Postgres extension. In this case, it returns one row per `product_id`. The particular row is the one with the largest amount, as determined by `amount de...
You could use `RANK()`: ``` WITH cte AS ( SELECT * , RANK() OVER (PARTITION BY product_id ORDER BY amount DESC) AS rnk FROM Offers ) SELECT id, product_id, created_at, amount FROM cte WHERE rnk = 1 ORDER BY amount DESC; ``` `LiveDemo` Keep in mind that if there will be 2 or more `product_id` created with differe...
PostgreSQL select max from rows
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
When building a stored procedure that inserts into a simple link table, should it check if the FK's exist and gracefully return an error or just let SQL throw an exception? * What is best practice? * What is most efficient? Just in case someone doesn't understand my question: * `Table A` * `Table B` * `Table AB` Sh...
**If the tables are under your control, there is no reason to perform an extra check.** Just assume they are set up correctly, and let SQL handle any error. Constantly checking that you have indeed done what you intended to do is overly defensive programming that adds unnecessary complexity to your code. For example, ...
As a basic concept, validating values before a potentially error raising code is a good thing. However, in this case, there could be (at least theoretically) a change in table a or table b between the exists checks and the insert statement, that would raise the fk violation error. I would do something like this: ``` ...
Stored procedure best practice? Should they check if foreign keys exist before inserting?
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a query : ``` insert into xx_tab_abc (wr_flag,actual_term_date,person_num) SELECT BOL_FLAG, ACTUAL_TERM_DATE, PERSON_NUMBER FROM WR_TAB ``` Can i modify this select query in such a way that if `actual_term_date in wr_tab` is not null then 'Y' is inserted into `wr_flag` else no value is passed ?
``` SELECT case when ACTUAL_TERM_DATE is not null then 'y' else BOL_FLAG end, ACTUAL_TERM_DATE, PERSON_NUMBER FROM WR_TAB ```
Are you saying that you don't want to insert anything if `ACTUAL_TERM_DATE` is null? If so, you can just do this ``` insert into xx_tab_abc (wr_flag, actual_term_date, person_num ) SELECT 'Y', ACTUAL_TERM_DATE, PERSON_NUMBER FROM ...
Insert into one table to another and use case in select
[ "", "sql", "oracle", "sql-insert", "" ]
I'm having trouble figuring out the evaluation order of boolean predicates in SQL. Consider the following selection predicate over our (imaginary) car database: ``` WHERE make='Honda' AND model='Accord' OR make='VW' AND model='Golf'; ``` I know that AND has precedence over OR, however I'm confused if this expression...
This should be evaluated like ``` WHERE (make='Honda' AND model='Accord' ) OR (make='VW' AND model='Golf'); ``` **Explanation:** In SQL server [`AND` has precedence over `OR`](https://msdn.microsoft.com/en-in/library/ms190276.aspx) and there fore you can imagine AND parts to be inside parenthesis and evaluated first ...
if you are unsure about the evaluation order (me too, btw), you always can set parentheses as needed. So you "define" your evaluation order yourself, and even if the sql interpreter changes its evaluation behaviour, the result will still be the same. I know that this does not really answer your question, but why bothe...
Order of evaluation of boolean expressions in SQL
[ "", "sql", "" ]
For some reason I have a hard time grasping joins and this one should be very simple with the knowledge that I have in SQL. Anyway, I have 2 tables. We will call them TableA and TableB. One of the columns in TableA is "ID". TableB only consists of the column "ID". I want to return all rows in TableA whose ID is presen...
You can do this using an `EXISTS`: ``` Select A.* From TableA A Where Exists ( Select * From TableB B Where A.Id = B.Id ) ``` You can also use a `JOIN` if you wish, but depending on your data, you may want to couple that with a `SELECT DISTINCT`: ``` Select Distinct A.* From TableA A J...
this should work ``` SELECT B.ID FROM TableA A JOIN TableB B ON (A.ID=B.ID) WHERE A.ID=B.ID ```
Join of Two Tables where Data Matches in One Column
[ "", "sql", "sql-server", "" ]
I have a table with a UserID and ImageID Column. I want to select all the UserId's with only one ImageID. I have the code below. ``` Select UserID From AF.UserImageTable Where Count(ImageId) = 1 ``` When I run the code I get the error. ``` An aggregate may not appear in the WHERE clause unless it is in a subquery co...
When you use the below group by clause with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows(in this case UserID and aggregates their values) and then the HAVING clause eliminates groups that you dont need. ``` Select UserID,count(ImageId) From AF.UserImageTable group by UserID having ...
try : ``` Select UserID From AF.UserImageTable Group By UserID Having Count(ImageId) = 1 ```
Select ID Where only one value exists for that ID
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have this condition in my stored procedure to determine which `WHERE` clause to use: ``` IF (@communityDesc = 'All Areas') BEGIN WHERE V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (SELECT name FROM dbo.splitstring(@communityDesc)) AND V_CONSTAT_ACTUAL_DATES.DATE_TO_E...
Or just put all of the logic into a single WHERE ``` SELECT * FROM [Table] WHERE V_CONSTAT_ACTUAL_DATES.DATE_TO_END >= GETDATE() AND (@communityDesc = 'All Areas' OR V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (SELECT name FROM dbo.splitstring(...
You can't separate out a query by a conditional. You'd have to do something like. ``` if(@communityDesc = 'All Areas') BEGIN SELECT * FROM Table WHERE V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (select name from dbo.splitstring(@communityDesc)) AND V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE() ORDER ...
SQL Server : IF condition not working in stored procedure
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have written a PL/SQL code to to print only records greater than id=4. I used a goto statement in the program, which is not detected in exception. Please help me continue the program after encountering the exception. My code is ``` declare cursor cur is select * from student; c student%rowtype; lt3 excep...
when you use `goto` in `cursor`, cursor will be closed, hence you cannot achieve the expected behaviour. From [Doc](https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/goto_statement.htm) > If you use the GOTO statement to exit a cursor FOR loop prematurely, > the cursor is closed automatically. The cursor is also...
You should avoid using goto statement in any code if you can. Below code should achieve what you are trying to do. I don't have access in database so there might be some incorrect syntax. ``` declare cursor cur is select * from student; c student%rowtype; lt3 exception; PRAGMA exception_init(lt3,-...
How do i continue running my program after encountering exception in SQL?
[ "", "sql", "oracle", "exception", "plsql", "goto", "" ]
I have the following sql query which gets back unique days from a column of time stamp values for a particular user. What I am trying to get back is the count of timestamp values for each unique day for a particular user. ``` select distinct DAY(time) from users_has_activities where usersID = 47; ```
Using a count `COUNT(column_name)` with a GROUP BY should do the trick: ``` SELECT DAY(time), COUNT(DAY(time)) FROM users_has_activities WHERE usersID = 47 GROUP BY DAY(time); ```
``` select count(distinct DAY(time) ) from users_has_activities where usersID = 47; ```
SQL query with where and distinct
[ "", "mysql", "sql", "" ]
I made two tables like this ``` degree_plan student_record ------------------------------ ---------------------------- major course course_no ID course_no grade ------------------------------ ---------------------------- COE COE200 1 ...
Try this way ``` select a.mjor, a.course, b.grade from degree_plan as a left join student_record as b on a.course_no=b.course_no and b.id=4455 where a.major='COE' ```
``` select * from degree_plan left join studen`t_record on studen`t_record.course_no = degree_plan.course_no where major = 'COE' ``` you need major in the where to filter
How can I restrict LEFT JOIN?
[ "", "mysql", "sql", "" ]
These are my **tblEmp** table and **tblDept** table(I'm using MS-SQL Server 2012), when I try using a cross join on these two tables it's giving me the result which I didn't expected, just wanted to know why this cross join gives this kind of result, Thank you. ``` ID Name Gender Salary Dept_id 1 abc male ...
The result is correct, the `cross join` will give you all combinations based on two tables: `tblEmp` and `tblDept`. And since you use `Dept_Name` as the combination, without where clause, it will give you every combination possible between your two tables: ``` Name Gender Salary Dept_Name abc male 2004 ...
A [`CROSS JOIN`](https://technet.microsoft.com/en-us/library/ms190690(v=sql.105).aspx) would give you each row of the first table join with each row of the second table, (a Cartesian product) unless you add a condition using the where clause to connect the two tables (and in that case, it behaves like an inner join) H...
Unexpected result of Cross join
[ "", "sql", "sql-server", "cross-join", "" ]
how do I query a table for a column that is clob type? I need to query the table for the column for a certain string (in addition to other conditions - I might need to use Case statement), my initial idea was to query the data in the sub-query and then find a match using Case in the top query. however I am now stuck as...
Hope this examples illustrates clearly what i am trying to explain. ``` SET SQLBL ON; SET DEFINE OFF; CREATE TABLE CLOB_TEST ( clob_in CLOB ); INSERT INTO CLOB_TEST VALUES ( 'I am working as a DBA and senior database resource in L&T Infotech in Pune India' ); SELECT DBMS_LOB.SUBSTR(CLOB_IN,3000) ot FROM CL...
In many respects, the same way you "query a column" (odd terminology!) of type varchar2. table structure: ``` SQL> describe t Name Null? Type ------------------------- -------- -------------------------------------------- COL1 VARCHAR2(20) COL2 ...
Querying Oracle Clob datatype
[ "", "sql", "oracle", "plsql", "" ]
I'm currently running an aggregate query, summing amounts sold (say) on a given date. ``` select convert(date, datetimesold), sum(amountsold) from tblSold group by convert(date, datetimesold) ``` where datetimesold is a datetime value. The `convert(date,...)` gets rid of the time value, so the `group by` can group ...
You already noticed that it is difficult to convert from UTC to local time zone correctly. In fact, it is very difficult, because rules for daylight savings change. You need to maintain a historical database of timezones to do it properly. I store two timestamps - in UTC and in local time zone. In some reports we need...
If you have access to the timezone name somehow, you can use the variant of the SQL date function that accepts a standard timezone string e.g. ``` select date(date, @timezone_name) as dte, sum(amountsold) from tblSold group by dte ``` where `@timezone_name` is any value from: ``` select * from sys.time_zone...
How to efficiently group by date with a timezone specified?
[ "", "sql", "sql-server", "t-sql", "date", "azure-sql-database", "" ]
I'm trying to sum a certain column over a certain date range. The kicker is that I want this to be a CTE, because I'll have to use it multiple times as part of a larger query. Since it's a CTE, it has to have the date column as well as the sum and ID columns, meaning I have to group by date AND ID. That will cause my r...
I eventually found a solution, and it doesn't need a CTE at all. I wanted the CTE to avoid code duplication, but this works almost as well. Here's a [thread explaining summing conditionally](https://stackoverflow.com/questions/21421973/sum-for-multiple-date-ranges-in-a-single-call) that does exactly what I was looking ...
Depending on what you are looking for, this might be a better approach: ``` select 'by sales rep' breakdown , salesRep , '' year , sum(price * amountShipped) amount from etc group by salesRep union select 'by sales rep and year' breakdown , salesRep , convert(char(4),orderDate, 120) year , sum(price * amountShipped...
Summing a column over a date range in a CTE?
[ "", "sql", "function", "aggregate", "common-table-expression", "" ]
I currently have six queries in which I take the results and use a spreadsheet to calculate two different final percentages. I believe that it can be done in a single query, and without a spreadsheet, but I am not knowledgeable enough in SQL to figure it out. I am hoping for some direction from the amazing SQL Gods her...
You can't use variables like that and you can't do this in one aggregate query because it's going to create a massive Cartesian product and give you incorrect results. You could use CTE's or subqueries for each query you have listed and then join them together on the STID and apply your formulas. example... ``` /* d...
You never set the variables to any real value, the you proceed to select the useless variable in a irrelevant SELECT statement. in the following line ``` Set @pdD = Sum( Case When a.DueDate < GetDate() Then DateDiff(d,a.DueDate,@runDate) * (a.WeeklyRate/7) ) ``` You are not stating where s.DueDate comes from. It won...
TSQL calculating from combined queries
[ "", "sql", "t-sql", "" ]
I have the following SQL and it returns 349017 records. The number of records will increase on a daily basis. Currently I used pagination to display only 12 records. It took around 2 to 3 secs to return every 12 records. How do I optimize the query to 0 second? Kindly give any solution / suggestions. I have a lot of ...
Solution is really simple - you should have `vInfo.CreatedDate` as indexed DATETIME column. If modifying column type isn't possible for some reason, you can create a [`PERSISTENT` computed column](https://technet.microsoft.com/en-us/library/ms191250%28v=sql.105%29.aspx) and then define an index on it. Example: ``` A...
Without a schema and sample data, it's just a guess, but it appears that ``` ORDER BY CAST(vInfo.CreatedDate AS DATETIME) DESC ``` is the biggest time sink. Ideally, you wouldn't store dates as something other than datetime - I'm guessing you'll need to sort on createdData in more places. If you cannot modify ...
SQL Query Performance Optimization
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I've managed to use this query ``` SELECT PartGrp,VendorPn, customer, sum(sales) as totalSales, ROW_NUMBER() OVER (PARTITION BY partgrp, vendorpn ORDER BY SUM(sales) DESC) AS seqnum FROM BG_Invoice GROUP BY PartGrp, VendorPn, customer ORDER BY PartGrp, VendorPn, totalSales DESC ``` To get a r...
I would change your query to be like this: ``` SELECT PartGrp, VendorPn, customer, sum(sales) as totalSales, ROW_NUMBER() OVER (PARTITION BY partgrp,vendorpn ORDER BY SUM(sales) DESC) as seqnum, COUNT(1) OVER (PARTITION BY partgrp,vendorpn) as cnt FROM BG_Invoice GROUP BY PartGrp,Ve...
You can try something like: ``` SELECT PartGrp,VendorPn, customer, sum(sales) as totalSales, ROW_NUMBER() OVER (PARTITION BY partgrp,vendorpn ORDER BY SUM(sales) DESC) as seqnum FROM BG_Invoice GROUP BY PartGrp,VendorPn, customer HAVING seqnum <> '1' ORDER BY PartGrp,VendorPn, totalSales desc ```
T-SQL: Select partitions which have more than 1 row
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using a Control Flow and Data Flow tasks to record the number of rows read from an Excel data source in Visual Studio SSIS. The data is then processed into good and bad tables, the rows in these counted and the results written into a statistics table via a parameterised SQL statement. For reasons unknown the data ...
Is that an Access parameterised query? I've never run one of those from SSIS. I do know that SSIS can be weird about mapping the values from the variables to the query parameters. Have you noticed that the display order of your variables (in the variable-to-parameter mapping) is the same as how they get assigned to pa...
I recommend that you create a fourth variable for the fourth parameter rather than trying to do math in the ExecuteSQL task. Instead of using P1, P2 & P3 in the Parameter Names column of the Parameter-mapping tab, try using their zero-based ordinal position. In the query itself, use question marks for the parameters:...
SSIS Variables and Parameters written to wrong Access Fields
[ "", "sql", "visual-studio", "ms-access", "ssis", "" ]
I have a table 'floating\_options', and I want to create a spatial index on a column 'area\_geo' (which is a sdo\_geometry column, with two rows of data that appear as expected when I select \* from floating\_options). I have used the following code but I am receiving the error below. I would be very grateful for any ...
Before indexing the table you should have it 'spatially enabled'. Try to check if it is shown in spatial metadata: ``` SELECT * FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = UPPER('floating_options') AND COLUMN_NAME = UPPER('area_geo'); ``` If there are no results - then a couple of options are available...
The following should also be considered: Oracle has case-sensitive names [see this post](https://stackoverflow.com/questions/563090/oracle-what-exactly-do-quotation-marks-around-the-table-name-do). The next problem with the "intelligent" guys of Oracle is, that their USER\_SDO\_GEOM\_METADATA table does not support lo...
Creating a spatial index on oracle
[ "", "sql", "oracle", "geospatial", "spatial-index", "" ]
I have two tables with the following formats: Table Name: "Awards" ``` id | Name | Exp_1 | Exp_2 | Exp_3 1 | Joe | 1 | 2 | 3 2 | Bob | 1 | | 3 3 | James | | 2 | ``` Table Name: "Exp" ``` id | Exp 1 | Ser...
You would seem to need multiple left joins: ``` select a.id, a.name, e1.exp as exp1, e2.exp as exp2, e3.exp as exp3 from awards a left join exp e1 on a.exp_1 = e1.id left join exp e2 on a.exp_2 = e2.id left join exp e3 on a.exp_3 = e3.id ; ```
Try this ``` SELECT a.id, a.Name, exp1.Exp, exp2.Exp, exp3.Exp FROM Awards a LEFT JOIN Exp exp1 on exp1.id = a.Exp_1 LEFT JOIN Exp exp2 on exp2.id = a.Exp_2 LEFT JOIN Exp exp3 on exp3.id = a.Exp_3 ``` You will need to join each of your Exp fields in Awards table to the Exp table, use LEFT JOIN in case there is no val...
SQL joining between columns and rows
[ "", "sql", "" ]
-1 to 100 in SQL and display 'Fizz' if the number is divisible by 3 'Buzz' if divisible by 5 and 'FizzBuzz' if divisible by both. below is my code ``` select Case when Remainder (rownum,3)=0 then 'Fizz' when Remainder (rownum,5)=0 then 'Buzz' when (remainder (rownum,3)=0 and remainder(ROWNUM,5) = 0) then ...
You need to convert `ROWNUM` to a string in your `ELSE` case by either: * `CAST( ROWNUM AS VARCHAR2(3) )` * `''||ROWNUM` * `TO_CHAR( ROWNUM )` You also need the case when it is divisible by both 3 and 5 to be at the top of the list (otherwise the preceding cases will take precedence). Like this: ``` SELECT CASE ...
It's in your else statement. Rownum is a NUMBER whereas Fizz, Buzz, and FizzBuzz are CHAR.
Fizz buzz SQL logic error
[ "", "sql", "oracle", "" ]
I want to add incremental value on insert function. I have tried the following code but is not working. I want to increment `COLUMN1` by 1 each time.`COLUMN1` is not a key column. ``` @var=0; INSERT INTO TABLE_A (COLUMN1,COLUMN2,COLUMN3,COLUMN4) SELECT @var++,COLUMN6,COLUMN7,COLUMN8 FROM TABLE_B; ``` ...
You can use `ROW_NUMBER` to generate sequential value for `COLUMN1`: ``` INSERT INTO TABLE_A (COLUMN1,COLUMN2,COLUMN3,COLUMN4) SELECT ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) - 1, COLUMN6, COLUMN7, COLUMN8 FROM TABLE_B; ```
You can try to make the column as `IDENTITY` column. If it is an existing column then you can add it like this: ``` ALTER TABLE (TABLE_A) ADD NewColumn INT IDENTITY(1,1) ALTER TABLE (TABLE_A) DROP COLUMN COLUMN1 sp_rename 'TABLE_A.NewColumn', 'COLUMN1', 'COLUMN' ``` and then simply do like ``` INSERT INTO TABLE_A ...
SQL Insert Function (Insert incremental value)
[ "", "sql", "sql-server", "sql-server-2012", "" ]
This is my table **tblEmployee** ,when I'm trying to use a self join query it's result is varying while shifting columns, can someone please explain me the difference between those two queries.Thanks ``` EmployeeID Name ManagerID 1 Mike 3 2 Rob 1 3 Todd NULL 5 Be...
First a simple explanation: the left join takes every row in the first table that has at least a match in the second table on the column you selected. In the **first query** you are considering the *Manager ID* on every row and looking for a match on the *Employee ID* in the second table: since value in the second tab...
With **Query1** you are selecting each employee (E) and their manager (M) if there is one (left join). With **Query2** you reversed that. You are selecting each employee (E) and their subordinates (M). The alias for `M.Name` is incorrect now, because it's not the manager but a subordinate. As some employees have more ...
Not quite understanding the query after just shifting column names
[ "", "sql", "sql-server", "join", "self-join", "" ]
I have a table named CompApps and I wish to retrieve particular records based on a multiple condition query. My SQL is very rusty and this is why I am asking on Stack Overflow. What I need is to amend the SQL below to include a where clause that will exclude records that do not have any relevant information in the fiel...
Or maybe like this Correcting this according to dnoeth's comment: ``` SELECT RefNum, Interface, ExAPI, ExtraInfo, OpenCol FROM CompApps WHERE Interface NOT IN('None','N/A') OR ExAPI NOT IN('None','N/A') OR ExtraInfo NOT IN('None','N/A') OR OpenCol NOT IN('None','N/A'); ```
Try this: ``` SELECT RefNum, Interface, ExAPI, ExtraInfo, OpenCol FROM CompApps WHERE (Interface IS NOT NULL AND (Interface !='None' AND Interface !='N/A')) OR (ExAPI IS NOT NULL AND (ExAPI != 'None' AND ExAPI != 'N/A')) OR (ExtraInfo IS NOT NULL AND (ExtraInfo != 'None' AND ExtraInfo != '...
Complex SQL Query Filter
[ "", "sql", "sql-server", "" ]
I am having a lot of trouble with PostgreSQL trying to figure out how to find the most common value that fits a specific criteria. The `ID` is the ID number of the book, meaning repeating numbers means there are multiple copies of the book. I have 2 tables here: ``` Table A: =====+=================== ID | Conditi...
Ok, so firstly I assumed that your columns and tables names are case sensitive which means you must use duble quote marks. To print most "taken" book name with number of "taken" copies, you can use simple aggragete `count()`, then order the output descending and at the end limit the output to 1 row, like: ``` SELECT ...
``` CREATE TEMP TABLE MostCommon AS (SELECT id, (sum(ID)/id) book_taken FROM tableA where condition = 'Taken' group by id); select name from tableB t2 join MostCommon mc on mc.id = t2.id where mc.id in (select max(book_taken) from MostCommon) ```
Finding value with most common condition
[ "", "sql", "postgresql", "aggregate-functions", "" ]
I would like to find data in a table with no matching records based on two fields (ContractState, TransID). For instance, assume this data set (in reality, all data sets contain hundreds of records, I'm just including a few): ``` AccountNbr ContractState TransID Product 3335477 AL 80079 ...
Use window functions. For the data you provided, this should work: ``` select cs.* from (select cs.*, count(*) over (partition by AccountNbr, ContractState) as cnt from tblSQLContractState cs where TransID IN (80079, 80080) ) cs where cnt = 1; ```
You can use a `NOT EXISTS` to select records where there is another record with this `TransId` but not with this `ContractState`: ``` SELECT 'tblSQLContractState' as TableName, cs.AccountNbr, cs.ContractState, cs.TransID, cs.Product FROM tblSQLContractState cs WHERE cs.TransID IN (80079, 80080) AND NOT EX...
SQL to find only data in a table with no matching records
[ "", "sql", "sql-server", "" ]
I have a large database with connections between cities. Each connection has a start and destination town, a start date, and a price for that connection. I'd like to compute any combinations of outgoing+return connections, for any connections, and for dates where the return connection is between 1-20 days. Then select...
The query to get all pairs uses a `join`: ``` select tto.city_start, tto.city_end, tto.date_start, tfrom.date_end, (tto.price + tfrom.price) as price from t tto join t tfrom on tto.city_end = tfrom.city_start and tto.city_start = tfrom.city_end and tfrom.date_start >= tto.date_start + ...
Here is a solution without the row\_number partition part: ``` SELECT a.city_start, a.city_end, b.city_end, a.date_start, b.date_start, min(a.price + b.price) FROM flight AS a JOIN flight AS b ON a.city_start = b.city_end AND a.city_end = b.city_start WHERE b.date_start BETWEEN a.date_start + 1 AND...
How to compute permutations with postgresql?
[ "", "sql", "postgresql", "" ]
I'm trying to query the sum of the populations of all cities where the CONTINENT is 'Asia'. The two tables CITY and COUNTRY are as follows, ``` city - id, countrycode, name population country - code, name, continent, population ``` Here's my query ``` SELECT SUM(POPULATION) FROM COUNTRY CITY JOIN ON COUNTRY.CODE = C...
It isn't working because the way you've written it `CITY` is being interpreted as a table alias for `COUNTRY`. Additionally, it looks like you've got a POPULATION column in each table so you need to disambiguate it. Let me rewrite the query for you: ``` SELECT SUM(CITY.POPULATION) FROM COUNTRY JOIN CITY ON COUNTRY.COD...
I know the question was already answered, but I would like to put out the optimised solution. The below solution will decrease the execution time and at the same time it will take less resource to perform the SQL query. ``` select sum(a.population) from city a inner join(select * from country where continent = 'Asia')...
Simple inner join not working
[ "", "mysql", "sql", "" ]
I have a varchar value like this: ``` DECLARE @TestConvert VARCHAR(MAX) = '1234.94-' ``` And I want to convert this value to a `decimal(5,2)` likes this: ``` SELECT CAST(@TestConvert AS DECIMAL(18, 4)) ``` The problem is the sign at the end of the value. If the sign is at the beginning like this: ``` DECLARE @Tes...
For SQL2012 and above `PARSE` will handle this. (My test box is running 2016 so apologies if this doesn't work for you) ``` DECLARE @TestConvert VARCHAR(MAX) = '1234.94-' SELECT PARSE(@TestConvert AS DECIMAL(18, 4)) AS Converted Converted --------------------------------------- -1234.9400 (1 row(s) affected) ``` `...
``` DECLARE @TestConvert VARCHAR(MAX) = '1234.94-' if(charindex('-', @TestConvert) = len(@TestConvert)) begin set @TestConvert = replace(@TestConvert, '-', '') select 0 - cast(@TestConvert as DECIMAL(6, 2)) end else select cast(@TestConvert as DECIMAL(6, 2)) ```
SQL Server : convert varchar to numeric with sign at the end
[ "", "sql", "sql-server", "sql-server-2012", "" ]
``` UPDATE WEB SET WEB.ID_D_SUPPORT = DIM.ID_D_SUPPORT FROM dbo.F_SUPPORT_WEB WEB INNER JOIN dbo.D_SUPPORT DIM ON WEB.id_support = DIM.id_support AND (WEB.date_creation BETWEEN DIM.Date_Deb_Valid AND DIM.Date_Fin_Valid) ``` I have this query below with 300 million rows in the table F\_S...
If your log table drive isn't big enough to support that single transaction, you need to break it up into multiple transactions. I had a similar issue and tested until I found a sweet spot (100,000 rows updated for me). Keep looping until all records are done. You could do so by simply modifying your query. ``` UPDATE...
You'll want to run updates on a loop. When you try to update all those records at once, it has to copy all of them to the transaction log in case of an error so it can roll back the changes. If you do updates in batches, you won't run into that issue. See below ``` SELECT 1 --Just to get a @@ROWCOUNT established WHILE...
How can I run this UPDATE query faster?
[ "", "sql", "sql-server-2008-r2", "sql-update", "inner-join", "between", "" ]
I have a strange situation with a simple select by column `pqth_scan_code` from the following table: **table pqth\_** ``` Field Type Null Key Default Extra pqth_id int(11) NO PRI NULL auto_increment pqth_scan_code varchar(250) NO NULL pqth_in...
``` SELECT * FROM `pqth_` WHERE pqth_scan_code = "7900722!30@3#6$EN" ``` needs `INDEX(pqth_scan_code)`. Period. End of discussion. ``` SELECT * FROM `pqth` WHERE `pqth_id`=27597 ``` has a useful index, since a `PRIMARY KEY` is an index (and it is unique). ``` SELECT * FROM `pqthc` WHERE pqthc_scan_code = "7900722!3...
you have to understand the concept of primary key and indexes and how they help in searching, reference docs [here](http://dev.mysql.com/doc/refman/5.7/en/optimization-indexes.html)
SQL - Strange issue with SELECT
[ "", "mysql", "sql", "mariadb", "" ]
I am able using the code below to select data from any number of days in the past but what if I only want the data from the previous month, e.g. from 60 days ago to 30 days ago. I thought I might be able to use `INTERVAL 60 - 30`, but I am not sure that is working... ``` SELECT product, COUNT(OrderNumber) AS ...
This is too long for a comment: ``` Date(OrderDate) < DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND Date(OrderDate) >= DATE_SUB(CURDATE(), INTERVAL 60 DAY) ``` Note: if `OrderDate` is already a date, then don't use the `DATE()` function. It can prevent the use of indexes. Even if `OrderDate` has a time component, you pr...
Do you know about the MySQL functions `MONTH()` and `NOW()`? You can use these in your where clause: ``` MONTH(OrderDate) = MONTH(NOW()) - 1 ``` Of course, this needs to be fine tuned for example for years (to get December if it is January).
SQL Select data from previous month
[ "", "mysql", "sql", "" ]
I want to query the list of `CITY` names from the table `STATION(id, city, longitude, latitude)` which have vowels as both their first and last characters. The result cannot contain duplicates. For this is I wrote a query like `WHERE NAME LIKE 'a%'` that had 25 conditions, each vowel for every other vowel, which is qu...
You could use a [regular expression](http://dev.mysql.com/doc/refman/5.7/en/regexp.html#operator_regexp): ``` SELECT DISTINCT city FROM station WHERE city RLIKE '^[aeiouAEIOU].*[aeiouAEIOU]$' ```
in **Microsoft SQL server** you can achieve this from below query: ``` SELECT distinct City FROM STATION WHERE City LIKE '[AEIOU]%[AEIOU]' ``` **Or** ``` SELECT distinct City FROM STATION WHERE City LIKE '[A,E,I,O,U]%[A,E,I,O,U]' ``` **Update --Added Oracle Query** > --Way 1 --It should work in all Oracle versions...
SQL query to check if a name begins and ends with a vowel
[ "", "mysql", "sql", "select", "" ]
I am working on a SQL assignment in Oracle. There are two tables. table1 is called Person10: fields include: ID, Fname, Lname, State, DOH, JobTitle, Salary, Cat. table2 is called StateInfo: fields include: State, Statename, Capital, Nickname, Pop2010, pop2000, pop1990, sqmiles. Question: > Create a view named A10...
Yeah I originally messed this up when I first answered this because it was on the fly and I didn't have a chance to test what I was putting down. I forgot using a GROUP BY is more suited for aggregate functions (Like SUM, AVG and COUNT in the select) and that's probably why it's throwing the error. Using a ORDER BY is ...
You can try using a Sub Query like this. ``` CREATE VIEW A10T2 AS SELECT statename, capital, nickname FROM stateinfo WHERE statename IN (SELECT statename FROM person10 WHERE Cat = 'N' AND Salary BETWEEN 75000 AND 125000 GROUP BY statenam...
SQL Assignment about joining tables
[ "", "sql", "oracle", "inner-join", "" ]
I've searched StackOverflow for all the possible solutions concerning how to insert a linebreak in a SQL text string. I've referred this link but to no avail. [How to insert a line break in a SQL Server VARCHAR/NVARCHAR string](https://stackoverflow.com/questions/31057/how-to-insert-a-line-break-in-a-sql-server-varchar...
Well your query works perfectly fine. SSMS by default shows all query out put in the grid view, which does not display the line break character. To see it you can switch to text view using `cntrl` + `T` shortcut or like below [![enter image description here](https://i.stack.imgur.com/CBXDB.png)](https://i.stack.imgur...
It works perfectly: ``` CREATE TABLE sample(dex INT, col VARCHAR(100)); INSERT INTO sample(dex, col) VALUES (2, 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'); SELECT * FROM sample; ``` `LiveDemo` Output: [![enter image description here](https://i.stack.imgur.com/64L3H.png)](https://i.stack.imgur.com...
SQL: Insert a linebreak in varchar string
[ "", "sql", "sql-server", "t-sql", "" ]
I have a query that gives me the following results. This result set contains the times when jobs on a server started as well as when they finished. ``` JobName LatestStartTime LatestEndTime Job1 2016-04-15 00:00:40.000 2016-04-15 00:07:40.000 Job2 2016-04-15 00:01:23.0...
The difficult part is getting the list of jobs on a single row. The counts are easy: ``` select t.increment, j.jobname, sum(count(*)) over (partition by t.increment) as countOfJobs from times t left join jobs j on t.increment >= j.lasteststarttime and t.increment <= j.lastestendtime group by t...
try this: ``` SELECT [increment], JobName , Count(1) over (Partition by [increment]) AS NumberOfJobs FROM temp_table INNER JOIN ( SELECT JobName, st.t AS t1, LatestEndTime AS t2 FROM query AS q OUTER APPLY ( SELECT Max([increment]) AS t FROM temp_table WHERE [increment] < q.LatestStartTime) as ...
Doing Counts based on timestamps
[ "", "sql", "sql-server", "timestamp", "" ]
I'd like to order pairs (or group of 3,4 etc.) of rows given the SUM of a certain value. The rows are consecutive based on the concatenation of Name+Surname+Age To better understand given the following table: ``` ID Name Surname Age Salary ------------------------------ 1 John Smith 30 2 2 John Smit...
``` SELECT t.*, COALESCE(SUM(salary) OVER (PARTITION BY name, surname, age), 0) ss FROM mytable t ORDER BY ss DESC ```
or try this ``` SELECT ID, Name, Surname, Age, Salary FROM mytable ORDER BY SUM(Salary) OVER (PARTITION BY Name, Surname, Age) DESC, ID ```
Order pairs/triplets of rows given the sum of a column
[ "", "sql", "oracle", "" ]
I have a table in a SQL Server 2008 R2 database that defines transitions between different states. Example relevant table columns: ``` TransitionID | SourceStateID | DestinationStateID | WorkflowID -------------------------------------------------------------- 1 | 17 | 18 | 3 2 ...
Similar to Quassnoi's answer, but prevents circular references that start after the first element: ``` DECLARE @src int = 18, @dst int = 184; WITH cte AS (Select TransitionId, SourceStateId, DestinationStateID, SourceStateID as StartingState, 0 as Depth , cast(TransitionId as varchar(max)) + ',' as IDPath , c...
``` WITH q (id, src, dst, sid, cnt, path) AS ( SELECT transitionId, sourceStateId, destinationStateId, sourceStateId, 1, CAST(transitionId AS VARCHAR(MAX)) path FROM mytable WHERE sourceStateId = 18 UNION ALL SELECT m.transitionId, m.sourceStateI...
SQL Server CTE to find path from one ID to another ID
[ "", "sql", "sql-server", "common-table-expression", "hierarchical", "hierarchical-query", "" ]
I have the following tables: ``` Employees ------------- ClockNo int CostCentre varchar Department int ``` and ``` Departments ------------- DepartmentCode int CostCentreCode varchar Parent int ``` Departments can have other departments as parents meaning there is infinite hierarchy. All department...
SunnyMagadan's query is good. But depending on number of employees in a department you may wish to try the following one which leaves DB optimizer an opportunity to traverse department hierarchy only once for a department instead of repeating it for every employee in a department. ``` SELECT e.ClockNo, e.CostCentre, ...
When we join the tables we should stop further traversal of the path when we found proper department that belongs to the Employee at previous level. Also we have exceptional case when Employee.Department=0. In this case we shouldn't join any of departments, because in this case Department is the Root. We need to choo...
How can I Ascertain the structure for each person from a self referencing table
[ "", "sql", "hierarchy", "self-join", "pervasive-sql", "" ]
i have a cros tab query in MS Access which i want to replicate in T-SQL, T-SQL table '#tmpZSPO\_DMD' has Part,Location, Qty,FiscalMonthPeriod. and when i run, the data looks like below. ``` Part LOCATION Qty FiscalMonthPeriod 123 4040_0086 1 CON00 123 4040_0086 1 CON00 123 4200_0010 1 CO...
A very simple PIVOT will do the job. ``` SELECT * FROM ( SELECT Part, LOCATION, Qty, FiscalMonthPeriod FROM @Table ) t PIVOT ( SUM(Qty) FOR FiscalMonthPeriod IN ([CON00], [CON01], [CON02], [CON03]) ) p ```
``` SELECT tm.PART, tm.Location, SUM(IIF(tm.FiscalMonthPeriod= 'CON00', [Sum], NULL)) As CON00, SUM(IIF(tm.FiscalMonthPeriod= 'CON01', [Sum], NULL)) As CON01, SUM(IIF(tm.FiscalMonthPeriod= 'CON02', [Sum], NULL)) As CON02, SUM(IIF(tm.FiscalMonthPeriod= 'CON03', [Sum], NULL)) As CON03 FROM #tmpZSPO_DM...
Cross tab Pivot in TSQLwith group by and order by
[ "", "sql", "sql-server", "crosstab", "" ]
I have a table called SOITEM. In that table the column TOTALPRICE has to be summed and result in the total sales by month, where the column with the dates is called DATELASTFULFILLMENT. I want to compare sales form Jan 2014 with Jan 2015, then Feb 2014 with Feb 2015 and so forth. I got this so far, but I'm not sure ho...
You could consider grouping your results using the Month/Year from your date field and then using calculating the [`SUM()`](https://msdn.microsoft.com/en-us/library/ms187810.aspx) for each of those groups : ``` SELECT DATEPART(Year, DATELASTFULFILLMENT) AS [Year], DATEPART(Month, DATELASTFULFILLMENT) AS [M...
This works for MySQL. I assume should be the same for MS SQL. ``` Select SUM(SOITEM.TOTALPRICE) FROM SOITEM WHERE DATELASTFULFILLMENT>='2014-01-31' AND DATELASTFULFILLMENT<='2014-01-31' UNION Select SUM(SOITEM.TOTALPRICE) FROM SOITEM WHERE DATELASTFULFILLMENT>='2015-01-31' AND DATELASTFULFILLMENT<='2015-01-31' UNION...
How to sum sales by months and compare them
[ "", "sql", "sql-server", "" ]
I created a table using this query `CREATE TABLE Store (id number(11) primary key not null, opening_time timestamp CHECK (EXTRACT(HOUR FROM opening_time) > 8 || NULL));` Now, when I try to insert some data using `insert into Store values(1, '04/04/2012 13:35 PM');`, I encounter this error `SQL Error: ORA-01843...
`'04/04/2012 13:35 PM'` is not a date - it is a string. Oracle will do an implicit `TO_DATE( string_value, format_mask )` on non-date literals when inserting them into a `DATE` column using the value of the `NLS_DATE_FORMAT` session parameter as the format mask (*note: this is a session parameter and belongs to the cl...
> SQL Error: ORA-01843: not a valid month `'04/04/2012 13:35 PM'` is a **string** and not a **date**. You should always use **TO\_DATE** to explicitly convert a string into date. Never ever rely on **implicit datatype conversion**. You might just be lucky to depend on your **locale-specific NLS settings**. However, it...
Encountering SQL Error: ORA-01843: not a valid month
[ "", "sql", "oracle", "date-formatting", "" ]
I want to delete all rows in both tables where the chart\_id is 1, but it wont work and I dont have any clue why. ``` DELETE `cms_module_charts` FROM `cms_module_charts` INNER JOIN `cms_module_charts_kategorie` ON `cms_module_charts_kategorie`.`chart_id`=`cms_module_charts`.`chart_id` WHERE `chart_id`= 1 ``` This ...
From the [MySQL Docs](http://dev.mysql.com/doc/refman/5.7/en/delete.html) it looks like you can do this easily: ``` DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id; ``` OR ``` DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3 WHERE t1.id=t2.id AND t2.id=t3.id; `...
i think in you database scheme you should use `ON DELETE CASCADE`,then when you delete a rows ,it delete its references but when you deleting using join it doesn't make a sense.
How to delete rows from two tables using INNER JOIN in mysql?
[ "", "mysql", "sql", "database", "join", "inner-join", "" ]
I have a view with this structure: ``` EntryId | EntryName | ParentEntryId | Depth | DatePosted ``` What I want to do is to write an SQL query that will bring the first 2 entries with Depth=0 along with the first descendants (based on the ParentEntryId). Below, I provided an example output. ``` EntryId | EntryName |...
You can also do this with a recursive cte.. You should make sure the performance meets your standards though if you're using this on a large record set ``` ;WITH cte AS ( SELECT [EntryId], [EntryName], [ParentEntryId], [Depth], [DatePosted], [EntryId] [R...
Based on your updated question, below query will yield perfect results ``` SELECT EntryId , EntryName , ParentEntryId , Depth , DatePosted, ChildCount FROM ( SELECT TOP 10 E1.EntryId , E1.EntryName , E1.ParentEntryId , E1.Depth , E1.DatePosted, ( SELECT...
SQL Query to read a certain number of records with nested data
[ "", "sql", "sql-server", "" ]
How to combine select distinct and order by a non-selected attribute or any alternative way? I have a table called message ``` +----+------+-----------+-------------+ | id | body | sender_id | receiver_id | +----+------+-----------+-------------+ | 10 | ... | 1 | 2 | | 28 | ... | 1 | ...
Here's one way to do it: ``` select receiver_id from (select receiver_id, max(id) max_id from message group by receiver_id) ilv order by max_id desc limit 10; ```
I'm not sure what "order by not-selected attribute" means. But the basic query can be handled using `where` and a subquery (or a `join` and explicit aggregation): ``` select m.receiver_id from message m where m.id = (select max(m2.id) from message m2 where m2.sender = m.sender) order by id desc; ``` I am guessing tha...
How to combine select distinct and order by a non-selected attribute or any alternative way?
[ "", "mysql", "sql", "select", "" ]
I have the following two tables (populated with more data): **rating** ``` ID | user_id | rating_value | date 1 1 0.6 2016-04-02 2 2 0.75 2016-04-05 3 1 0.4 2016-04-08 4 2 0.5 2016-04-12 ``` **recommendation** ``` ID | user_id | ...
You can try the below query which will work in **PostgreSQL**, mySQL and SQL server ``` SELECT rec.user_id, rec.recommendation_text, rec.date, rating.rating_value, rating.date FROM recommendation AS rec JOIN rating ON rec.user_id = rating.user_id JOIN (SELECT rec.id as id1, max(rating.id) as id2 FROM recommendation...
Another method without subselect: ``` select rec.user_id, rec.recommendation_text, rec.dates, rat.rating_value, rat.dates from recommendation as rec left join rating as rat on rat.user_id = rec.user_id and rat.dates < rec.dates left join rating as rat1 on rat.user_id = rat1.user_id and rat.dates < rat1.dates and rat1....
SQL Join Sorting and Limiting Results
[ "", "sql", "postgresql", "join", "" ]
I have the following code: ``` SELECT cr_ts, msg_id, info FROM messaging_log WHERE UPPER(INFO) LIKE '%' || TRIM(UPPER(P_INFO)) || '%' AND cr_ts >= NVL(P_DATE, SYSDATE-10) AND msg_id = NVL(P_ID, msg_id) ORDER BY cr_ts desc; ``` where P\_INFO, P\_DATE and P\_ID are parameters. In the normal case every parameter is NUL...
Try this;) ``` SELECT cr_ts, msg_id, info FROM messaging_log WHERE UPPER(INFO) LIKE '%' || TRIM(UPPER(P_INFO)) || '%' AND ((P_DATE IS NULL AND cr_ts >= (SYSDATE - 10)) OR cr_ts >= P_DATE) AND (P_ID IS NULL OR msg_id = P_ID) ORDER BY cr_ts DESC; ```
``` SELECT cr_ts, msg_id, info FROM messaging_log WHERE UPPER(INFO) LIKE '%' || TRIM(UPPER(P_INFO)) || '%' AND cr_ts >= NVL(P_DATE, SYSDATE-10) AND NVL(msg_id,'*') = NVL(P_ID, '*') ORDER BY cr_ts desc; ```
How to use NVL in where clause
[ "", "sql", "oracle", "" ]