Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've searched around, but haven't found the similar situation to what I'm trying to achieve. I want to execute the where clause expression only when the condition is true, otherwise I want to ignore the data that doesn't match it. ``` Where ( case when LeaveDateTime > FromDate and EnteringDateTime < ToDate the...
"execute where clause expression only when the condition is true, otherwise I want to ignore the data that doesn't match it" Since you say you want to ignore, i.e. not include, data otherwise if the first condition is not met, then it sounds like you want a simple AND. That's may not be what you intended to express, w...
Replace this with simple logic: ``` Where (not (LeaveDateTime > FromDate and EnteringDateTime < ToDate) or dateadd(day, Threshhold, LeaveDateTime) >= EnteringDateTime ); ``` If the variables take on `NULL` values, then the logic is somewhat more cumbersome. Your version doesn't work because `case` is a ...
Conditional where clause SQL Server 2012
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I must write query in SQL which will return Account Id. For this query i have input parameters, which can be empty. In database here is rows where some field is null or empty. So in case parameter is empty i also need to check field if it's null. ``` SELECT a.Account_ID FROM Accounts a WHERE a.FirstName =...
I think it is a or condition you need: ``` SELECT a.Account_ID FROM Accounts a WHERE ((@FirstName='' and a.FirstName is null) or a.FirstName = @FirstName) /*Add check if @FirstName = '' then a.FirstName IS NULL */ AND a.LastName = @LastName AND a.Middle = @MiddleName AND a.Email = ...
I normally do something like this if i want special behavior for empty params: ``` SELECT a.Account_ID FROM Accounts a WHERE ( (@firstname != '' AND a.FirstName = @FirstName) OR (@firstname = '' AND a.FirstName is null) ) AND a.LastName = @LastName AND a.Middle = @MiddleName AND a.Email = @Email AND...
In Where clause add check if Parameter is empty string
[ "", "sql", "select", "conditional-statements", "sql-server-2014", "" ]
I have a table and there are 4 fields in it, `ID, Price, QTY, Ratting` and Optional [Position]. I have all the records Grouped By Columns `[Qty,Ratting]` I have to define the position of groupwise and store that Position into Optional column. For better understanding I have added an image with data in table: ![ente...
You can try this: ``` SELECT ID ,Price ,Qty ,Ratting ,CASE WHEN RowID >= 1 AND RowID <= 3 THEN 0 ELSE CASE WHEN RowID > Total - 3 THEN 1 ELSE 2 END END AS Position FROM (SELECT ID ,Price ,Qty ,Ratting ,COUNT(*) OVER(PARTITION ...
Use `Window Function`. Try this. ``` ;WITH cte AS (SELECT *, Row_number()OVER(partition BY rating ORDER BY id) rn, count(id)OVER(partition BY rating) mx FROM @RankTable) SELECT ID, Price, Qty, Rating, mx - rn, CASE WHEN rn IN (...
Find Top Most AND Lowest In a Table's Group Column
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I know how to find all tables with specified column name in database: ``` SELECT TABLE_NAME , COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%Name%' ``` As a result I get a table with `TABLE_NAME` and `COLUMN_NAME`. Is it possible to set all values in columns received by query to NU...
Use `Dynamic Sql`. Try this. ``` DECLARE @sql NVARCHAR(max)='' SELECT @sql += 'update ' + TABLE_NAME + ' set ' + COLUMN_NAME + '= NULL ' FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE '%Name%' --print @sql EXEC Sp_executesql @sql ```
You cannot define each table and each column in your query. For that you need to select tables and columns dynamically and execute it. You can use a cursor to this dynamically ``` DECLARE @TableName VARCHAR(100)='' DECLARE @ColumnName VARCHAR(100) DECLARE @PreviousTableName VARCHAR(100)='' DECLARE @PreviousColumnName...
Find all tables with specified column name and set values to NULL
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a table in Hive (SQL) with a bunch of timestamps that need to be grouped in order to create separate sessions based on the time difference between the timestamps. Example: Consider the following timestamps(Given in HH:MM for simplicity): `9.00 9.10 9.20 9.40 9.43 10.30 10.45 11.25 12.30 12.33` and so on.. So n...
So it's not MySQL but Hive. I don't know Hive, but if it supports LAG, as you say, try this PostgreSQL query. You will probably have to change the time difference calculation, that's usually different from one dbms to another. ``` select min(thetime) as start_time, max(thetime) as end_time from ( select thetime, cou...
With MySQL lacking LAG and LEAD functions, getting the previous or next record is some work already. Here is how: ``` select thetime, (select max(thetime) from mytable afore where afore.thetime < mytable.thetime) as afore_time, (select min(thetime) from mytable after where after.thetime > mytable.thetime) as a...
Grouping Timestamps based on the interval between them
[ "", "sql", "session", "select", "group-by", "hive", "" ]
I have the following two tables Wishlist ``` id item created_by modified_by --------------------------------------- 1 Lips.. 5 6 ``` Users ``` id first_name ---------------- 5 Mark 6 Clare ``` I need to replace columns created\_by and modified\_by with the first\_name associate...
Join the user table twice, specify the exact columns you want and rename them accordingly: ``` SELECT wishlist.id, wishlist.item, u1.first_name AS created_by, u2.first_name AS modified_by FROM wishlist LEFT JOIN user AS u1 ON u1.id = wishlist.created_by LEFT JOIN user AS u2 ON u2.id = wishlist.modified_by ```
Try this: ``` SELECT w.id,w.item, u1.first_name as created_by , u2.first_name as modified_by FROM wishlist w LEFT JOIN user u1 ON u1.id = wishlist.created_by LEFT JOIN user u2 ON u2.id = wishlist.modified_by ```
Replace columns with SQL JOIN
[ "", "mysql", "sql", "join", "foreign-keys", "" ]
I have created a table empInfo as follow ``` CREATE TABLE empInfo ( empid INT(11) PRIMARY KEY AUTO_INCREMENT , firstname VARCHAR(255) DEFAULT NULL, lastname VARCHAR(255) DEFAULT NULL ) ``` Then I run below Insert statements :- ``` INSERT INTO empInfo VALUES(NULL , 'SHREE','PATIL'); INSERT INTO empInfo(firstn...
This [behaviour is by design](https://dba.stackexchange.com/a/60531/5489), viz inserting `0, NULL, or DEFAULT` into an `AUTO_INCREMENT` column will all trigger the `AUTO_INCREMENT` behaviour. ``` INSERT INTO empInfo VALUES(DEFAULT, 'SHREEKANT','JOHN'); INSERT INTO empInfo VALUES(NULL, 'SHREEKANT','JOHN'); INSERT INTO ...
As per the [documentation page](http://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html): > No value was specified for the AUTO\_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers. **If the column is declared NOT NU...
MySQL is not failing when deliberately inserting `NULL` in Primary Key AUTO_INCREMENT column
[ "", "mysql", "sql", "" ]
Is there any way to send a recursive query in SQL? Given the end node id, I need all the rows up to the root node (which has `parentid = NULL`) ordered by level. E.g. if I have something like: ``` nodeid | parentid a | NULL b | a c | b ``` after querying for `end_node_id = c`, I'd get somet...
Ended up with the following solutions (where level is the distance to the end node) Oracle, using [hierarchical queries](http://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm) (thanks to the info provided by @Mureinik): ``` SELECT IDCATEGORY, IDPARENTCATEGORY, LEVEL FROM TNODES START WITH IDC...
If you are using mssql 2005+ you can do this: **Test data:** ``` DECLARE @tbl TABLE(nodeId VARCHAR(10),parentid VARCHAR(10)) INSERT INTO @tbl VALUES ('a',null),('b','a'),('c','b') ``` **Query** ``` ;WITH CTE AS ( SELECT tbl.nodeId, tbl.parentid, 0 AS Depth FROM @tbl as tbl ...
Hierarchical SQL Queries: Best SQL query to obtain the whole branch of a tree from a [nodeid, parentid] pairs table given the end node id
[ "", "sql", "tree", "hierarchical-data", "recursive-query", "hierarchical-query", "" ]
On postgresql 9.3, I have a table with a little over a million records, the table was created as: ``` CREATE TABLE entradas ( id serial NOT NULL, uname text, contenido text, fecha date, hora time without time zone, fecha_hora timestamp with time zone, geom geometry(Point,4326), CONSTRAINT entradas_pkey PRIMARY...
You can simplify your query quite a bit: ``` SELECT x.t1, count(*) AS ct FROM generate_series('2014-12-02'::timestamp , '2014-12-03'::timestamp , '15 min'::interval) x(t1) LEFT JOIN entradas t ON t.fecha_hora >= x.t1 AND t.fecha_hora < x.t1 + interva...
**Analysis of the wrong estimate** The gist of the problem here is that the postgres planner has no idea what values and how many rows are coming out of the `generate_series` call, and yet has to estimate how much of them will satisfy the JOIN condition against the big `entradas` table. In your case, it fails big time...
Postgresql ignoring index on timestamp column even if query is faster using index
[ "", "sql", "postgresql", "postgresql-9.3", "postgresql-performance", "sql-execution-plan", "" ]
I have Table1 with Column1: ``` Column1| -------| 1 aaaa| 2 aaaa| 3 aaaa| 4 aaaa| 10 aaaa| 6 aaaa| 7 aaaa| 8 aaaa| 9 aaaa| 5 aaaa| ``` If I query: ``` Select * FROM Table1 Order By Column1 ``` The output is: ``` 1 aaaa 10 aaaa 2 aaaa 3 aaaa 4 aaaa 5 aaaa 6 aaaa 7 aaaa 8 aaaa 9 aaaa ``` What I...
try this: ``` Select * FROM Table1 Order By cast(SUBSTRING (Column1,1,charindex(' ',Column1)-1) as int) ``` Please check this [**DEMO**](http://sqlfiddle.com/#!3/3a311/9)
Got it: ``` SELECT C FROM Table_1 ORDER BY CAST(Left(Column1, CHARINDEX(' ', Column1)) AS int) ``` Thanks everyone
Order by with special condition
[ "", "sql", "sql-order-by", "" ]
In the below query condition is failing but logically it should pass. Is something wrong with to\_char?? ``` SELECT data FROM table1 WHERE TO_CHAR(TO_DATE(value1, 'DD/MM/RRRR HH24:MI:SS'), 'DD/MM/RRRR HH24:MI:SS') <= TO_CHAR( SYSDATE, 'DD/MM/RRRR HH24:MI:SS') AND TO_CHAR(TO_DATE(value2, 'DD/MM/RRRR HH24:MI:SS'), ...
Finally after lot of googling i got the solution. Below query is working for me :) :) SELECT MESSAGE FROM TABLE1 WHERE TO\_TIMESTAMP(value1, 'DD/MM/RRRR HH24:MI:SS') <= CAST(SYSDATE AS TIMESTAMP) AND TO\_TIMESTAMP(value2, 'DD/MM/RRRR HH24:MI:SS') >= CAST(SYSDATE AS TIMESTAMP); value1='02/07/2014 12:30:10' value2='06/...
Why are you comparing dates as strings? This also begs the question of why you would store dates as strings in the first place. You should store date/times using the built-in types. Try this instead: ``` SELECT data FROM table1 WHERE TO_DATE(value1, 'DD/MM/RRRR HH24:MI:SS') <= sysdate AND TO_DATE(value2, 'DD/MM...
TO_CHAR only considering dates while comparing two time stamps?
[ "", "sql", "oracle", "" ]
I am fairly new in Access and SQL programming. I am trying to do the following: ``` Sum(SO_SalesOrderPaymentHistoryLineT.Amount) AS [Sum Of PaymentPerYear] ``` and group by year even when there is no amount in some of the years. I would like to have these years listed as well for a report with charts. I'm not certain...
Thank you John for your help. I found a solution which works for me. It looks quiet different but I learned a lot out of it. If you are interested here is how it looks now. ``` SELECT DISTINCTROW Base_Customer_RevenueYearQ.SalesRep, Base_Customer_RevenueYearQ.CustomerId, Base_Customer_RevenueYearQ.Customer, Ba...
You need another table with all years listed -- you can create this on the fly or have one in the db... join from that. So if you had a table called alltheyears with a column called y that just listed the years then you could use code like this: ``` WITH minmax as ( select min(year(SO_SalesOrderPaymentHistoryLin...
Include missing years in Group By query
[ "", "sql", "sql-server", "missing-data", "" ]
I have three tables TableThreeItems, TableTwoItems and TableOneItems, I need to get the number of visits that Person had in each of these tables. I tried the following : ``` SELECT Person.[PersonId] , Count(TableOneItemId ) as TableOneItemCount , Count(TableTwoItemIdId ) as TableTwoItemCount , Count(TableThreeItemI...
You can do this in a single `join` by using `count(distinct)`: ``` SELECT Person.[PersonId], Count(distinct TableOneItemId ) as TableOneItemCount, Count(distinct TableTwoItemIdId ) as TableTwoItemCount, Count(distinct TableThreeItemId ) as TableThreeItemCount FROM [dbo].[Person] LEFT JOIN ...
Just add a `DISTINCT` to the count and you're done: ``` SELECT Person.[PersonId] , Count(DISTINCT TableOneItemId ) as TableOneItemCount , Count(DISTINCT TableTwoItemIdId ) as TableTwoItemCount , Count(DISTINCT TableThreeItemId ) as TableThreeItemCount FROM [dbo].[Person] LEFT JOIN TableOneItem ON TableOneItem.Pe...
Select count from multiple tabes
[ "", "sql", "" ]
I am working on sqlite 1st time I have need help on following problem I have 2 tables as follows # test1 --- key value a    1 b    2 c    3 e    7 f    41 j    52 # test2 --- key value a    null b    null c    null d    null e    null f    null g    null j    null I...
*(Assuming you mean conditional UPDATE, not INSERT)* Fortuitously, it seems you need to reset `test2` to null where the join fails, so you can do an update with the set specified as a subquery: ``` update test2 set value = (SELECT t1.value FROM test1 t1 where t1.key = test2.key LIMIT 1); ``` [SqlFiddle:](http://s...
Try this UPDATE test2 SET value = (SELECT test1.value FROM test1 WHERE test2.key =test1.key) ;
conditional UPDATE sqlite statement
[ "", "sql", "database", "sqlite", "" ]
This was an interview question. If I have a table like this: ``` ID FirstName LastName -- --------- -------- 1 Aaron Aames 2 Malcolm Middle 3 Zamon Zorr ``` How can I get output that looks like this? ``` Aaron Aames ...
Here is another way using a self-join. ``` CREATE TABLE temp (ID INT IDENTITY, FirstName VARCHAR(25), LastName VARCHAR(25)); INSERT INTO temp VALUES (N'Aaron', N'Aames'), (N'Malcolm', N'Middle'), (N'Zamon', N'Zorr'); WITH names(ID, Name, ColNum) AS( SELECT ID, FirstName, 1 FROM temp UNION ALL ...
You have really high reputation, so this isn't just a "they asked me at an interview" kind of question. There are several approaches. I think the one that I would take is a `union all`. Recognize that every other row is from the table. The rest are from joining one row to the next. So, that suggests: ``` select first...
How do you make a column value slide to the right or the left using SQL?
[ "", "sql", "sql-server", "" ]
I am trying to create SQL trigger which adds a new record to the same table where an insertion is made through a web page. I am not exactly sure how to implement it but I tried the following query ``` CREATE trigger [dbo].[trgI_DealsDoneInserRecord] on [dbo].[Terms] after insert As Insert into DealsDone ...
Try this: ``` CREATE trigger [dbo].[trgI_DealsDoneInserRecord] ON [dbo].[Terms] AFTER INSERT As BEGIN INSERT INTO DealsDone (Company,Grade,Term,Pipeline,[Index],Volume,Price,[Type],CounterParty, TermID,GradeID,CPID,Locked,Product) SELECT Company,Grade,Term,Pipeline,[Inde...
While I generally advocate *against* using `SELECT *`, in this case it seems like a benefit: * By not specifying the fields you can automatically account for changes in the tables without having to update this trigger if you add or remove or even rename fields. * This will help you catch errors in schema updates if on...
SQL trigger to add new records to a table with the same structure when an insertion is made
[ "", "sql", "sql-server", "t-sql", "triggers", "sql-server-2012", "" ]
Im new to Codeigniter and its developing. i have tested a query succefully. But when i try to take voteid value im getting errors please help me. ``` $query=$this->db->query("SELECT voteid FROM Questions WHERE questionid = '$questionid'"); echo $query->voteid; //im getting errors here. ``` Var\_dump value of...
``` $query=$this->db->query("SELECT * FROM Questions WHERE questionid = '$id'"); echo $query->row()->voteid; ``` try this it should work
Your query returns nothing because it's incorrect. Try: "SELECT voteid FROM Questions WHERE questionid = " . $questionid (I assume that $questionid is a variable of integer type)
take value after execute query
[ "", "sql", "codeigniter", "" ]
**Background** We recently had an issue with query plans sql server was using on one of our larger tables (around 175,000,000 rows). The column and index structure of the table has not changed for 5+ years. The table and indexes looks like this: ``` create table responses ( response_uuid uniqueidentifier not nul...
The reason is simple: the optimizer changes its mind on what the best plan is. This can be due to subtle changes in the distribution of the data (or other reasons, such as a type incompatibility in a `join` key). I wish there were a tool that not only gave the execution plan for a query but also showed thresholds for h...
This is one my most hated issues with SQL - I've had more than one failure due to this issue - once a query that had been working for months went from ~250ms to beyond the timeout threshold causing a manufacturing system to crash at 3am of course. Took awhile to isolate the query and stick it into SSMS and then start b...
Why did SQL Server suddenly decide to use such a terrible execution plan?
[ "", "sql", "sql-server", "performance", "" ]
I have the following SQL statement. It joins three tables: `Person`, `Deliverable`, and `DeliverableActions` ``` select p.first_name, p. last_name, d.title, da.type from Deliverable d right join Person p on d.person_responsible_id = p.id right join DeliverableAction da on da.DeliverableID = d.id w...
you can use `case based aggregation` or you can also use `pivot` ``` select p.first_name, p. last_name, d.title, sum(case when da.type = 1 then 1 else 0 end) as type_1, sum(case when da.type = 2 then 1 else 0 end) as type_2, sum(case when da.type = 3 then 1 else 0 end) as type_3, ...
``` select first_name, last_name, title, sum(case when type = 1 then 1 else 0 end) as type_1 from ( select p.first_name, p. last_name, d.title, da.type from Deliverable d right join Person p on d.person_responsible_id = p.id right join DeliverableAction da on da.DeliverableID = d.id where d.date_deadline >= @startDate...
SQL Server query to roll up data
[ "", "sql", "sql-server", "" ]
Lets say I have a simple query like: ``` SELECT A ,B FROM C ``` I will get this result: ``` A|B --- x|x ``` Without changing the select clause in the query (SELECT A, B), how can I receive a result as follows: ``` B|A --- x|x ``` ######## EDIT The reason I ask is because I want to do the following but...
Your revised query could be written: ``` SELECT DISTINCT A, B FROM RBase; ``` or ``` SELECT DISTINCT B, A FROM RBase; ```
You could use a subquery: ``` SELECT A, B FROM (SELECT B AS A, A AS B FROM C) AS sq; ``` Obviously the column names won't match but the column content would be swapped.
How To Switch Columns In SQL Results
[ "", "sql", "sql-server", "" ]
Hello I'm using MS JET OLEDB 4.0 on VBA (MS ACCESS) ``` SQL = "SELECT COUNT(Date) FROM [Orders] WHERE [Orders].[Date] BETWEEN " & "#" & StartDate & "#" & " AND " & "#" & EndDate & "#" ``` The [Date] is formatted like f dd/mm/yyyy (French) and the StartDate and EndDate are formatted like mm/dd/yyyy (Two date objects)....
Use [Format function](http://www.techonthenet.com/access/functions/date/format.php). ``` SQL = "SELECT COUNT(Date)" & vbcr & _ "FROM [Orders]" & vbcr & _ "WHERE [Orders].[Date] BETWEEN #Format(" & StartDate & "], 'MM/dd/yyyy')# AND #Format(" & EndDate & ",'MM/dd/yyyy')#" ```
Always use ISO date formatting YYYY-MM-DD and you will have no problems. Without formatting.
How to format date in a SQL query?
[ "", "sql", "vba", "" ]
I have two tables; `dbo.Users`: ``` user_id user_name gender has_phone -------------------------------------- 1 admin Male true 2 UserA Male false 3 UserB Female true ``` and `dbo.Filterby`: ``` id name filterid filtervalue ------------------------------...
You could do this by using `CROSS JOIN` ``` SELECT user_id, user_name, gender, has_phone FROM ( SELECT u.user_id,u.user_name, u.gender,u.has_phone, CASE ISNULL(f.filterid,'') WHEN '' THEN '-1' WHEN 'gender' THEN u.gender WHEN 'has_phone' THEN u.has_phone ...
In my experience using dynamic SQL is going to be the simplest way to do this. Take a look at the example below. Basically I think you would want to split this up using a variable and then some dynamic SQL. ``` DECLARE @Table_Name VARCHAR(1000) /*Would actually be an input parameter in our SP.*/ DECLARE @Statement ...
SELECT WHERE (column name is a result of another query)
[ "", "sql", "sql-server", "" ]
What I want to do is have a SQL join inside a table. Here is what it looks like: ### pie table ``` Id type message 1 2 'hello' 2 0 'bye' 3 2 'meh' ``` ### cake table ``` Id data pieId 1 70 1@2 2 6 2 3 8 1@3@2 ``` That is what the...
Looks like you need to update your database design I would get rid of the pieId from cake table and create a relationship table. Lets call it CakePies with Id, PieId, CakeId. Just add the relationship to that table The query would be ``` Select * from Cake c Inner join CakePies cp on c.Id = cp.CakeId inner join...
Take a look at this example for fnSplitString: <http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/> From there, try: ``` SELECT c.id, c.data, (SELECT message FROM pie WHERE pieid IN (SELECT * FROM fnSplitString(c.pieid, '@') ) AS 'mes...
SQL statement inside a table
[ "", "sql", "sql-server", "select", "join", "sql-like", "" ]
I have multiple tables in my database with different names but all have the same structure. Is there a way that I can change the structure to add a column to every table?
As David Faber suggested, you can accomplish this only in a loop. I have provided the code sample below to accomplish this. ``` private static final String ALTER_USER_TABLE_ColumnDetails = " ADD NEW_COLUMN_NAME TEXT"; @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVers...
**SQL inhericance.** (works in postgresql atleast) if all the tables inherit a base table, adding a column to the base table would add it to all the others. (after aquiring a lock on every table in the database) If your DBMs doesn't do this sort of sql inheritance, then i think "no": Get a list of tables and write a...
how to change structure of multiple tables at once in sql
[ "", "sql", "" ]
Is there a simple way to compare a list of numbers in my query to a column in a table to return the ones that are NOT in the db? I have a comma separated list of numbers (1,57, 888, 99, 76, 490, etc etc) that I need to compare to the number column in a table in my DB. SOME of those numbers are in the table, some are n...
I would put the list of numbers to be checked in a table of their own, then use `WHERE NOT EXISTS` to check whether they exist in the table to be queried. See this [SQLFiddle demo](http://sqlfiddle.com/#!2/645c5/4) for an example of how this might be accomplished: If you're comfortable with this syntax, you can even a...
May be this is what you are looking for. Convert your `CSV` to rows using `SUBSTRING_INDEX`. Use `NOT IN` operator to find the values which is not present in `DB` Then Convert the result back to `CSV` using `Group_Concat`. ``` select group_concat(value) from( SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.a, ',', n.n), ',...
mysql find numbers in query that are NOT in table
[ "", "mysql", "sql", "" ]
Currently my triggers for each table are like this for every field in a table: ``` ALTER TRIGGER [dbo].[trg_Statement] ON [dbo].[tbl_Statement] FOR INSERT, UPDATE, DELETE AS BEGIN SET NOCOUNT ON INSERT INTO tbl_ChangeLog(TableName, ID, FieldName, OldValue, NewValue) SELECT 'Statement', CU.id, 'i...
I agree with Madison, a single row in you AUDIT table that contains the entire record is going to be more useful and more performant. This becomes more true the wider the base table is. In your case: ``` CREATE TRIGGER IUD_Statement_Audit ON dbo.tbl_Statement AFTER INSERT, UPDATE, DELETE AS BEGIN IF (@@rowCount = 0...
I sometimes create an identical table to the table I want to log except I add a new identity primary key and a datetime field to track when the change occurred. Then whenever the original table changes, I insert into the tracking table the entire row that changed plus the current datetime. The pros to this are it is e...
More efficient way of logging changes in my table trigger
[ "", "sql", "sql-server", "database", "performance", "t-sql", "" ]
I have records from a specific table which contains fields: `phone1`, `phone2` . How can i change value of `057` in these fields to `053`, but only the beginning of the value? *For example:* `057-4353009` should change to `053-4353009`, but `057-5405731` should change to `053-5405731` (*the second `057` in this speci...
You have to implement two parts: 1. Checking if the phone number starts with the specific sequence (`WHERE phone LIKE '057%'`) 2. Getting the part after `057` and concatenate with the new one (`'053' + RIGHT(phone, LEN(phone) - 3)`) Here is the example query to do this: ``` UPDATE tbl SET phone = '053' + R...
You can use [**REPLACE**](http://msdn.microsoft.com/ru-ru/library/ms186862.aspx) : ``` UPDATE tbl SET phone = REPLACE(phone, '057-', '053-') ``` ### [SQLFiddle](http://sqlfiddle.com/#!3/9201bb/1) *Edit : In case you are not sure if the number has the structure with a delimiter like in **xxx–xxxxxxx**:* ``` UPDATE t...
How to change only the beginning of value that matches condition?
[ "", "sql", "sql-server", "replace", "" ]
I have this query ``` SELECT Client.ClientNo, Client.ContactName, Deal.Currency, MAX(Deal.DealDate) FROM Deal JOIN Client ON Deal.ClientNo = Client.ClientNo GROUP BY Client.ClientNo, Client.ContactName, Deal.Currency; ``` which gives me a result ``` 1 John ...
Untested, but should work. Will return several rows for a clieant if the client has two (or more) deals the same, latest day. ``` SELECT Client.ClientNo, Client.ContactName, Deal.Currency, Deal.DealDate FROM Deal JOIN Client ON Deal.ClientNo = Client.ClientNo WHER...
You could do something like this: **Test data:** ``` DECLARE @Deal TABLE(ClientNo INT,Currency VARCHAR(10),DealDate DATETIME) DECLARE @Client TABLE(ClientNo INT,ContactName VARCHAR(100)) INSERT INTO @Deal VALUES (1,'EUR','2014-10-07'),(1,'GBP','2014-11-12'),(2,'GBP','2014-09-17'), (2,'USD','2014-12-23'),(1,'USD','20...
SQL Server: aggregate to single result
[ "", "sql", "sql-server", "greatest-n-per-group", "" ]
I want to get the biggest ZIP code in DB. Normally I do this ``` SELECT * FROM ( Select * From tbuser ORDER BY zip DESC ) WHERE rownum = 1 ``` with this code I can get the biggest zip code value without a duplicate row (since zip code is not a primary key). But the main company at Japan said that I cant use it ...
> I want to get the biggest ZIP code in DB. If you really *only* want the zip code, try that: ``` SELECT MAX(zip) FROM TBUSER; ``` This will use the index on the `zip` column (if it exists). That being said, Oracle is usually smart enough to properly optimize sub-query selection using `ROWNUM`. Maybe your main comp...
This sounds to me like bad advice (masquerading as a rule) from a newbie data base administrator who doesn't understand what he's looking at. That insight isn't going to help you, though. Rarely does a conversation starting with "you're an obstructionist incompetent" achieve anything. So, here's the thing. First of al...
Selecting the biggest ZIP code from a column
[ "", "sql", "oracle", "greatest-n-per-group", "" ]
I have 2 table in my database that tables are in relationship with foreign key I want to select all records from main table and then select count of each row in another table than have same ID from main table I tried to create a select query but it is not work correctly this query return all records from main table + c...
``` SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc, COUNT(tblForumPosts_1.id) AS Expr1 FROM dbo.tblForumSubGroups AS tblForumSubGroups_1 INNER JOIN dbo.tblForumPosts AS tblForumPosts_1 ON tblForumSubGroups_1.id = tblForumPosts...
Do not mix sub-query and join logic. Use only one of them. I prefer sub-select. ``` SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc, (SELECT COUNT(*) FROM dbo.tblForumPosts WHERE dbo.tblForumSubG...
selecting records from main table and count of each row in another table
[ "", "sql", "sql-server", "" ]
One `Quiz` can have many `Submissions`. I want to fetch all `Quizzes` that have at least one associated `Submission` with `submissions.correct = t` and at least one associated `Submission` with `submissions.correct = f`. How can I fix the following query and the WHERE statement in particular to make that happen: ``` ...
The best solution depends on the details of your implementation, data distribution and requirements. **If** you have a typical installation with referential integrity (FK constraint) and defined `submissions.correct` as `boolean NOT NULL` and just want the `quiz_id` along with a count of total submissions, then you do...
``` -- I want to fetch all Quizzes SELECT * FROM quizzes q WHERE EXISTS ( -- that have at least one associated Submission with submissions.correct = t SELECT * FROM submissions s WHERE s.quiz_id = q.id AND s.correct = 't' ) AND EXISTS ( -- and at least one associated Submission with submissions.correct = f....
Postgres: Inner Join with AND condition on same field
[ "", "sql", "postgresql", "" ]
I've been working on a school management project. A teacher has multiple subjects, I need to display only one subject in query but I get all the subjects that a teacher has. Now I need only one record for Teacher 2 (TeacherId =2 has two subjects (English & Math) from the above screenshot's query. English or Math any of...
The easiest way would be to join just one subject per teacher in the first place. So join with an aggregate: ``` select t.teacherid, t.teachername, g.gender, t.dob, coalesce(s.subject, 'no subject') as subject, t.contact, t.address, t.email, t.photo from teacher t join gender g on g.genderid ...
Take your query add Row\_Number() statement as another column and put in the CTE your entire query ``` WITH CTE AS ( Select *,Row_Number()OVER(PARTITION BY SUBJECT ORDER BY 1 DESC)RN from Table ) Select * from CTE WHERE RN = 1 ``` OR TRY LIKE THIS ``` Select * from Dbo.Subject INNER JOIN (Select DISTINCT ISNULL(MAX...
How to get DISTINCT row from INNER JOIN Query in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have a table called post in which it has a column called title. I wanted to select all post which only have 1 word as the title. So for example 'cat' , 'dog' . There are posts which has more than one more such as 'cat and dog are not good', this I don't want to select. Only post with one word title only. How can I do...
``` SELECT * FROM post WHERE title NOT LIKE '% %' ``` Chooses rows where titles have no spaces. **EDIT:** > If a single word with a space in the end like `cat`, then? Then you smack your users with a tunafish for making silly inputs, and also your programmers for not trimming the inputs. Just kidding. If that is a...
If a single word with a space in the end like 'cat '. **Query** ``` CREATE TABLE tbl(title VARCHAR(250)); INSERT INTO tbl VALUES('cat '); INSERT INTO tbl VALUES('dog'); INSERT INTO tbl VALUES('cat and dog'); SELECT * FROM tbl WHERE TRIM(TRAILING ' ' FROM title) NOT LIKE '% %'; ``` **[Fiddle Demo 1](http://sqlfiddl...
select entries that has one word
[ "", "mysql", "sql", "" ]
``` INSERT INTO MonthlyFee(StudentID, ClassTypeID, Fee, MonthID, [Year], IsDefaulter, FeeStatus, CreatedDate) SELECT StudentID, ClassTypeID FROM ClassRollNo ``` I want to set the following values (mostly hardcoded parameters): MonthID 1, Year 2015, IsDefaulter FALSE, FeeStatus 0 and CreatedDate GETDATE().
Just hard code those values in same `select` statement in order of insert `column list`.Try this syntax ``` INSERT INTO MonthlyFee (StudentID, ClassTypeID, Fee, MonthID, [Year], IsDefaulter, FeeStatus, CreatedDate) S...
Use the same query and the values you described: ``` INSERT INTO MonthlyFee(StudentID, ClassTypeID,Fee,MonthID, [Year],IsDefaulter,FeeStatus,CreatedDate) SELECT StudentID, ClassTypeID, 0, 1, 2015, 0, 0, GETDATE() FROM ClassRollNo ```
Insert Data from multiple tables into a single table
[ "", "sql", "sql-server", "join", "subquery", "" ]
Why do we need to use query `SELECT COLUMN1, COLUMN2` when we can just use `SELECT *` and only show the columns we want? And what's the difference between `SELECT ALL` and `SELECT`?
The question is, why would one use `SELECT col1, col2` when you can easily just show what columns you like in the application and always use `SELECT *`? The main reasons are these: 1. Selecting only the columns you want means that the server has to gather and send less data to the application, making for a faster que...
There are a lot of questions posted before comparing differences of `SELECT Col1, Col2` vs `SELECT *` You can find some of them here. [Which is faster/best? SELECT \* or SELECT column1, colum2, column3, etc](https://stackoverflow.com/questions/65512/which-is-faster-best-select-or-select-column1-colum2-column3-etc) [...
SELECT COLUMN SQL
[ "", "mysql", "sql", "" ]
while studying, im struggling to find an answer to this question: What is a generic datamodel? Are there any alternatives to a generic datamodel, if so; which one would you recommend? I've looked everywhere to find a decent answer, but i didn't find it. It might be just a very simple question, i just couldn't find t...
Perhaps by generic data model you mean an entity attribute value model: [EAV on wikipedia](http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model) This data model has one table and three columns. It is usually burnt by fire if ever discovered by someone of a database (vs developer) persuasion. The ...
It could be possible its an EAV mode. But that leaves me with the following question: are there any alternatives to this model? Thanks.
SQL - Alternatives to a generic datamodel
[ "", "sql", "database", "generics", "datamodel", "" ]
I am using SQL Server. I have two date filters using those fields as show below in query. ``` SELECT * FROM student WHERE Dateofbirth >= '2014-10-03' AND Dateofbirth <= '2014-10-03' ``` While using this same date no result get listed. If I change the date to ``` SELECT * FROM student WHERE Dateofbirt...
Looking at the issue Dateofbirth is probably a datetime column. A datetime column has both a date part and time part.So, your query with date alone will translate as ``` SELECT * FROM student WHERE Dateofbirth >= '2014-10-03 00:00:00.000' AND Dateofbirth <= '2014-10-03 00:00:00.000' ``` So, to get the entire day the...
``` SELECT * FROM student WHERE Dateofbirth >= '2014-10-03' AND Dateofbirth <= '2014-10-03' ``` This means show only data which have only `2014-10-03` value. There is hour is also in your date, and your date string is without hour,minute, second. So in compare it will not get. The problem will solved by type casting ...
SQL Server : where with same date
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I need to convert a SQL column which is in `varchar` datatype to `decimal` and the null values to 0. This is my code to convert `varchar` to `decimal`: ``` SELECT CAST(debit as DECIMAL(9,2)), CAST(credit as DECIMAL(9,2)), sum_accname, sum_date, sum_description FROM sum_balance ``` I need to...
``` SELECT COALESCE(CAST(debit as DECIMAL(9,2)),0) as debit, COALESCE(CAST(credit as DECIMAL(9,2)),0) as credit, sum_accname, sum_date, sum_description FROM sum_balance ```
Use [**COALESCE**](http://msdn.microsoft.com/en-us/library/ms190349(v=sql.105).aspx) function to fetch NOT NULL values. Try this: ``` SELECT CAST(COALESCE(debit, '0') AS DECIMAL(9,2)), CAST(COALESCE(credit, '0') AS DECIMAL(9,2)), sum_accname, sum_date, sum_description FROM sum_balance; ```
How to convert SQL column null value to 0 and varchar to decimal in sql query
[ "", "sql", "sql-server", "select", "sql-server-2008-r2", "crystal-reports", "" ]
I am using SQL Server 2012. I have a simple query, ``` select * from P_Bld where datep = (select max(datep) from P_Bld) and codeBlood like 'nm_%' order by codeBlood ``` This works fine and returns the data as shown below ``` codeBlood num nm_aab 1 nm_abc 2 nm_rst 3 ``` I was wondering if i...
I think this will do, First replace "nm\_" by blank using `Replace()` function & then convert remaining string to Uppercase bu `Upper()` function ``` select Upper(Replace(codeBlood,'nm_','')) as codeBlood,num from P_Bld where datep = (select max(datep) from P_Bld) and codeBlood like 'nm_%' order by codeBlood ```
If the pattern is same, try this ``` select Upper(substring(codeBlood,4,length(CodeBllod))),num from P_Bld where datep = (select max(datep) from P_Bld) and codeBlood like 'rf_%' order by codeBlood ```
query and formatting string at the same time
[ "", "sql", "sql-server", "" ]
I'm a newbie to SQL (Server) and the following question is really making me clueless. ``` ID Order Type ===================== 26 Automatic Orders 26 Backend Orders 41 Automatic Orders 58 Automatic Orders 86 Automatic Orders 86 Automatic Orders 86 Automatic Orders 111 Automat...
Not sure this is exactly what you need, but It can guide you to the solution. If I understood correctly, You want the hotel in which the difference between the automatic and backend orders is the highest? If so, this may help. Assuming such table exists, and is populated with the values you provided: ``` CREATE TAB...
If I understand your question correctly, you want Hotels with more `Automatic Orders` than `Backend Orders`. You can use `SUM` and `HAVING` function for this. ``` SELECT ID FROM temp GROUP BY ID HAVING SUM(CASE WHEN [Order Type] = 'Automatic Orders' THEN 1 ELSE 0 END) > SUM(CASE WHEN [Order Type] = 'Backe...
SQL Query to find the ID with highest difference of contents
[ "", "sql", "sql-server", "" ]
Here is my query: ``` IF EXISTS(%some query%) BEGIN BEGIN TRY ALTER DATABASE [MyDatabase] SET single_user WITH ROLLBACK IMMEDIATE; --do something --throw some exception END TRY BEGIN CATCH --here I want to set database back to multi_user RAISERROR ('DBErr...
It's been a while, but I believe the `with rollback immediate` option is there to say you want this to succeed no matter what. the normal behavior blocks until all running transactions have completed successfully. Also, setting the database to multi-user mode when it's already multi-user is safe. However, if you want...
What happens if you simply put ``` ALTER DATABASE [MyDatabase] SET MULTI_USER ``` after the CATCH ? It shouldn't find any active user since you are in single user from your program/stored procedure? Also, have you tried putting everything in a transaction, using ROLLBACK in the CATCH block?
How do I go back to multi_user mode
[ "", "sql", "sql-server", "t-sql", "multi-user", "single-user", "" ]
I have datetime column value below ``` 2015-01-04 20:37:00.000 ``` I tried below ``` cast(cast(MyDateColumn as date) as datetime)+cast(datepart(hour,MyDateColumn ) as float)/24 as MyDateColumn ``` and ``` CAST(CONVERT(CHAR(16),MyDateColumn,113) AS datetime) as MyDateColumn ``` These are did not work for me How c...
In SQL Server this will work: ``` DECLARE @now [datetime]; SET @now = GETDATE(); SELECT CONVERT([varchar](10), @now, 105) + ' ' + RIGHT('0' + CONVERT([varchar](2), DATEPART(HOUR, @now)), 2) + ':' + RIGHT('0' + CONVERT([varchar](2), DATEPART(MINUTE, @now)), 2); ```
Since MS SQL 2012, you can use [`FORMAT`](http://msdn.microsoft.com/en-GB/library/hh213505.aspx), ``` SELECT FORMAT([MyDateColumn], 'dd-MM.yyyy HH:mm') ```
Sql Server select datetime without seconds
[ "", "sql", "sql-server", "datetime", "" ]
I have table person ``` create table Person ( id SERIAL not null, ... ); ``` person can have 0 or more PreviousName ``` create table PreviousName ( id SERIAL not null, person_id INTEGER not null, value VARCHAR(120) ); ``` how can I select all person who has for example value in previous...
``` select * from Person where id in (select person_id from PREDCHOZI_JM_PR where value = 'John') ```
You can find distinct person\_id from PREDCHOZI\_JM\_PR with value containing john: ``` SELECT * FROM Person WHERE id IN (SELECT DISTINCT person_id FROM PREDCHOZI_JM_PR WHERE value LIKE '%John%') ```
How to select person depending on one to many relationship
[ "", "sql", "postgresql", "" ]
I have written a stored procedure as ``` Declare @Split table ( Jurisdiction nvarchar(max) ) Insert into @Split select Jurisdiction from tbLicence where AgentId =@AgentId; Select * from @Split; Declare @products varchar(MAX); Select @products = Jurisdiction from @Split; Select @products; ``` I want to put all t...
First Initialize the variable with `empty string`. Then append all the rows using any delimiter. Use this. ``` DECLARE @products VARCHAR(MAX)=''; SELECT @products += Isnull(Jurisdiction, '') + ',' FROM @Split; SELECT left(@products,len(@products)-1); ``` or Use `For XML path()` ``` set @products=(select ','+Juri...
This might helps you ``` Declare @Split table( Jurisdiction nvarchar(max)) Declare @products varchar(MAX)='' declare @count int=(select count(*) from @split) declare @a int=1 Insert into @Split values ('a'),('b') while(@a<@count) begin Select @products += Jurisdiction from @Split set @a=@a+1 end select @...
How to put all rows in a column to a variable?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a table (tran) with the following values: ``` Set Type Acc Type Tran Value ---- ----- ---------- ---------- ------------------- ----------- 1 BS 87411 CCHQ Other Transactions -200 1 BS 87411 RECPT Other Transactions 200 1 BS 87411 ...
This is one of the things you can do, I'm afraid there's no getting away from a DELETE statement.. as you won't be able to overwrite your existing data by having a unique row with a summed up value without deleting it. ``` BEGIN TRANSACTION SELECT ROW_NUMBER() OVER (ORDER BY Type2) AS UniqueID, * ...
You can't do it this way. Try this instead: ``` update a set a.Value = t.Total from tran a INNER JOIN ( SELECT TranType, SUM(Value) Total FROM tran GROUP BY TranType ) AS t ON a.TranType = t.TranType ```
Update a table in SQL server (without output from select)
[ "", "sql", "sql-server", "t-sql", "" ]
I am using MySQL to solve this problem. I need to give points to a user based on the total time spent by him on a question. I have calculated the time spent by the user. Let's say it is in **user\_time** table. ``` user_id question_id time_spent 1 1 7 1 2 50 2 ...
I think the easiest approach is a correlated subquery. Something like this: ``` select ut.*, (select pt.points from points_table pt where pt.time_spent <= ut.time_spent order by pt.time_spent desc limit 1 ) as points from user_time ut ```
For another take on this, you could achieve the same result without having the points table: ``` SELECT *, CASE WHEN time_spent >= 30 THEN 1000 WHEN time_spent >= 20 THEN 500 WHEN time_spent >= 10 THEN 300 ELSE 100 END 'Points' FROM user_time; ```
MySQL: Range based on rows in external table
[ "", "mysql", "sql", "select", "join", "" ]
I've done a lot of googling as to what JSON is, and how it is used on the web. I understand that it is a way of storing data using Javascript object notation, and that it is a lightweight way to store data and is therefore preferable to XML. However, I don't quite understand exactly how XML and JSON are used to transm...
XML and JSON are *serialisation formats*. They're plain text formats which allow you to express more than plain text. JSON can express complex nested hierarchies of arrays and key-value objects, XML can express even more complex object-attribute-value-content hierarchies. Both data formats simply allow you to send more...
SQL is used to store data. XML and JSON are human readable, text based, data transport protocols. Typically a request is made either via HTTP or AJAX. The App that receives the request retrieves the data from an SQL database. The requested data is formatted into XML or JSON then transmitted to the requester as th...
How are XML and JSON used in conjunction with SQL?
[ "", "sql", "ajax", "xml", "json", "" ]
I have simple query like ``` SELECT * FROM temp t WHERE t.id IN (:IDs) ``` When executed, it prompts me (Oracle SQL Developer) for entering value if IDs variable. When I enter for example 169, everything runs smoothly, but when I try to enter multiple IDs, like 169,170,171, I get error Invalid Number even while putt...
The problem is the `varying-IN list`. In `SQL Developer`, when you are prompted to enter the value for the bind variable, you are simple passing it as `169,170,171` which it is not considering as a `set of values`. What you could do is, have multiple binds - `SELECT * FROM temp t WHERE t.id IN (:ID1, :ID2)` When pro...
If you put them into ", you get error. Oracle doesn't accept ". You should use just numbers without ". i.e: (169,170,171,...)
ORACLE substitute variable in IN statement
[ "", "sql", "oracle", "" ]
I cant seem to get this query to run, it keeps telling me "Msg 102, Level 15, State 1, Line 5 Incorrect syntax near '='." Not sure what i doing wrong here. Basically i need [forwarder\_preferred\_status] to be P2 or P3 depending on the value of [forwarder\_short] Any Suggestions would be welcome ``` Select ...
The code in your question is structured like this: ``` --Bad CASE A WHEN X THEN A = B WHEN Y THEN A = C ... END ``` Instead, you need to structure it like this: ``` --Good A = CASE WHEN X THEN B WHEN Y THEN C ... END ``` or like this: ``` --Good CASE WHEN X THEN B WHEN Y...
I bet this isn't the first time someone has needed to translate ABL to a P2 for a report and it won't be the last. As @Aaron pointed out, stop with these horrible case statements and tabularize it. For the sake of this answer, I am using a table variable. These generally are not advisable as the database engine doesn'...
Sql When A = Z then set B = X
[ "", "sql", "sql-server", "where-clause", "" ]
I am completely new to sql (have couple of days to get to know it) and have following question: Here is a syntax for constraints: While creating the table, I have this kind of line: ``` CONSTRAINT smth UNIQUE(name) ``` I understand that it puts constraint on column `name` for it to be unique but what is `smth` for?...
You name it (as with many things) so that you can perform *maintenance* in your database easily. See [ALTER TABLE ... DROP CONSTRAINT](http://www.postgresql.org/docs/9.1/static/sql-altertable.html) and note that you have to supply the *name* of the constraint there. Also, it's helpful if the constraint is [*violated*...
Constraints have names. It is useful. Just imagine: * when you need to drop a constraint * when you list constraints on a object * when a constraint fails, it will show name in error message.
Concerning Constraints
[ "", "sql", "postgresql", "" ]
I have a table that looks roughly like this ``` Year Species Count 1979 A 0 1980 A 10 1981 A 4 1982 A 3 1979 B 0 1980 B 1 1981 B 2 1982 B 3 1979 C 9 1980 C 14 1981 C 2 1982 C 1 ``` ...
This is the easiesy. You already have the counts. Group on species and filter table on the results of the subquesy. You can get the same functionality with an exists or a join also. ``` SELECT [YEAR] ,SPECIES ,[COUNT] FROM TABLE WHERE SPECIES IN ( SELECT SPECIES FROM TABLE GROUP BY SPECIES ...
In MySQL, you can do this using aggregation and a `join`: ``` select t.* from table t join (select species, count(*) as cnt from table group by species ) s on t.species = s.species where s.cnt >= 10; ```
Using a sum of values as a condition (SQL query)
[ "", "mysql", "sql", "" ]
could use some SQL help in Oracle 11G. I'm trying to create a result set that takes a current transaction, finds the most recent related transaction, shows the current price along with the previous price, and then calculates the difference. Assume each item can only have one price for a given month. If there's no earl...
You should be able to use [Lag analytical function](http://www.techonthenet.com/oracle/functions/lag.php) to get that. The query will look like below. ``` SELECT Item, Location, Department, MonthEnd, Price, COALESCE(LAG (MonthEnd, 1) OVER (ORDER BY MonthEnd), MonthEnd) PrevMonthEnd,...
Use Analytic Function to generate `row_number` and `Left join` the result .Try this. ``` WITH cte AS (SELECT *,Row_number()OVER (ORDER BY MonthEnd DESC) rn FROM yourtable) SELECT a.Item, a.Location, a.Department, a.MonthEnd, a.Price, COALESCE(( a.Price - b.Price ), a...
SQL select current transaction and reference most recent transaction
[ "", "sql", "oracle", "oracle11g", "analytics", "" ]
I have a string and want to get the first n characters of this string but ends with a whole word. ``` DECLARE @text VARCHAR(MAX) = '123 4056 78789 abcdefg 2222222222 3333 444 55555' ,@length INT = 23 ``` I have written this query so far: ``` REVERSE(STUFF(REVERSE(LEFT(@text, @length)), 1, CHARINDEX(' ',REVER...
If I understand your requirements correctly, I think you want the following: ``` WITH x AS ( SELECT '123 4056 78789 abcdefg 2222222222 3333 444 55555' AS [text], 22 AS [length] ) SELECT LEFT([text], LEN([text]) - CHARINDEX(' ', REVERSE([text]), LEN([text]) - [length])) FROM x; ``` (I put everything into the `WI...
I think I understand your requirements. What you need to do is to find the first space after the length, then return all the characters up until that point. Try this: ``` SELECT LEFT(@text + ' ',CHARINDEX(' ',@text,@length)) ```
How to get the first n characters of a string but ending with a whole word
[ "", "sql", "sql-server", "string", "t-sql", "sql-server-2008-r2", "" ]
I have a huge table with many columns and I know that this columns sometimes takes some specific value 'MyValue'. How can I select all the rows in that one specific table containing 'MyValue' regardless in which column. I found related topic here: [How do I find a value anywhere in a SQL Server Database?](https://stac...
To do it without a special procedure in a simple statement, you could convert each row to XML and then use an XQuery on the XML to search for any value in the row that matches. So for example: ``` declare @SearchValue as varchar(20) set @SearchValue = 'MyValue' select * --,(select MyTable.* for XML PATH (''),TYPE...
You can do this by reversing the value and column in `In` operator. ``` SELECT * FROM Mytable WHERE 'Myvalue' IN ( Col1, Col2, col3,.... ) ``` If you don't want to type the columns, then pull it from `information_schema.column` view and create a `dynamic query`
SQL search all columns of a table for text value
[ "", "sql", "sql-server", "search", "select", "text", "" ]
How to do something like this... ``` alter table customer_schedule add (week_number as (TO_CHAR((SCHEDULE_DATE),'iw')) ``` Wherein SCHEDULE\_DATE is one of the existing columns in table
This is where you need **VIRTUAL COLUMN**. If you are on 11g and up, you could certainly do - ``` alter table table_name add (column_name [data_type] [generated always] as (column_expression) [virtual]); ``` In your case, it will be something like - ``` alter table customer_schedule add (week_number data_type genera...
On 9i, you cannot use *virtual columns*, so I'd probably go with a view: ``` create view customer_schedule_view as select c.*, to_char(c.schedule_date, 'iw')) week_number from customer_schedule c; ``` Of course, in your forms you need then to select from the view rather from the table.
Alter table add column as select statement
[ "", "sql", "database", "oracle", "oracle9i", "" ]
I have a function that returns the following: ``` Title Start End Task A 2015-01-02 2015-03-31 Task B 2015-02-12 2015-04-01 Task C 2014-11-01 2015-02-05 .... ``` I want to return a column for each month and 1 if its within the Start and End period 0 otherwise ``` Title Start ...
You would do this with basic `case` statements: ``` select title, start, end, (case when 1 between month(start) and month(end) then 1 else 0 end) as jan, (case when 2 between month(start) and month(end) then 1 else 0 end) as feb, . . . (case when 12 between month(start) and month(end) then ...
If you only wanted to check 1 date, this would work. You should be able to adapt this sample to meet your needs. ``` SELECT c.CreateDateUTC, DATEPART(MONTH, c.CreateDateUTC) 'MONTH', CASE DATEPART(MONTH, c.CreateDateUTC) WHEN 1 THEN 1 END 'JAN', CASE DATEPART(MONTH, c.CreateDateUTC) WHEN 2 THEN 1 ...
Get months between two dates in TSQL
[ "", "sql", "sql-server", "t-sql", "date", "datetime", "" ]
I am having following values in database table : ``` 12.00 15.00 18.00 20.00 ``` I want to remove all decimal ZEROS from all values , So how can I do this using SQL query. I tried replace query but that is not working. I want values like : ``` 12 15 18 20 ``` My replace query : ``` select height(replace (1...
Since all your values end with ".00", there will be no rounding issues, this will work ``` SELECT CAST(columnname AS INT) AS columnname from tablename ``` to update ``` UPDATE tablename SET columnname = CAST(columnname AS INT) WHERE ..... ```
Here column name must be decimal. ``` select CAST(columnname AS decimal(38,0)) from table ```
Remove decimal values using SQL query
[ "", "sql", "sql-server", "" ]
I have a query like this: ``` (SELECT * FROM something WHERE ...) UNION (SELECT * FROM something WHERE ...) ``` Because I want the results from the first `SELECT` to come out on top. But, the second part comes out in reverse order. I can't simply order the entire query because it will push the first `SELECT` that I n...
``` SELECT * FROM something WHERE ... UNION SELECT * FROM (SELECT * FROM something WHERE ... ORDER BY timestamp DESC)a ```
If you want the first table to come first, then you need to order by that explicitly: ``` SELECT s.* FROM ((SELECT s.*, 1 as which FROM something s WHERE ...) UNION ALL (SELECT s.*, 2 as which FROM something s WHERE ...) ) s ORDER BY which, timestamp DESC ``` You can only trust an `order by` in the o...
MySQL: can't order one side of a union
[ "", "mysql", "sql", "" ]
Thank you in advance for taking the time to look at this. I am looking to take a number of records containing a date field and split them into hour columns with a count in each (sql server). E.g. ``` SpecialDateColumn 14/1/15 10:23 14/1/15 11:34 14/1/15 12:45 14/1/15 12:55 ``` I'm looking the ...
You can do this : ``` SELECT * FROM ( SELECT SpecialDateColumn AS [Date] ,DATEPART(HOUR, SpecialDateColumn) [Hour] FROM < TABLE > ) AL1 PIVOT(COUNT([Hour]) FOR [Hour] IN ( [0] ,[1] ,[2] ,[3] ,[4] ,[5] ,[6] ,[7] ,[8] ,[9] ,[10] ...
It is simple enough to write this as conditional aggregation: ``` select cast(SpecialDateColumn as date) as thedate, sum(case when datepart(hour, SpecialDateColumn) = 10 then 1 else 0 end) as hour_10, sum(case when datepart(hour, SpecialDateColumn) = 11 then 1 else 0 end) as hour_11, sum(case when...
Split date column into hour segments
[ "", "sql", "sql-server", "date", "" ]
I found this related answer useful: * [Export "Create Aggregate" functions from PostgreSQL](https://stackoverflow.com/questions/15112971/export-create-aggregate-functions-from-postgresql) But how do I get the `CREATE AGGREGATE` statement without a GUI client (e.g. with psql command line)?
Something like this, but I'm not sure if this covers all possible ways of creating an aggregate (it definitely does not take the need for quoted identifiers into account) ``` SELECT 'create aggregate '||n.nspname||'.'||p.proname||'('||format_type(a.aggtranstype, null)||') (sfunc = '||a.aggtransfn ||', stype = '...
A modern version to generate the `CREATE AGGREGATE` statement - using `format()` and casts to object identifier types to make it simple and add double-quotes and schema-qualification to identifiers where required automatically: ``` SELECT format('CREATE AGGREGATE %s (SFUNC = %s, STYPE = %s%s%s%s%s)' , aggf...
How to get definition/source code of an aggregate in PostgreSQL?
[ "", "sql", "postgresql", "aggregate-functions", "psql", "ddl", "" ]
Is it possible to retrieve the maximum value of a key column, increase it and insert it as a new value in the database, like this (pseudo-sql) ``` insert into mytable (mykeycolumn,col1,col2) values((max(mykeycolumn)+1),'val1','val2'); ```
Yes, you `INSERT` from a `SELECT`, but your fixed fields must "come from the `SELECT`" as well, like such: ``` INSERT INTO mytable (mykeycolumn, col1, col2) SELECT MAX(mykeycolumn)+1, 'val1', 'val2' FROM mytable; ``` --- **Complementing:** as [a\_horse\_with\_no\_name](https://stackoverflow.com/users/330315/...
You can with this: ``` INSERT INTO mytable (mykeycolumn,col1,col2) VALUES ((SELECT MAX(mykeycolumn) FROM mytable AS foo)+1,'val1','val2'); ```
max value of no autonincrement column in update query
[ "", "mysql", "sql", "" ]
I have a table with a column 'Name', like the following: ``` Name Michael Jackson Chester Bennington Mike Shinoda ``` I want to split the 'Name' values in FirstName and LastName,blike this: ``` LastName FirstName Jackson Michael Bennington Chester Shinoda Mike ``` And also I nee...
Try this ``` UPDATE data SET FirstName = SUBSTRING_INDEX(Name, ' ', 1), LastName = SUBSTRING(SUBSTRING_INDEX(Name, ' ', 2), LENGTH(SUBSTRING_INDEX(Name, ' ', 1)) + 1) ``` **EDIT** As David Faber stated, one can use `SUBSTRING_INDEX(Name, ' ', -1)` for updating the `LastName` column.
You might try this: ``` ALTER TABLE `data` ADD `FirstName` VARCHAR(30) , ADD `LastName` VARCHAR(30); UPDATE `data` SET `FirstName` = SUBSTR( `Name`, 1, INSTR(`Name`, ' ') - 1 ) , `LastName` = SUBSTR( `Name`, INSTR(`Name`, ' ') + 1, LENGTH(`Name`) - INSTR(`Name`, ' ') ) WHERE `Name` LIKE '% %...
Adding a new column,splitting a column value in two then insert a part of the value in the new column
[ "", "mysql", "sql", "split", "" ]
I am using following query on postgres database: ``` insert into user_settings (google_access_token, google_refresh_token) select 'google_access_token', 'google_refresh_token' from user where id = user_id ``` table user\_settings has a field `user_id` which corresponds to field named `id` in user table. but t...
you are taking a column in user\_settings and inserting into that table with condition. I think you have to use update statement because your condition is user .id = user\_settings .user\_id
You can update a table with out NULLs even if you don't have matching values ``` update user_settings set user_settings.google_access_token='google_access_token', user_settings.google_refresh_token='google_refresh_token' from user_settings inner join user on user_settings.user_id=user.id ```
Sql Insert with dynamic values
[ "", "sql", "postgresql", "" ]
I don't use SQL everyday so bear with me ... I need to find out if the date has passed a certain month and day period. If this is not clear let me give you an example: Ex: Given a date: 2012/02/08 (2012 Feb 08) determine if it is after 07/01 (Jul 01) in this case NO. I need some kind of generic query to check if any ...
``` select table.column from table where DATEPART(mm,table.column)>=7 and DATEPART(DD,table.column)>=1 ```
Here is a simple script that lets you do the test. The important part is the conditional in the case statement. Use that where you need to do the test. ``` declare @date datetime set @date = '2/8/2012' select case when @date > cast('7/1/' + cast(year(@date) as varchar(10)) as datetime) then 'yes' else 'no...
Microsoft SQL given ANY DATE find out if AFTER specific month and day
[ "", "jquery", "sql", "sql-server-2008", "" ]
I know this is possible through some complex techniques, i want to know any simplest way to achieve this patter that every 10 rows should repeat . for example ``` select a,b from tablename; (repeating 2 for example) ``` will give ``` a1,b1 a2,b2 a1,b1 a2.b2 a3,b...
You want blocks of ten rows repeated twice. So to get: ``` rows 1 to 10 rows 1 to 10 rows 11 to 20 rows 11 to 20 ... ``` In order to get rows n-fold cross join with a table holding n records. (You get such for instance by querying a big enough table and stop at rowcount n.) You also need the row number of your origi...
Use a CTE and union all: ``` with rows as ( select a, b from tablename where rownum <= 2 ) select * from rows union all select * from rows; ``` Just some caveats to this. You should use an `order by` if you want particular rows from the table. This is important, because the same select can retu...
Simplest way to repeat every N rows in sql
[ "", "sql", "oracle", "" ]
**(The database is Postgres )** Let's say I have a table races with `columns` `(user_name , race_time , race_speed , race_no).` Each users can have multiple races . I want to get data for each month and show for each month how many races are played in that month. ***But I also want to show which user played the most ...
[SQL Fiddle](http://sqlfiddle.com/#!15/c9d86/1) ``` with r as ( select to_char(race_time, 'YYYY-MM') as month, user_name, count(*) as n_races, max(race_speed) as max_speed from races group by 1, 2 ), total_races as ( select sum(n_races) as total_races, month from r ...
``` SELECT COUNT(DISTINCT user_name), user_name, EXTRACT(month FROM race_time) AS month, EXTRACT(year FROM race_time) AS year FROM races r GROUP BY user_name, year, month ORDER BY year desc, month desc ```
Getting data for a user in a month
[ "", "sql", "postgresql", "select", "group-by", "" ]
Can I transform the following insertion in a way that it can handle case where the subquery returns more than 1 row? Only the first value is needed. ``` insert into mytable (column1,column2) values ('value1', select value from mytable2 where columnX='ABC') ``` --- Any idea to get this in oracle as well?
In Oracle you can use a scalar sub-query with the insert...values syntax. For your example you would need to define "first value" and then write a query that only returns that. If it is the minimum value: ``` insert into mytable (column1,column2) values (9, (select min(value) from mytable2 where columnX = 'ABC')); ``...
Either use `INSERT ..VALUES` syntax or `INSERT ..SELECT`, not both ``` insert into mytable (column1,column2) select 'value1',value from mytable2 where columnX='ABC' ```
subquery - #1242 - Subquery returns more than 1 row
[ "", "mysql", "sql", "oracle", "" ]
I have three tables ``` orders.orderid (and other non-pertinent stuff) payment.orderid payment.transactiondate payment.amount projectedpayment.orderid projectedpayment.projecteddate projectedpayment.projectedamount ``` Essentially, `payment` represents when actual payments are received; `projectedpayment` represent...
I dont know postgres sorry :( but if you know how to do partitioned row numbers something like this should work. ``` select coalesce(a.orderid,b.orderid) as orderid ,transactiondate ,amount ,projecteddate ,projectedamount FROM (select orderid ,ransactiondate ...
This should work ``` Select * from Orders o Left Join Payments p on o.ID = p.OrderID Left Join ProjectedPaymentp pp on o.ID = pp.OrderID Order By o.ID ```
Query two similar tables and combine sorted results
[ "", "sql", "postgresql", "union", "" ]
If I open a connection to a database, for example, with SSMS, and I run a query like this: ``` SELECT * FROM MySchema.MyTable ``` the query is executed without error. If I run it as dynamic sql like this ``` declare var @qry nvarchar(200); set @qry = N'SELECT * FROM MySchema.MyTable' exec master.sys.sp_executesql @...
Both answers by Recursive and koushik veldanda work fine, but this gives a deeper insight to the problem: The problem is that executing a query with ``` exec master.sys.sp_execute_sql @qry ``` changes the context to the `master` database, so `MySchema.MyTable` is not accesible, because it doesn't belong to `master`,...
try this! change this ``` exec master.sys.sp_executesql @qry ``` to ``` exec sp_executesql @qry ``` or ``` exec @qry ```
Table doesn't exist error when execuitng dynamic sql with sp_executesql
[ "", "sql", "sql-server", "t-sql", "" ]
I have problem on my Database, I try simplify my database.. after a lot of tries the function use 'X' table , then use the function on 'X' table.you can not use function use same table... --after create table: ``` create table Items( ID int, Price money ); ``` --Insert some values ``` insert into Items Values(1,4);...
The problem you have is that the new value exists in the table (inside an implicit transaction) when the check constraint fires, so when you insert 15, the max(Price) *is* 15, so the constraint is satisfied, and the INSERT succeeds. I've had a thorough Google to try and find where this is documented but not found anyth...
Try with this code. It is working fine for me. ``` CREATE TABLE item ( ID INT, Price MONEY ); --Insert some values INSERT INTO item VALUES (1, 4); INSERT INTO item VALUES (2, 5); --create a function use above table CREATE FUNCTION GetMax (@price MONEY) RETURNS MO...
function do not work in CHECK Constraint on sql server
[ "", "sql", "sql-server", "database", "function", "" ]
I want to use a prefix for the city column too (ie: l.city) in the main select statement just like in the inner select sub query statement for a more "understanding" and a better looking way so to speak but i can't because it gives me ORA-00904: "L"."CITY": invalid identifier, using only city without identifier works, ...
Your `"L"` alias resides inside the view and is therefore not visible at the place where you want to use it. Try this: ``` SELECT d.department_name, x.city FROM departments d NATURAL JOIN (SELECT l.location_id,l.city,l.country_id FROM locations l // <-- "l" has no scope outside brack...
Just give your subquery an alias or remove the `l.` in `l.city`: ``` SELECT d.department_name, l.city FROM departments d NATURAL JOIN (SELECT l.location_id,l.city,l.country_id FROM locations l INNER JOIN countries c ON (l.country_id = c.country_id) INNER JOIN regions r...
ORA-00904: invalid identifier when using natural join in the from clause combined with inner joins in subquery
[ "", "sql", "oracle11g", "" ]
Using Postgres, I can perform an update statement and return the rows affected by the commend. ``` UPDATE accounts SET status = merge_accounts.status, field1 = merge_accounts.field1, field2 = merge_accounts.field2, etc. FROM merge_accounts WHERE merge_accounts.uid =accounts.uid RETURNING accounts.* ``` Th...
### Only update rows that actually change That saves expensive updates ***and*** expensive checks after the `UPDATE`. To update every column with the new value provided (if anything changes): ``` UPDATE accounts a SET (status, field1, field2) -- short syntax for .. = (m.status, m.field1, m.field2) -- .. u...
if you aren't relying on side-effectts of the update, only update the records that need to change ``` UPDATE accounts SET status = merge_accounts.status, field1 = merge_accounts.field1, field2 = merge_accounts.field2, etc. FROM merge_accounts WHERE merge_accounts.uid =accounts.uid AND NOT (status IS NOT D...
Return rows of a table that actually changed in an UPDATE
[ "", "sql", "postgresql", "sql-update", "" ]
I am using `DATEDIFF( day, date1, date2)` and it works great. Is it possible to have the plus sign if a number is positive and if it is negative, it has a minus.
You can CAST or CONVERT the output to a string, and then add the '+' sign if required (the minus will already be there if it is negative. ``` Case When DATEDIFF( day, date1, date2) > 0 Then '+' Else '' End + Cast (DATEDIFF( day, date1, date2) as VarChar(10)) ``` Here is an example ``` ;With MyTable as ( Select G...
You can use conditional formatting: ``` SELECT FORMAT(DATEDIFF( day, date1, date2),'+#;-#;0') FROM MyTable ```
SQL DATEDIFF add plus sign if number is positive
[ "", "sql", "sql-server", "t-sql", "datediff", "" ]
How could I retrieve only records that have a substring in one attribute that exists in the same attribute but on a different record for the same ID?.. to elaborate what I mean here's an example: Table containing two attributes: - ID - version Data is as follows: ID version 1 'draft 1.0' 1 'final' 1 '1.0' ...
This should works ``` with countOfVersion as (select id, count(id) occurence from yourTable where regexp_like(version, '^*1.0$*$') group by id) select id from countOfVersion where occurence > 0; ``` If you want to check for version 1.2 then don't forget to change the 1.0 in the regex.
Given what you explained, the better advice is probably the one given by @mason in a comment: *"You should normalize your tables."*. Assuming this is *not* an option at this time, *my* second option would be to add some virtual column containing the *version number*. At the very least this will allow you to easily ind...
check if a substring exists in another row for the same ID
[ "", "sql", "oracle", "" ]
I have the following statement which is still returning divide by zero error even when using the coalesce expression. ``` COALESCE(CAST(sum(case when W0.i13 = 1 then 1 else 0 end)AS FLOAT) / CAST(sum(case when W0.i13 <> 0 then 1 else 0 end) AS FLOAT),0) ``` > Msg 8134, Level 16, State 1, Line 1 Divide by zero error e...
As CoderOfCode pointed out in the comment - you are using 0 as the second argument to COALESCE instead of 1. But your real problem is that the `SUM` in the divisor gives 0, and COALESCE will happily use that (because 0 != NULL). You should be able to use a combination of `COALESCE / NULL` in the divisor part to force ...
When the SUM getting ZERO. It will be devided by ZERO. Try this... ``` COALESCE(CAST(sum(case when W0.i13 = 1 then 1 else 0 end)AS FLOAT),1) / COALESCE(CAST((case when sum(case when W0.i13 <> 0 then 1 else 0 end) = 0 then 1 else sum(case when W0.i13 <> 0 then 1 else 0 end) end) AS FLOAT),1) ```
SQL Server Divide by zero error encountered COALESCE()
[ "", "sql", "sql-server-2008", "" ]
I currently have an MS SQL query which calculates the length of time that each User has been logged in to a system during one day. The table I am extracting this information from records each log in/log out as a separate record. Currently, my MS SQL code is as follows: ``` SELECT CAST(DateTime As Date), User...
First you need to aggregate by date, and then by larger units of time. For instance, for the year to date: ``` SELECT UserId, SUM(diffsecs) FROM (SELECT CAST(DateTime As Date) as thedate, UserID, DATEDIFF(second, MIN(DateTime), MAX(DateTime)) as diffsecs FROM LoginLogoutData GROUP BY CAST(Date...
Here is an example of how to do this with working sample data and the T-SQL included. ``` -- original table you described CREATE TABLE LoginLogoutData (UserID int, DateTime DateTime) GO -- clean any previous sample records TRUNCATE TABLE LoginLogOutData /*local variables for iteration*/ DECLARE @i int = 1 ...
MS SQL GROUPED SUM
[ "", "sql", "sql-server", "sum", "" ]
I want to show results according to distance for e.g. if distance is under 300 than results till 300. If it is not under 300 than only take second condition which is under 400. But i am getting all results for e.g. 118,149,357 my inner select statement returns distance through a function ``` SELECT A.Id, A.Distance...
Try this. ``` ;WITH cte AS (SELECT Id, Round(( dbo.Getdistance(@Latitude, @Longitude, Latitude, Longitude) * 1000 ), 0) AS Distance FROM Messages WITH (NOLOCK) WHERE Len(Latitude) > 0 AND Len(Longitude) > 0) SELECT A.Id, A.Distance FROM cte a WHERE A....
A `WHERE` clause is evaluated for each row. Inside your filter for one specific row, you cannot use the existence of other rows in the same result set as a criterion in your filter. You have to re-think your approach. One way I can think of is to rank the rows by distance, and select the top 1 rank: ``` WITH cte1 AS ...
Conditional statement in where clause not working
[ "", "sql", "" ]
I would like to delete records from a table if the corresponding record is not present in another table. I.e. table1 has one-to-many relationship with table2. I need to delete orphaned records from table2 where table2.id is not present in table1. I have tried this in Access: `DELETE * FROM t2 RIGHT JOIN t2 ON t1.id ...
Remove the `*` after `DELETE`.. I would have solved it like this: ``` DELETE FROM t2 WHERE id not in ( SELECT id from t1); ``` Not sure if deleting with a join will work. It would need to be a `LEFT JOIN`though, as you want to delete all the rows in the first part of the join that is not joined with anything. Als...
This will help: ``` DELETE from t2 FROM t1 RIGHT JOIN t2 ON t1.id = t2.id WHERE t2.id is NULL ```
How to delete 'orphaned' records from second table
[ "", "sql", "ms-access", "" ]
i need to convert the following values from a variable: ``` 1234,1234,12345,12346,1344,4564 ``` to this: ``` '1234','1234','12345','12346','1344','4564' ``` using an SQL function. I have tried: ``` DECLARE @VAL AS VARCHAR(MAX) SELECT @VAL = '1234,1234,12345,12346,1344,4564' DECLARE @listStr VARCHAR(MAX) SELECT @...
Try this: ``` SELECT '''' + REPLACE('1234,1234,12345,12346,1344,4564', ',', ''',''') + ''''; ``` Check this **[SQL FIDDLE DEMO](http://www.sqlfiddle.com/#!3/d41d8/42450)** **OUTPUT** ``` | COLUMN_0 | |---------------------------------------------| | '1234','1234','12345','12346','...
``` DECLARE @VAL AS VARCHAR(MAX) SELECT @VAL = '1234,1234,12345,12346,1344,4564' SELECT '''' + REPLACE(@VAL,',',''',''') + '''' ```
Comma delimited list to string sql
[ "", "sql", "sql-server", "t-sql", "replace", "string-concatenation", "" ]
In my table, I have a datetime column and a tag column. I would like to select the latest value before a timespan, if there are no values in the timespan. If there are values in the timespan, I would not like to return any values. My query has the following input parameters: ``` @StartDate datetime @EndDate datetime ...
Here is my revised answer for the modified question: ``` SELECT [A].* FROM [dbo].[MyTable] AS [A] INNER JOIN ( SELECT [Tag], MAX([StartTime]) AS [StartTime] FROM [dbo].[MyTable] WHERE [StartTime] < @StartTime GROUP BY [Tag] ) AS B ON ([A].[Tag] = [B].[Tag] AND [A].[StartTime] = [B].[StartTime]) WHERE [A].[St...
``` SELECT * FROM MyTable t WHERE StartTime < @start AND id = (SELECT TOP 1 mt.id FROM MyTable mt WHERE mt.Tag = t.Tag ORDER BY StartTime DESC) AND NOT EXISTS (SELECT 1 FROM MyTable WHERE StartTime >= @start AND StartTime <= @end) ORDER BY StartTime DESC; ```
SQL Query - Select last date before timespan where no dates exists in timespan
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table (Postgres 9.3) defined as follows: ``` CREATE TABLE tsrs ( id SERIAL PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers, timestamp TIMESTAMP WITHOUT TIME ZONE, licensekeys_checksum VARCHAR(32)); ``` The pertinent details here are the `customer_id`, the `timestamp`, and ...
Your query in the question should perform better than the queries in the (previously) accepted answer. Test with `EXPLAIN ANALYZE`. `DISTINCT ON` is typically simpler and faster: ``` SELECT DISTINCT ON (licensekeys_checksum) * FROM tsrs ORDER BY licensekeys_checksum, timestamp DESC NULLS LAST; ``` *db<>fiddle [he...
Try this ``` select * from tsrs where (timestamp,licensekeys_checksum) in ( select max(timestamp) ,licensekeys_checksum from tsrs group by lice...
Returning the row with the most recent timestamp from each group
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I am trying to find two-tailed inverse of the X's t-distribution. It can be find using TINV function in Excel but I need this to achieve in SQL Sever. Please suggest me idea. The TINV function syntax has the following arguments: **Probability** : The probability associated with the two-tailed Student's t-distribution...
SQL-Server does not incorporate a lot of statistical functions. `tinv` is not present in SQL-Server. The only way to add a tinv function, is to use a CLR-Function. Thus, the problem reduces itselfs to "How do I calculate tinv with the subset of C# allowed in SQL-Server ?". If you're on .NET 4.0, you could use t...
You could either write your own implementation as a SQL function or use a [CLR](http://msdn.microsoft.com/en-us/library/ms254498%28v=vs.110%29.aspx) and write it in C#. My advice would be to use a CLR and include the [Accord](http://accord-framework.net) library (I recommend this one because they still have .NET 3.5 v...
SQL Server equivalent of Excel's TINV function
[ "", "sql", "sql-server", "distribution", "probability", "" ]
I have a table of employees which contains about 25 columns. Right now there are a lot of duplicates and I would like to try and get rid of some of these duplicates. First, I want to find the duplicates by looking for multiple records that have the same values in first name, last name, employee number, company number ...
You can use the sys.columns table to get a list of columns and build a dynamic query. This query will return a 'KeepThese' value for every record you want to keep based on your given criteria. ``` -- insert test data create table EmployeeMaster ( Record int identity(1,1), FirstName varchar(50), LastName ...
Try this. ``` ;WITH cte AS (SELECT Row_number() OVER( partition BY firstname, lastname, employeenumber, companynumber, statusflag ORDER BY (SELECT NULL)) rn, firstname, lastname, employeenumber, ...
Remove duplicates with less null values
[ "", "sql", "sql-server", "" ]
I would like to create a query where I find the details only for members with the earliest and latest registration\_date. So far I have ``` SELECT member_id, UPPER(name), registration_date from db.member WHERE registration_date >= '2012-01-01' ``` I am unsure how to find just min/max but am just testing it with the ...
you can get `min` , `max` dates in a subquery and then can get the results. ``` select member_id, upper(name), registration_date from db.member cross join ( select min(registration_date) as minDate, max(registration_date) as maxDate from db.member ) t where registration_date in ( t.minDate, t.maxDate) ``...
select min(dateColumn),max(dateColumn) from tbl;
Finding min and max dates SQL
[ "", "sql", "max", "min", "" ]
1. Working on SQL (2005 and 2008) 2. the variable with value '1,2,3' would be call @cedis and this could to have N number for example ``` set @cedis='1' or set @cedis='1,2,3,4,5,6,7' or set @cedis='125,98,91' ``` 3. so important, its this must to be a select only, a loop could not to be use, only a select! 4....
If am not wrong this is what you need ``` DECLARE @cedis VARCHAR(500)='1,2,3,4' SELECT Split.a.value('.', 'VARCHAR(100)') Numbers FROM (SELECT Cast ('<M>' + Replace(@cedis, ',', '</M><M>') + '</M>' AS XML) AS Numbers) AS A CROSS APPLY Numbers.nodes ('/M') AS Split(a) ``` **Result:** ``` Numbers ------- 1 2...
A table valued function would do it. ``` CREATE FUNCTION [dbo].[fn_Split](@text VARCHAR(MAX), @delimiter VARCHAR(5) = ',') RETURNS @Strings TABLE ( position int IDENTITY PRIMARY KEY, value VARCHAR(8000) ) AS BEGIN DECLARE @index int SET @index = -1 WHILE (LEN(@text) > 0) BEGIN ...
Hot to convert a variable with value '1,2,3' to a table (every number as a record)
[ "", "sql", "sql-server", "t-sql", "select", "" ]
If I execute the following query it works fine. ``` SELECT CASE WHEN description LIKE '%a%' THEN 'A' WHEN description LIKE '%b%' THEN 'B' ELSE 'C' END AS foo ,COUNT(*) AS cnt FROM product p GROUP BY foo ORDER BY foo; ``` The result is something like ``` foo | cnt ----------- A | 809 B |...
The reason why that happens is because MySQL was processing ORDER BY in earlier versions (apparently including 5.0) is the following way: 1. If the entire `ORDER BY` clause is an integer, sort by the corresponding element of the projection clause (`ORDER BY 2` sorts by the second element of the project clause) 2. If t...
If you want to group by the alias then put your query in a derived table ``` SELECT foo, count(*) cnt FROM ( SELECT CASE WHEN description LIKE '%a%' THEN 'A' WHEN description LIKE '%b%' THEN 'B' ELSE 'C' END AS foo FROM product p ) t1 GROUP BY foo ORDER BY FIELD(foo, 'A', 'B', 'C'); ...
Can't use alias in mysql function as part of ORDER BY clause
[ "", "mysql", "sql", "sql-order-by", "" ]
Given this table: ``` create temp table stats ( name text, country text, age integer ) insert into stats values ('eric', 'se', 1), ('eric', 'dk', 4), ('johan', 'dk', 6), ('johan', 'uk', 7), ('johan', 'de', 3), ('dan', 'de', 3), ('dan', 'de', 3), ('dan', 'de', 4) ``` I want know the coun...
You can join on the original table also: ``` SELECT s1.country, s1.age, COUNT(distinct s2.name) FROM stats s1 JOIN stats s2 ON s1.country=s2.country OR s1.age=s2.age GROUP by 1, 2; ```
Select distinct age and country from stats. For each record count how many distinct names you find in records matching country or age. ``` select country, age, ( select count(distinct name) from stats s where s.country = t.country or s.age = t.age ) as cnt from (select distinct country, age ...
Count distinct where attribute is either of keys
[ "", "sql", "postgresql", "" ]
I'm hitting a baffling issue in SQL. Somehow, a JOIN in a CASE statement is returning both TRUE and FALSE! If you run the below (I'm using SQL Server 2008), you'll see the effect. The JOIN creates 2 records, based on the CASE statements. Any ideas how to stop this? ``` CREATE TABLE #table1(id int PRIMARY KEY, fieldA...
It seems that you are using #table2.fieldB as a JOIN condition, so you are getting 2 values ('ABC Airlines' and 'Other'). Your expected result can be achieved if you change your query this way ``` SELECT * FROM #table1 t JOIN #table2 t2 ON t.fieldA = CASE WHEN t.fieldA <> t2.fieldB THEN '*** OTHER ***' ELSE t2...
why wouldn't you want: ``` SELECT * FROM #table1 t JOIN #table2 t2 ON t.fieldA = t2.fieldB ``` It is a bad practice to use case statements and inequalities in joins. Based on your end result desired all you want is an ordinary inner join.
why is SQL CASE returning both true and false?
[ "", "sql", "sql-server", "" ]
I am pretty new in SQL and expecially in Oracle DB and I have some doubt about how to update a specific single field values of all records of a table. So, int an Oracle DB, I have a very simple table named **PROJECT\_INFO\_STATUS** that have the following form: ``` ID STATUS ------------- 0 Closed 1 Active 2 T...
``` update PROJECT_INFO_STATUS set ID = ID +1 ``` you can directly add column value if it is not `PK` or `FK`
Simply set the column value to itself plus one: ``` update project_info_status set id = id + 1; select * from project_info_status; ID STATUS ---------- ---------- 1 Closed 2 Active 3 Testing 4 Started ``` If the ID value is used as a foreign key in anoth...
How can I update the value of a specific field of my table for all rows?
[ "", "sql", "database", "oracle", "oracle10g", "oracle-sqldeveloper", "" ]
For MSSQL or MySQL, here is a query that unites two results into one: ``` SELECT boy as person from table1 union all SELECT girl as person from table2 ``` How to modify the query above so that the result contains the second (added) column with the name of the table (so it contains `table1` or `table2` value).
you can give string lateral with table name as second column ``` SELECT boy as person, 'table1' as column2 from table1 union all SELECT girl as person, 'table2' as column2 from table2 ```
Just `Hard code` the `tablename` in Second Column ``` SELECT boy as person,'Table1' as Tablename from table1 UNION ALL SELECT girl as person ,'Table2' as Tablename from table2 ```
Select with UNION ALL to display tablename as an additional column
[ "", "mysql", "sql", "select", "union", "" ]
Postgres I have table user\_answers: ``` ---------------------------- | id | user_id | answer_id | ---------------------------- | 1 | 47 | 121 | ---------------------------- | 2 | 47 | 125 | ---------------------------- | 3 | 47 | 141 | ---------------------------- | 4 | 49 |...
Your query returns nothing because `answer_id` has only one value on any given row. It cannot have multiple values on the row. This is an example of a set-within-sets query. I would recommend using `group by` and `having`. Here is one method: ``` SELECT user_id FROM user_answers WHERE answer_id IN (121, 125) GROUP BY...
``` select user_id from user_answers where answer_id in (121, 125) group by user_id having count(*) = 2 ```
How to compare the values of one column? SQL(Postgres)
[ "", "sql", "postgresql", "" ]
I have the following mysql table (simplified): ``` CREATE TABLE IF NOT EXISTS `mytable` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `emails` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `phones` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `history` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, ...
Organize your `OR` criteria in `()` ``` SELECT * FROM mytable WHERE (all_emails LIKE '%addr@yahoo.com%' OR all_phones LIKE '%addr@yahoo.com%') AND history !='None ``` [`Sample Demo`](http://www.sqlfiddle.com/#!2/df6830/3)
You should explicitly set parenthesis in your `WHERE` clause : ``` WHERE (all_emails LIKE '%addr@yahoo.com%' OR all_phones LIKE '%addr@yahoo.com%') AND history !='None' ```
Mysql not equal operator failing?
[ "", "mysql", "sql", "" ]
Basically, when given a list of strings, I want to create a table with `select` statement. For example, ``` "A", "B", "C", ``` I want to create a table as a sub-select like: ``` sub-select +---------+ | "A" | +---------+ | "B" | +---------+ | "C" | +---------+ ``` How do I do this in redshift and post...
One of the way to convert a column value to multiple rows is using split\_part function and UNION. Here is an example. Source Table: ``` => CREATE TABLE t_csv (value varchar(64)); => INSERT INTO t_csv VALUES ('"A","B","C"'); => INSERT INTO t_csv VALUES ('"D","E"'); => INSERT INTO t_csv VALUES ('"F","G","H","I"'); =>...
Have no chance to test it in db, but something like that ``` select * INTO table from ( SELECT CAST('A' AS VARCHAR(100)) AS col UNION ALL SELECT 'B' AS col UNION ALL SELECT 'C' AS col ) a ```
From a string array, create a table
[ "", "sql", "postgresql", "amazon-redshift", "" ]
I have a table analyst\_request ``` ------------------------- id | test | request_id | ------------------------- 1 | a |NDQA201404320 ------------------------- 2 | a |NDQA201404320 ------------------------- 3 | b |NDQA201404333 ------------------------- 4 | ...
Generally you can do ``` delete from analyst_request where id not in ( select min(id) from analyst_request where request_id IN ( 'NDQA201404320') group by test, request_id ) ``` But MySQL can't delete from the same table you are selecting from. So you need to make a temp table like this ``` delete from...
Why not make it a `unique` field and prevent duplicates getting into the data base in the first place?
Delete Single value from duplicate record
[ "", "mysql", "sql", "" ]
I need to get the following two queries into one statement in PostgreSQL. ``` select count(*) as REDEEMTOTALUSED from voucher where campaign_id='123' and redeemcount>0; select count(*) as REDEEMTOTALUNUSED from voucher where campaign_id='123' and redeemcount=0; ``` The result should be the following. ``` REDEEM...
Please try: ``` select (select count(*) as REDEEMTOTALUSED from voucher where campaign_id='123' and redeemcount>0) AS REDEEMTOTALUSED , (select count(*) as REDEEMTOTALUNUSED from voucher where campaign_id='123' and redeemcount=0) AS REDEEMTOTALUNUSED ``` or another way: ``` SELEC...
Use conditional aggregation: ``` select sum(case when redeemcount > 0 then 1 else 0 end) as REDEEMTOTALUSED, sum(case when redeemcount = 0 then 1 else 0 end) as REDEEMTOTALUNUSED from voucher where campaign_id = '123'; ```
Multiple queries in one statement
[ "", "sql", "postgresql", "" ]
I have a report that produces a list of values that should all be numbers but are currently stored as a varchar. In my export I am casting the varchar character as an Int but when some one incorrectly enters a char or a special character the report fails because is cannot convert to an INT ``` Current List 557780 5588...
You can try this on SQL 2012+: ``` SELECT COALESCE(TRY_CONVERT(INT, SomeNum), 99999999) AS Value FROM YourTable ```
you can use do it with pattern ``` case when SomeNum NOT LIKE '%[^0-9]%' THEN 99999999 ELSE cast(SomeNum as int) END ```
SQL Server Check String for Spaces, Special Characters, and Charcters
[ "", "sql", "sql-server", "sql-server-2012", "" ]
ere's an example: I want to see how good my marketing efforts are working for a product I'm trying to sell in a store. For instance, I want to know how many people bought my product within a month after they received a coupon for it in their email on 12/1/2014, compared to how many people bought my product in that same...
Use `Left Outer Join` with `NULL` check ``` SELECT C.* FROM customer C LEFT OUTER JOIN email e ON C.customer_Number = E.customer_Number WHERE E.customer_Number IS NULL ``` Or use `Not Exists` ``` SELECT * FROM customer C WHERE NOT EXISTS (SELECT 1 FROM email e ...
``` select from customers c left outer join email e on c.customer_number = e.customer_number where e.customer_number is null or C.purchase_date < e.send_date ```
How to write a SQL query that subtracts INNER JOIN results from LEFT JOIN results?
[ "", "sql", "left-join", "inner-join", "" ]
Hi I try to show data from two tables, but second table is empty ``` SELECT ST.* , E.data, E.status FROM `students` ST INNER JOIN `table2` E ON E.id_student=ST.id_student WHERE ST.class='$class' AND E.data LIKE '$year-$month-%' ORDER BY ST.surname, ST.name, E.data ``` what query I can use for my request (if second...
Left join will do it for you. ``` SELECT ST.* , E.data, E.status FROM `students` ST LEFT JOIN `table2` E ON E.id_student=ST.id_student and E.data LIKE '$year-$month-%' WHERE ST.class='$class' ORDER BY ST.surname, ST.name, E.data ``` It will give you ST data values even if E data is empty. Of course you have to take c...
You have to use **LEFT JOIN** to fetch the data from first table and matched data of second table. ``` SELECT ST.*, E.data, E.status FROM `students` ST LEFT JOIN `table2` E ON E.id_student=ST.id_student AND E.data LIKE '$year-$month-%' WHERE ST.class='$class' ORDER BY ST.surname, ST.name, E.data ```
MySQL - Select from table 1 if second table is empty or not not empty
[ "", "mysql", "sql", "select", "join", "" ]
I have to calculate percentage based on count. Given below is a sample data table. ``` TeamName Count1 Count0 -------- ----- ------ Team1 1 2 Team2 3 0 Team3 1 1 ``` I want to display the percentage based on the `greatest value` in `Count1`. `The expecting output sam...
use `Max()over ()` trick to find the max of all the row. ``` select TeamName, Count1, Count0, (count1*100.0)/nullif(Max(Count1) over(),0) Percentage1, (count0*100.0)/nullif(max(Count1) over(),0) Percentage2 from yourtable ``` or Use a `subquery` to find the `Max` and do the math ``` SELECT TeamName, Count...
``` SELECT TeamName, Count1, Count0, Count1 / (SELECT MAX(Count1) FROM Tbl), Count0 / (SELECT MAX(Count1) FROM Tbl) FROM Tbl ``` What out for zero values in Count1. I can improve answer, if you describe case what to do when MAX(Count1) is zero.
How to calculate percentage in sql?
[ "", "sql", "" ]
I have two tables that I want to join. The first table is named `WorkItem`: ![enter image description here](https://i.stack.imgur.com/zC4in.png) The second table is `WorkItem_Schedule`: ![enter image description here](https://i.stack.imgur.com/9pAce.png) I want to get the **1st** joined row with `ActualEndDate IS N...
`cross apply` is probably the easiest way to do this: ``` select w.*, ws.* from WorkItem w cross apply (select top 1 ws.* from WorkItem_Schedule ws where ws.WorkItemId = w.WorkItemId and ws.ActualEndDate is null order by ws.WorkItemScheduleId ) ws; ``` By "first", I assume you ...
You could use `ROW_NUMBER()` function to get the "first" joined row. ``` SELECT * FROM ( SELECT W.WorkItemId ,WS.WorkItemScheduleId ,CASE WHEN WS.ActualEndDate IS NULL THEN ROW_NUMBER() OVER (PARTITION BY W.WorkItemId ORDER BY WorkItemScheduleId) --ROW_NUMBER() only invoked when the ActualEndDate I...
SQL Server INNER JOIN with GROUP BY
[ "", "sql", "sql-server", "inner-join", "" ]