Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have to produce artikel number based on some convention, and this convention is as below The number of digits ``` {1 or 2 or 3}.{4 or 5}.{n} ``` example products numbers: ``` 7.1001.1 1.1453.1 3.5436.1 12.7839.1 12.3232.1 13.7676.1 3.34565.1 12.56433.1 247.23413.1 ``` The first part is based on producent, and ev...
A fairly straight forward way is to (ab)use [PARSENAME](https://msdn.microsoft.com/en-us/library/ms188006.aspx) to split the string to be able to extract the current maximum. An outer query can then just implement the rules for the value being missing/9999/other. The value (12 here) is inserted in a table value constr...
I don't fully understand what you're asking for. I am unsure about the examples...but if i was doing it I'd try to break the field into 3 fields first and then do something with them. [sqlfiddle](http://sqlfiddle.com/#!6/91513/15) ``` SELECT nummer,LEFT(nummer,first-1) as field1, RIGHT(LEFT(nummer,second-1),sec...
Get max number from table add one and check with specific convention
[ "", "sql", "sql-server", "" ]
How can I execute the below Stored Procedure? ``` create or replace procedure squareOf(x IN OUT NUMBER) is begin x:= x*x; end; ```
@Massie already mentioned one approach using anonymous block. Another approach is using bind variable in command line like below - ``` var c number; exec :c:= 6; execute squareOf(:c); print c; ```
``` DECLARE x NUMBER := 6; BEGIN squareOf(x => x ); dbms_output.put_line( 'X: '|| x ); END; ``` returns 36
Executing a Stored Procedure from Oracle SQL Developer
[ "", "sql", "oracle", "stored-procedures", "" ]
We are using the below updated SQL to get customers list from our db whom we send SMS before 3 days. ``` SELECT * FROM sms WHERE sent_time >= NOW() - INTERVAL 3 DAY; ``` The table `sms` is updated daily along with the `sent_time` column with default value of 0 or the last sent time. There are rows with the value of ...
The function `NOW()` will return current date and time, but as I can see you have used PHP [time()](http://php.net/manual/en/function.time.php) before, which returns a Unix-Timestamp. The SQL equivalent is `UNIX_TIMESTAMP()`. Syntax `UNIX_TIMESTAMP()` ``` SELECT * FROM sms WHERE sent_time >= UNIX_TIMESTAMP() - (60*60...
`NOW() - INTERVAL 3 DAY;` returns a DATETIME while `echo time() - ( 60*60*24*3 );` returns a timestamp. If your database column is a timestamp, your MySQL test will never work, use this instead: ``` SELECT * FROM sms WHERE sent_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 3 DAY) ```
Get all rows before a specific day
[ "", "mysql", "sql", "" ]
I got a Table which looks like this: ``` DATE | Number 01-01-16 00:00:00 10 02-01-16 00:00:00 10 03-01-16 00:00:00 11 04-01-16 00:00:00 12 05-01-16 00:00:00 13 .... 31-01-16 00:00.00 15 ........ 29-02-16 00:00:00 18 ``` I got this table...
This is Gordon's code for determining the correct dates plus subqueries to fetch the Number values for those rows: ``` SELECT (SELECT Number FROM cc_open_csi_view WHERE last_day(date_sub(curdate(), interval 1 month)) = date(`DATE`)) as lastmonth, (SELECT Number FROM cc_open_csi_view WHERE last_d...
Here is logic for the last day of this month and the previous month: ``` select last_day(curdate()) as last_day_of_this_month, last_day(date_sub(curdate(), interval 1 month)) as last_day_of_prev_month ``` You can get the last day of any month relative to the current month by changing the "1". And, I have no i...
SQL - Last Day of Month
[ "", "mysql", "sql", "" ]
I have a select statement, where I have created 2 temp tables and doing an insert into select before taking the data from those temp tables creating a join between them. This final select is what I want the metadata to be. In ssms it runs fine, in ssis I don't know why its throwing that error. Query is as such: ``` CR...
try using a table variable instead something like: ``` DECLARE @Per TABLE (PerID bigint NOT NULL......) DECLARE @Pre TABLE (PerID bigint NOT NULL, IsWorking.......) INSERT INTO @Per SELECT .... FROM ..... INSERT INTO @Pre SELECT .... FROM ..... SELECT * FROM @Per per LEFT JOIN @Pre pre ON per.PerID = pre.PerID ``` Sh...
If you are working on SSIS 2012 or later versions, then it uses system stored procedure **sp\_describe\_first\_result\_set** to fetch the metadata of the tables and it does not support temporary tables. But you can use other options like table variables and CTEs.
The metadata could not be determined because statement 'insert into
[ "", "sql", "ssis", "" ]
I am not very familiar with SQL queries, but I would like to move and combine multiple queries which I'm doing on the code level to the server to speed it up and to simplify it. Currently this takes several seconds even for only 5-10 items. I have a view and a table, let's call them View1, Table1. My first query: ``...
I have given a try with subqueries, this is working for me. Thanks everyone for trying to help! ``` SELECT View1.Data, View1.ItemId, z.SerialNumberDate, z.IsPrinted FROM View1 JOIN ( SELECT View1.Id, x.SerialNumberDate, x.IsPrinted FROM View1 JOIN ( ...
CTEs are a simple way to combine such queries: ``` with q1 as ( SELECT UnitSerialNumber, SerialNumberDate, IsPrinted FROM Table1 WHERE OrderID = 1234 AND IsActive = 1 ), q2 as ( SELECT ResultId, SerialNumberDate, IsPrinted FROM View1 WHERE ItemId = 338 AND StatusId = 2 AN...
SQL Query Simplification - How to do in SQL Server what is currently done in the code?
[ "", "sql", "sql-server", "while-loop", "" ]
I have data set of call customer, I want to make count () to know: Total number of calls for each customer Total duration of call for each customer Total of locations the customer he where in This my data: ``` Phone no. - Duration In minutes - Location 1111 3 88 2222 4 ...
This is almost similar to fthiella answer. Try like this ``` select PhoneNo, count(*) as TotalNumberOfRecords, sum(DurationInMinutes) as TotalDurationOfCalls, count(distinct location) as TotalOfLocations from yourtablename group by PhoneNo ```
You can use a GROUP BY query with basic aggregated functions, like COUNT(), SUM() and COUNT(DISTINCT) like this: ``` select phone_no, count(*), sum(duration), count(distinct location) from tablename group by phone_no ```
make many count () in one query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to figure out what the correct syntax for `UNION` is. My schema looks like is the following: ``` Players (playerNum, playerName, team, position, birthYear) Teams = (teamID, teamName, home, leagueName) Games = (gameID, homeTeamNum, guestTeamNum, date) ``` I need to print all `teamIDs` where the team played...
If you just need the home teams, this should suffice: ``` SELECT DISTINCT hometeamnum FROM games WHERE guestteamnum NOT IN (SELECT teamid FROM teams WHERE teamname = 'Y') ``` If you need both home teams and guest teams: Select all teams that are not 'y' that didn't play agains 'y' as home team and didn't play agains...
Using `NOT EXISTS` allows you to locate rows that don't exist. That is , you want teams that have played against 'X' which are rows that do exist and these can be located by using a simple join and where clause\*\*. Then from those rows you need to find any that do not exist against the team 'Y'. ``` SELECT DISTINCT ...
SQL UNION syntax
[ "", "sql", "" ]
I have two tables - DataRecord and DataRecordArchive New(unique dataRecordID - ex. 'id1') dataRecord inserted to DataRecord table with version 0. When (almost every) update is performed on some existing dataRecord (dataRecordID 'id1' already exists in DataRecord table) - the existing dataRecord (id :'id1' version :0 )...
Create a view that unions the two tables. Update the view.
I cannot place a comment so will post as an answer. Ideally, we would need your table structure, sample data from your tables to suggest correctly. However, based on limited info I suggest to use dynamic sql. You will use dynamic sql to manipulate the from clause of your sql query based on conditions. Please post tabl...
How to select record from one of two tables by criteria , then update it
[ "", "sql", "sql-server", "database", "t-sql", "sql-update", "" ]
How I can make the following query and delete in one query ? ``` select krps.kpi_results_fk from report.kpi_results_per_scene krps inner join report.kpi_results kr on kr.session_uid = '0000c2af-1fc8-4729-bb2a-d4516a63107a' and kr.pk = krps.kpi_results_fk delete from report.kpi_results_per_scene where kpi_results_fk ...
I think for your case, *NO* need to use `inner join`. Following query could reduce the overhead of `inner join` ``` DELETE FROM report.kpi_results_per_scene WHERE kpi_results_fk IN (SELECT kr.pk FROM report.kpi_results kr WHERE kr.session_uid = '0000c2af-1fc8-4729-bb2a-d4516a63107a') ```
use IN operator: ``` delete from report.kpi_results_per_scene where kpi_results_fk in ( select krps.kpi_results_fk from report.kpi_results_per_scene krps inner join report.kpi_results kr on kr.session_uid = '0000c2af-1fc8-4729-bb2a-d4516a63107a' and kr.pk = krps.kpi_results_fk) ```
Write a SQL delete based on a select statement
[ "", "mysql", "sql", "" ]
I have a **table** (lets call it AAA) containing 3 colums **ID,DateFrom,DateTo** I want to write a query to return all the records that contain (even 1 day) within the period DateFrom-DateTo of a **specific year** (eg 2016). I am using SQL Server 2005 Thank you
Try this: ``` SELECT * FROM AAA WHERE DATEPART(YEAR,DateFrom)=2016 OR DATEPART(YEAR,DateTo)=2016 ```
Another way is this: ``` SELECT <columns list> FROM AAA WHERE DateFrom <= '2016-12-31' AND DateTo >= '2016-01-01' ``` If you have an index on `DateFrom` and `DateTo`, this query allows Sql-Server to use that index, unlike the query in Max xaM's answer. On a small table you will probably see no difference but on a l...
SQL find period that contain dates of specific year
[ "", "sql", "sql-server-2008", "" ]
I Use simple sql query to save some date to database. mysql column: ``` current_date` date DEFAULT NULL, ``` But when executed query show Error: ``` insert into computers (computer_name, current_date, ip_address, user_id) values ('Default_22', '2012-01-01', null, 37); ``` [2016-03-22 12:21:46] [42000][1064] ...
`current_date` is a [mysql function](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html), you can't have it as columns alias in your insert into query; try escaping your column names `` insert into computers (`computer_name`, `current_date`, .... ``
"current\_date" is reserved in MySQL, so use (`) character to enclose field names Use this ``` INSERT INTO computers (`computer_name`, `current_date`, `ip_address`, `user_id`) VALUES ('Default_22', '2012-01-01', null, 37); ```
SQL syntax error, when saving date to MySql
[ "", "mysql", "sql", "date", "" ]
I have SQL Server 2014 and for college I want to implement soft delete on all my tables. ``` SET DATEFORMAT dmy CREATE TABLE Customers ( CustomerId int IDENTITY (1,1) not null, FirstName varchar (20) not null, LastName varchar (30) not null, Address1 varchar (30) not null, Address2 varchar (30) no...
*Consistency is key.* Whatever field name you use on one table try to keep it consistent for the other tables also, this will help greatly when you refactor code and need to apply a new where clause to many lines of code. Using [`ALTER TABLE`](https://msdn.microsoft.com/en-us/library/ms190273.aspx) you could simply a...
Add field deleted\_time (user etc. ) and add trigger to fill this fields on delete and cancel delete record. In query's add condition deleted\_time is not null. For better performance on current data you can create new table like "Customers\_arch" and add trigger on delete to Customers, to insert row from Customers t...
Implementing soft delete
[ "", "sql", "sql-server-2014", "soft-delete", "" ]
I need to write an SQL query to identify the title of the film with the longest running time and I'm just wondering how I would do that? I've tried this but I'm not sure exactly what I need to do to fix the statement. ``` select f.film_title from film f order by f.film_len desc limit 1; ``` I thought the simplest app...
--You have to assume that there will be movies with the same runtime. ``` select f.film_title from film f where film_Len = (select max(film_Len) from film) ```
You can also use ranking function to determine: ``` SELECT * FROM (SELECT f.film_title, rank() over(partition BY f.film_title order by f.film_len DESC) rnk from film f ) WHERE rnk = 1 ``` If there're 2 films with the same length, they will be shown.
SQL ORDER and LIMIT to 1 result
[ "", "sql", "oracle", "max", "sql-order-by", "rownum", "" ]
I have a column in `jsonb` storing a map, like `{'a':1,'b':2,'c':3}` where the number of keys is different in each row. I want to count it -- jsonb\_object\_keys can retrieve the keys but it is in `setof` Are there something like this? ``` (select count(jsonb_object_keys(obj) from XXX ) ``` (this won't work as `ERR...
You could convert keys to array and use array\_length to get this: ``` select array_length(array_agg(A.key), 1) from ( select json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}') as key ) A; ``` If you need to get this for the whole table, you can just group by primary key.
Shortest: ``` SELECT count(*) FROM jsonb_object_keys('{"a": 1, "b": 2, "c": 3}'::jsonb); ``` Returns 3 If you want all json number of keys from a table, it gives: ``` SELECT (SELECT COUNT(*) FROM jsonb_object_keys(myJsonField)) nbr_keys FROM myTable; ``` Edit: there was a typo in the second example.
How to count setof / number of keys of JSON in postgresql?
[ "", "sql", "json", "postgresql", "" ]
I've stuck in an MS SQL SERVER 2012 Query. What i want, is to write multiple values in "CASE" operator in "IN" statement of WHERE clause, see the following: ``` WHERE [CLIENT] IN (CASE WHEN T.[IS_PHYSICAL] THEN 2421, 2431 ELSE 2422, 2432 END) ``` The problem here is in 2421, 2431 - they cannot be separated with comma...
This is simpler if you don't use `case` in the `where` clause. Something like this: ``` where (T.[IS_PHYSICAL] = 1 and [client] in (2421, 2431)) or (T.[IS_PHYSICAL] = 0 and [client] in (2422, 2432)) ```
I'd use AND / OR instead of a case expression. ``` WHERE (T.[IS_PHYSICAL] AND [CLIENT] IN (2421, 2431)) OR (NOT T.[IS_PHYSICAL] AND [CLIENT] IN (2422, 2432)) ```
"CASE WHEN" operator in "IN" statement
[ "", "sql", "sql-server", "t-sql", "" ]
I have 2 rows from 2 tables in a database that I want to compare. Column1 is on table1 and is an Integer field with entries like the following `column1 147518 187146 169592` Column2 is on table2 and is a Varchar(15) field with various entries but for this example lets use these 3: `column2 169592 00010000089 DummyI...
You can try to use `ISNUMERIC` in following: ``` SELECT * FROM table1 WHERE column1 IN (SELECT CASE WHEN ISNUMERIC(column2) = 1 THEN CAST(column2 AS INT) END FROM table2) ```
Try casting the int to a string: ``` SELECT * FROM table1 WHERE cast(column1 as varchar(15)) IN (SELECT column2 FROM table2) ```
Cast varchar that holds some strings to integer field in informix
[ "", "sql", "casting", "informix", "" ]
Is there a way to calculate how old someone is based on today's date and their birthday then display it in following manners: ``` If a user is less than (<) 1 year old THEN show their age in MM & days. Example: 10 months & 2 days old If a user is more than 1 year old AND less than 6 years old THEN show their age in...
Probably not the most efficient way to go about it, but here's how I did it: I had to first get the date difference between today's date and person's birthdate. I used it to get years, months, days, etc by combining it with ABS(), and Remainder (%) function. ``` declare @year int = 365 declare @month int = 30 declare...
This is basically what you are looking for: ``` DECLARE @date1 DATETIME , @date2 DATETIME; SELECT @date1 = '1/1/2008' , @date2 = GETDATE(); SELECT CASE WHEN DATEDIFF(YEAR, @date1, @date2) < 1 THEN CAST(DATEDIFF(mm, @date1, @date2) AS VARCHAR)+' Months & '+CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, @...
Get date difference in year, month, and days SQL
[ "", "sql", "sql-server", "date", "date-difference", "" ]
How I can move value of a column to upper row where banakaccount is null Below is my table data of two creditor TABLE1 ``` UniqueDatabaseNo Creditor BankAccountNo 882370 300020 NULL NULL 300020 NULL NULL 300020 NULL 0 300020 ...
You can do what you want using aggregation: ``` select max(UniqueDatabaseNo) as UniqueDatabaseNo, Creditor, max(case when BankAccountNo like '[a-Z][a-Z]%' then BankAccountNo end) as BankAccountNo from t group by Creditor; ``` Edit: You might was conditional logic for `UniqueDatabaseNo` as well: ``` select ma...
Try this ``` select UniqueDatabaseNo,Creditor,TT.BankAccountNo from TABLE1 T1 OUTER APPLY( SELECT BankAccountNo as 'BankAccountNo' FROM TABLE1 T2 WHERE T1.Creditor=T2.Creditor AND T2.BankAccountNo IS NOT NULL )TT where T1.uniquedatabaseno >0 AND T1.UniqueDatabaseNo IS NOT NULL ```
Moving value from below row to upper one
[ "", "sql", "sql-server", "" ]
I have several tables with 30+ columns each and I would like to easily get the names of the columns that do not allow for null values. Is there a simple query that can do this for a table? Something like `describe [table_name]` but that only shows required columns, and not necessarily other info about the columns (li...
``` USE [dbtest] GO CREATE TABLE dbo.[Event] ( ID INT PRIMARY KEY, Name VARCHAR(10) NULL ) GO ------------------------------------------------ USE [dbtest] --- !!! GO SELECT name FROM sys.columns WHERE [object_id] = OBJECT_ID('dbo.Event', 'U') AND is_nullable = 0 ``` Output - ``` name ----------- ID `...
``` SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'test1' AND is_nullable = 'no' ```
Select column names that cannot be null
[ "", "sql", "sql-server", "" ]
I have a `SQL` query that retrieves only the names not containing any number: ``` ... WHERE Name NOT LIKE '%[0-9]%' ``` On the other hand, when trying to use this query in `Lambda Expression` with different combinations as shown below, none of them is working does not work: ``` .Where(m => !m.EmployeeName.Contains("...
As far I know you can't apply regular expression in Linq to Entities. What I recommend to do is if you have other conditions call `Where` method using them first, and then call `AsEnumerable` to work with Linq to Object which allows you use regular expressions, so you can apply the condition you need: ``` var query= c...
You can use `Regex.IsMatch`. ``` yourEnumerable.Where(m => !Regex.IsMatch(m.EmployeeName, @"\d")); ```
Check if a String value contains any number by using Lambda Expression
[ "", "sql", "asp.net-mvc", "entity-framework", "linq", "lambda", "" ]
Let's say I have a table like this: ``` name_1 name_2 value ------------------- john alex 6 alex john 6 bob rick 7 rick bob 7 ``` I want to get rid of the duplicates so I'm left with this: ``` name_1 name_2 value ------------------- john alex 6 rick bob 7 ``` Does `distinct` work? A...
Here's one option using `least` with `greatest` and `distinct`: ``` select distinct least(name_1, name_2) name_1, greatest(name_1, name_2) name_2, value from yourtable ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!4/5cddf/2)
[SQL Fiddle](http://sqlfiddle.com/#!4/0d0f5/1) **Oracle 11g R2 Schema Setup**: ``` create table table_name (name1, name2, value) AS SELECT 'john', 'alex', 6 FROM DUAL UNION ALL SELECT 'alex', 'john', 6 FROM DUAL UNION ALL SELECT 'bob', 'rick', 7 FROM DUAL UNION ALL SELECT 'rick', 'bob', 7 FROM DUAL UNION ALL SELECT...
SQL - remove duplicate tuples, even if values are out of order
[ "", "sql", "oracle", "" ]
I need help with a correlated subquery in Oracle Sql. The problem is, that the second level deep subquery contains the daily.day, so this query results in an error. ``` DAILY - columns: daily_id, day, emp_details_id, worked_hour EMP_DETAILS - columns: emp_details_id, valid_from, valid_to, detail_type, detail_value `...
You can avoid the self-joins by using an analytic query to rank the joined rows by the latest `ed.valid_from` date for the `daily` record. The basic query is something like: ``` SELECT daily.*, ed.*, rank() over (partition by daily.emp_details_id, daily.day order by ed.valid_from DESC) rnk FROM DAILY ...
You need to query DAILY in the subquery. Also, you can get rid of the nested subquery, ORDER BY ... DESC, and ROWNUM = 1 by using the MAX function in the subquery, with the [FIRST or LAST](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions065.htm) aggregate variation to get the DETAIL\_VALUE corresponding ...
Correlated query in oracle sql
[ "", "sql", "oracle", "" ]
I have table that has 3 columns. I want to select data by list of data. ``` Table 1 key1 key2 value 12 A 100 15 A 150 17 C 56 13 D 600 12 C 100 10 B 80 ``` I have this list as key to select: ``` key1 key2 12 A 17 ...
It's unclear to me what you mean with "list of data", but if those are two tables, you can do: ``` select value from table1 where (key1, key2) in (select key1, key2 from table2); ``` You can also supply the values directly: ``` select value from table1 where (key1, key2) in ( (12,'A'), (17,'C'...
There's no meaning for 'list of data' in SQL. But if you want to display the result that you mentioned above. Use this code- Select value from Table 1 Where (key1,key2) in ((12,'A'), (17,'C'),(13,'D')) ;
How to select row of data by list of data
[ "", "sql", "postgresql", "" ]
I have 3 tables, `persons`, `companies` and `tasks`. Persons make different tasks in different companies. What I want is a list of ALL the persons table, the last task they have in tasks and the name of the company when they do that task. The most recent task could be the newest task\_date or the higher id.tasks, it ...
The solution is in the `LEFT JOIN`, but you need to first join the sub query, and only then the `tasks` table, otherwise you get too many results (I also fixed some typos in your query): ``` SELECT p.id persons_id, p.name persons_name, c.company_name FROM persons p LEFT JOIN ( SELECT id_...
What you should do is make the latest task/company data an inline view, then do a left join to that from the person table. ``` SELECT * FROM persons p LEFT JOIN ( SELECT * FROM tasks t INNER JOIN companies c ON c.id = t.companies.id WHERE t.id IN (SELECT max(id) FROM tasks GROUP BY id_persons) ) combined_t...
Join 3 tables, LIMIT 1 on second table
[ "", "mysql", "sql", "" ]
Is there a way to group and sum columns based on a condition? ``` id | code | total | to_update 1 | A1001 | 2 | 0 2 | B2001 | 1 | 1 3 | A1001 | 5 | 1 4 | A1001 | 3 | 0 5 | A1001 | 2 | 0 6 | B2001 | 1 | 0 7 | C2001 | 11 | 0 8 | C2001 | 20 | 0 ``` In thi...
You need to have a subquery that gives you all codes that have at least 1 record where update=1 and you need to join this back to your table and do the group by and sum: ``` select m.code, sum(total) from mytable m inner join (select distinct code from mytable where `to_update`=1) t on m.code=t.code group by m.code ``...
You could do it like this: ``` SELECT code, SUM(total) AS total FROM mytable GROUP BY code HAVING MAX(to_update) = 1 ``` This assumes that the possible values of *to\_update* are 0 or 1. Implemented in this [fiddle](http://sqlfiddle.com/#!9/0d81f/1), which outputs the result as requested in the question. As...
Mysql group and sum based on condition
[ "", "mysql", "sql", "" ]
I'd like to update an existing table to have a unique, auto-generated int field. How can I do this in entity framework (code first)? --- Longer explanation: A client would like for each record in a table to have a unique identifier as a reference number for other databases/bookkeeping. Ordinarily I would simply use ...
To solve this issue I ended up writing a script to copy everything in the table so that they were all given new ID's. I then moved any foreign keys from the original record to the copy. Then, I deleted the originals. In this convoluted fashion I was able to alter all the ID's to something less proprietary, and could t...
There is nothing native to EF, but you can be [generate unique values for using guid's](https://stackoverflow.com/questions/12012736/entity-framework-code-first-using-guid-as-identity-with-another-identity-column) for property (populated using NEWID() T-SQL function). Additionally, you could also create a new [SEQUENC...
Updating a table to have a unique, generated int (that is not the primary key)
[ "", "sql", "sql-server", "entity-framework", "ef-code-first", "entity-framework-migrations", "" ]
How can I pad an integer with zeros on the left (lpad) and padding a decimal after decimal separator with zeros on the right (rpad). For example: If I have 5.95 I want to get 00005950 (without separator).
If you want the value up to thousandths but no more of the decimal part then you can multiply by 1000 and either `FLOOR` or use `TRUNC`. Like this: ``` SELECT TO_CHAR( TRUNC( value * 1000 ), '00000009' ) FROM table_name; ``` or: ``` SELECT LPAD( TRUNC( value * 1000 ), 8, '0' ) FROM table_name; ``` Using `TO_CHA...
How about multiplication and `lpad()`: ``` select lpad(col * 1000, 8, '0') . . . ```
How to pad zeroes for a number field?
[ "", "sql", "oracle", "oracle-data-integrator", "" ]
I have a table that looks like the following but also has more columns that are not needed for this instance. ``` ID DATE Random -- -------- --------- 1 4/12/2015 2 2 4/15/2015 2 3 3/12/2015 2 4 9/16/2015 3 5 1/12/2015 3 6 2/12/2015 3 ``` ID is the primary k...
You can use `NOT EXISTS()` : ``` SELECT * FROM YourTable t WHERE NOT EXISTS(SELECT 1 FROM YourTable s WHERE s.random = t.random AND s.date > t.date) ``` This will select only those who doesn't have a bigger date for corresponding `random` value. Can also be done using `IN()` : ``...
This method will work in all versions of SQL as there are no vendor specifics (you'll need to format the dates using your vendor specific syntax) You can do this in two stages: **The first step is to work out the max date for each random:** ``` SELECT MAX(DateField) AS MaxDateField, Random FROM Example GROUP BY ...
SQL query with grouping and MAX
[ "", "sql", "" ]
here is my query: ``` SELECT COALESCE ([dbo].[RSA_BIRMINGHAM_1941$].TOS, [dbo].[RSA_CARDIFFREGUS_2911$].TOS,[dbo].[RSA_CASTLEMEAD_1941$].TOS, [dbo].[RSA_CHELMSFORD_1941$].TOS) AS [TOS Value] ,RSA_BIRMINGHAM_1941$.Percentage AS [Birmingham] ,RSA_CARDIFFREGUS_2911$.Percentage AS [Cardiff Regus] ,[db...
The results you get are as expected. This is because the joins are all relative to the first table. If there is a TOS in the second table that has no match with the first table that will generate a new record. If there is a TOS in the third table that has no match with the first table that will again generate a new rec...
Queries are so much easier to write and to read with table aliases. The problem is the matching in the second `FULL OUTER JOIN`. The `FROM` clause needs to look like this: ``` FROM [dbo].[RSA_BIRMINGHAM_1941$] b FULL OUTER JOIN [dbo].[RSA_CARDIFFREGUS_2911$] cr ON b.TOS = cr.TOS FULL OUTER JOIN [dbo].[R...
Values of FULL OUTER JOIN appearing in 2 different fields
[ "", "sql", "sql-server", "t-sql", "" ]
I need to improve the performance of a view. Unfortunately I can't use an index since I'm using "Top Percent" and randomness in my query. Here is the query used by the view ``` Select Top (10) Percent from Table Order By NEWID() ``` The view pulls the data in around 50 seconds which is too much. I hope you could hel...
There is no way to improve this given your requirements. Get more hardware - only solution. It is likely you overload tempdb - in which case a high performance SSD and proper configuration on that one may help. The reason is that in order to get the top 10 percent by your random order, SQL Server MUST process ALL rows...
For a truly random sample, you need some form of randomness. One method that doesn't require sorting is approximate, but might be sufficient for your purposes: ``` Select t.* from Table t where rand(checksum(newid()) <= 0.1; ``` This is approximate, of course. If you really needed *exactly* 10 percent, this approach ...
Improving view performance without using an Index
[ "", "sql", "sql-server", "" ]
I have a text which looks something like this `VENDOR CORPORATION (GA/ATL)`. I want to make it look like `Vendor Corporation (GA/ATL)`. So, I want to make only the first letter of every word upper case except those words which exists between `(` and `)`. I came across - `UPPER(LEFT(FIELD_NAME,1))+LOWER(SUBSTRING(FIEL...
Try to use [function](http://www.sql-server-helper.com/functions/initcap.aspx) like this: ``` BEGIN DECLARE @Index INT DECLARE @Char CHAR(1) DECLARE @PrevChar CHAR(1) DECLARE @OutputString VARCHAR(255) SET @OutputString = LOWER(@InputString) SET @Index = 1 WHILE @Index <= LEN(@InputString...
Using the Jeff Moden splitter (which can be found here. <http://www.sqlservercentral.com/articles/Tally+Table/72993/>) this can be accomplished. You then need to use a cross tab, also known as a conditional aggregate to put the piece back together. You could also do this with a PIVOT but I find the cross tab less obtus...
Making first letter of every word upper case with a condition
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I have been having issues switching to an offline version of the Lahman SQL baseball database. I was using a terminal embed into an EDX course. This command runs fine on the web terminal: ``` SELECT concat(m.nameFirst,concat(" ",m.nameLast)) as Player, p.IPOuts/3 as IP, p.W,p.L,p.H,p.BB,p.ER,p.SV,p.SO as K, ...
In 5.7 the sqlmode is set by default to: ``` ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION ``` To remove the clause ONLY\_FULL\_GROUP\_BY you can do this: ``` SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); ``` This supposed you need to make that GROUP BY with...
The accepted solution above didn't work for me on version `5.7.9, for osx10.9 (x86_64)`. Then the following worked - ``` set global sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'; ```
Error Code: 1055 incompatible with sql_mode=only_full_group_by
[ "", "mysql", "sql", "mysql-workbench", "mysql-error-1055", "" ]
I have the below query that shows me the records in Oracle that are not `null` but some of the records contain spaces such as '',' ', etc. How can I modify the query so it will ignore empty spaces? ``` select * from table where field1 is not null ``` Many Thanks.
## You should use trim or replace function e.g. 1. ``` select * from table where field1 is not null and trim(field1) != '' ; ``` 2. ``` select * from table where field1 is not null and replace(field1,' ') ; ``` p.s null is not empty data ! it is unknown.
If you problem is empty or extra space you can do something like this.. ``` select * from table where replace(field1,' ','') is not null ```
Not Null - Spaces on field
[ "", "sql", "oracle", "" ]
I'm new to PL/SQL and I'm trying to learn it as fast as I can. I was trying to do a simple SELECT but I came across this error. Although I know what it means, I really don't know how to solve the problem... This is my portion of code: ``` SELECT NVL(UPPER(T.COL1),'N.D.') COL1, V.SECO, 'N' CL_ME...
To make a grouping of a complex function that the one you have, I always make a subselect. Thus, your query will become: ``` select child_query.stuff, child_query.flag_def_fui from ( select 'some-stuff' some_stuff, (case when v.col2 is null and v.seco in ('b090','b1...
The other answers give you two options and are both correct. Just to be clear, and to specifically answer your edited question, you have three options to work around the issue of not being able to reference aliased columns in the `GROUP BY`: 1) [Answer 1: Wrap your query](https://stackoverflow.com/a/36182347/8432) so ...
ORA-00904 - Invalid Identifier
[ "", "sql", "oracle", "" ]
I have a two unbound textboxes in a Form where the user sets the start and end dates for query. The user than hits a button to generate report. Everything works except Access pops up a Dialog Box asking for the start and stop dates even though the variables myStartDate and myEndDate have proper values. I suspect I am...
You need to escape the string to use these variables. What you want is: ``` whereString = "LabDate Between #" & myStartDate & "# AND #" & myEndDate & "#" ```
If you (and I guess so) have applied a *date* format to the two textboxes, you don't need most of the converting, but you must pass formatted string expression for the date values to the SQL code: ``` Private Sub PrintReport_Click() Dim myForm As Form Dim myTextBox As TextBox Dim myStartDate As String ...
VBA not recognizing Value of Unbound Textbox for Query
[ "", "sql", "vba", "ms-access", "" ]
I checked many posts with related questions, but couldnt find an answer. I have 2 tables which have a one to many relationship. One is customers and the other one is projects. One customer can have many projects. their PK and FK are customer.customer\_id and project\_customer\_id. Now when I use the following SQL ``...
Since you are only concerned with the count of projects "if I understood correctly from your question", either create a function to get you this count, or write a sub query like the example below... ``` SELECT *, ( SELECT COUNT(project.project_id) from project WHERE project.customer_id = ...
Use this query: ``` SELECT *, COUNT(project.project_id) AS totalProjects FROM `customer` LEFT JOIN `project` ON `project`.`project_customer_id` = `customer`.`customer_id` GROUP BY `customer`.`customer_id` ORDER BY `customer`.`date_created` DESC ```
SQL join get results that have no join aswell
[ "", "mysql", "sql", "join", "" ]
Good day developers! [![Image 1](https://i.stack.imgur.com/PMB0M.png)](https://i.stack.imgur.com/PMB0M.png) I have this table JOBS and i wanted to get the latest record of every department. As you can see, there is only 2 department. The output row should be ID's # **1 and 6** I tried using this ``` SELECT j.id, j...
One solution using `subquery`: ``` SELECT j.id, j.title, j.department_id, j.date_created FROM JOBS j WHERE (department_id, Date) IN (SELECT department_id, MAX(date_created) FROM JOBS WHERE department_id = j.department_id) ``` This can also be rewritten as a `JOIN`.
Use `IN()` : ``` SELECT j.id, j.title, j.department_id, j.date_created FROM JOBS j WHERE (date_created,department_id) IN (SELECT MAX(Date),department_id FROM group by department_id) ``` Or `NOT EXISTS()` : ``` SELECT * FROM JOBS t WHERE NOT EXISTS(SELECT 1 FROM JOBS s ...
Getting latest record on every department
[ "", "mysql", "sql", "" ]
I'm trying to merge tables where rows correspond to a many:1 relationship with "real" things. I'm writing a blackjack simulator that stores game history in a database with a new set of tables generated each run. The tables are really more like templates, since each game gets its own set of the 3 mutable tables (player...
I think you're not using PostgreSQL the way it's intended to be used, plus your table design may not be suitable for what you want to achieve. Whilst it was difficult to understand what you want your solution to achieve, I wrote this, which seems to solve everything you want using a handful of tables only, and function...
Wouldn't using the UNION operator work? For the hands relation: ``` SELECT * FROM hands_first UNION ALL SELECT * FROM hands_second ``` For the matches relation: ``` SELECT * FROM matches_first UNION ALL SELECT * FROM matches_second ``` As a more long term solution I'd consider restructuring the DB because it will ...
Merging Complicated Tables
[ "", "sql", "database", "postgresql", "merge", "" ]
I need to find out the names of the students who have enrolled in *at least* two courses. Creating the two tables: ``` CREATE TABLE Student ( StudentID varchar(20) PRIMARY KEY, FirstName varchar(15), LastName varchar(30), Sex varchar(6), DOB date, Email varchar(40) ); CREATE TABLE Enrols ( StudentID va...
``` SELECT Student.FirstName AS "First Name", Student.LastName AS "Last Name", Enrols.CourseID AS "Course ID", COUNT(Student.FirstName) AS "Number of Names" FROM Student INNER JOIN Enrols ON Student.StudentID = Enrols.StudentID GROUP BY Student.FirstName HAVING COUNT(Student.FirstName) >= 2; ``` W...
You should use `HAVING` and `GROUP BY` (but not the curseID if you use group by) ``` SELECT Student.FirstName AS "First Name", Student.LastName AS "Last Name", COUNT (*) AS "Number of Names" FROM Student INNER JOIN Enrols ON Student.StudentID = Enrols.StudentID HAVING COUNT(Student.Firstname) >...
SELECT from One Table an Element that Occurs Multiple Times in Another Table
[ "", "mysql", "sql", "inner-join", "" ]
I have a self-referencing table: there's an ID and a PARENTID column that allows the records to be ordered into a hierarchical structure (let's call them record hierarchies). There's also a query (let's call it 'Query A') that returns a list of records from this table. Some of the returned records are 'root records' (...
One of possible solutions: ``` declare @TableA table ( ID int, ParentID int NULL, Name varchar(100) ) insert into @TableA(ID, ParentID, Name) values (1, NULL, 'root 1'), (2, NULL, 'root 2'), (3, 2, 'node 3->2'), (4, 1, 'node 4->1'), (5, 4, 'node 5->4->1'), (6, 3, 'node 6->3->2'), (7, 4, 'node 7->4->1'), (8, 7, ...
If you want to retrieve `Root` Item of each item then you can use the following approach : ``` select t1.*,(case when t1.PARENTID is null then t1.ID else t1.PARENTID end ) Id_Root , 0 IsTraced into #tmp from TableName t1 left outer join TableName t2 on t1.ID=t1.PARENTID order by t1.PARENTID while exists(select TOP 1...
Getting 'root records' from self-referencing table
[ "", "sql", "sql-server", "hierarchical-data", "recursive-query", "" ]
I want to pull all the unique IDs for particular rows with the same username and then display each result as a row. For example... Here's my table: ``` +----+------+ | id | name | +----+------+ | 1 | Joe | | 2 | Amy | | 3 | Joe | | 4 | Amy | | 5 | Joe | | 6 | Amy | +----+------+ ``` Here's the result I ...
Use a [`GROUP_CONCAT()`](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat) with `DISTINCT` clause to aggregate unique ids for a particular name: ``` SELECT name, GROUP_CONCAT(DISTINCT id SEPARATOR ',') AS ids FROM yourtable GROUP BY name ``` To review the usage of it also see [MySQ...
You can use [group\_concat](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat) for that: ``` SELECT name, GROUP_CONCAT(id) AS ids FROM table GROUP BY name ``` You can also specify a separator, but the one by default is the comma. You can also specify `DISTINCT`, but since *id...
In MySQL How do I SELECT all ids from rows with a similar value
[ "", "mysql", "sql", "select", "" ]
In SQL Server Management Studio I went to Generate Scripts and create an INSERT script which looks like the following: ``` SET IDENTITY_INSERT [dbo].[Product] ON GO INSERT [dbo].[Product] ([Id], [Name]) VALUES (1, N'Product 1') GO INSERT [dbo].[Product] ([Id], [Name]) VALUES (2, N'Product 2') GO INSERT [dbo].[Product...
Why not do all the inserts in one step? ``` INSERT [dbo].[Product] ([Id], [Name]) SELECT id, name FROM (VALUES (1, N'Product 1'), (2, N'Product 2') (3, N'Product 3') ) v(Id, Name) WHERE NOT EXISTS (SELECT 1 FROM Product P2 WHERE p2.id = v.id); ```
``` SET IDENTITY_INSERT [dbo].[Product] ON GO INSERT [dbo].[Product] ([Id], [Name]) select id,name from products t where not exists(select 1 from products t2 where t2.id=t1.id and t2.name=t1.name GO SET IDENTITY_INSERT [dbo].[Product] OFF ```
Creating a SQL Script that inserts several items into a table but checking if each exist first
[ "", "sql", "sql-server", "ssms", "" ]
So let's say I have a table like ``` Table 1 ============= id | ... ============= 1 | ... 2 | ... 3 | ... . . . . . . Table 2 ======================= id | table1_id | ... ======================= 1 | 1 | ... 2 | 1 | ... 3 | 2 | ... . . . . ...
Insert a dummy entry with copy of id 1 row in [Table 1] with new id. Then update all columns of id 1 with id 2 with following query ``` UPDATE T SET T.col2 = S.col2 ,T.col3 = S.col3 ,T.col4 = S.col4 . = . . = . . = . [Table 1] T CROSS JOIN ( SELECT col2 ,col3 ...
I would create a temporary entry with a new id in Table 1, move the references in Table 2 from `table1_id=1` to the new id, move `table1_id=2` to `table_1_id=1` and then move the temporary referencves to `table1_id=2`.
How can I safely swap the ids of two rows that are references in other tables?
[ "", "sql", "sql-server", "t-sql", "" ]
Essentially, I have two tables: Table A ``` aId|isOne|bId ---+-----+--- 1 |1 |2 2 |0 |2 3 |1 |1 ``` Table B ``` bId|one|two ---+---+--- 1 |5 |13 2 |3 |11 ``` Table A refers to Table B and specifies whether the data of `one` or of `two` is desired. What I need to do is sum the values given the `bId...
I was actually able to solve this by simply replacing the arbitrary `bId` within the subqueries with a specified value of `tableA.bId`, for anyone curious of an answer.
I would simply inner join the 2 tables and use case statement within the sum() to sum the right values: ``` select tableA.bId, sum(case when isOne=0 then two when isOne=1 then one else 0 end) as val from tableA inner join tableB on tableA.bId = tableB.bId group by tableA.bId ; ```
Apply Group By to If Statement Results
[ "", "mysql", "sql", "" ]
``` SELECT salesman_id, COUNT(sale_id) FROM Commission GROUP BY salesman_id HAVING salesman_id IN (select... *subqueries* ``` COUNT(sale\_id) gives me the number of sale\_ids **regardless of the subqueries**, although i want the number of sale\_ids **after** the subqueries are done. how come this i...
If you want to limit the results that your query deals with then you need to do that in the `WHERE` clause. The `HAVING` clause is filtering that happens **after** aggregates have been performed. Try moving your subqueries to the `WHERE` clause instead.
Try this: ``` SELECT salesman_id, COUNT(sale_id) FROM Commission WHERE salesman_id IN (select... *subqueries*) GROUP BY salesman_id ```
getting the COUNT value depending on the subqueries
[ "", "mysql", "sql", "database", "" ]
I have this function that I found here: [Insert trigger to Update another table using PostgreSQL](https://stackoverflow.com/questions/12343984/insert-trigger-to-update-another-table-using-postgresql) ``` CREATE TABLE table1 ( id integer NOT NULL, name character varying, CONSTRAINT table1_pkey PRIMARY KEY (id) )...
To support `UPDATE` you can do this: Trigger: ``` CREATE TRIGGER trig_copy AFTER INSERT OR UPDATE ON table1 FOR EACH ROW EXECUTE PROCEDURE function_copy(); ``` Function: ``` CREATE OR REPLACE FUNCTION function_copy() RETURNS TRIGGER AS $BODY$ BEGIN if TG_OP='INSERT' then INSERT INTO table2...
``` create or replace trigger trig_copy after insert or update on table1 begin merge into table2 t2 using ( select id, name from table1 t1) t_new on (t2.id = t_new.id) when matched then update set t2.name = t_new.name ...
How to create function that updates changes in one table from another table?
[ "", "sql", "postgresql", "" ]
I need to write a Delphi 7 and mysql database query which would return the records including ALL words in the submitted name. So query will return records which has all those name words but can have different order. For example, if search string is John Michael Smith, query should be able to return records with names ...
Instead of replacing spaces with `%`, you could replace them with `% AND P_Name LIKE %`: ``` mask:='''WHERE (P_Name LIKE %'+StringReplace(Edit1.text,' ','% AND P_Name LIKE %',[rfReplaceAll, rfIgnoreCase])+'%)'''; ``` Apologies if there is some problem with the syntax (I don't know Delphi), but if `Edit1.text:= 'John ...
You can build table of words dynamically. To find yours match do query that join both tables in possible match, and by grouping results test it - is name have all of words, try this: ``` WITH words AS (SELECT 'John' AS word FROM dual union SELECT 'Michael' FROM dual union SELECT 'Smith' FROM dual ) , ...
Query to Search All possible words
[ "", "mysql", "sql", "delphi", "search", "" ]
I have an Oracle table with "users" in it, and a table with "events" related to users, date-stamped as to when each event took place. I'd like to produce a simple table showing each user and the **most recent event** that took place, but I can't quite work out the nested query or aggregation function to do this, since ...
This may be simplest using a correlated subquery: ``` select u.*, (select e.status from events e where e.user_id = u.user_id order by e.event_date desc limit 1 ) as Most_Recent_Status from users u; ``` This saves the trouble of aggregation (or equivalently `select distinc...
Here is an sql query: ``` select U.user_name, E.event_status from users U, events E where U.user_id = E.user_id and (E.user_id, E.event_date) = (select distinct user_id, max(event_date) from events ...
Oracle - Join tables using aggregated function?
[ "", "sql", "oracle", "" ]
I have wrote query like this to check json column has key ``` SELECT * FROM "details" where ("data"->'country'->'state'->>'city') is not null; ``` How can we write query which will select row if "data" contains "city" JSON structure of data is not consistent.
You can check the **top-level** keys of `data` with `?` as it is said in the [documentation](http://www.postgresql.org/docs/9.5/static/functions-json.html). For example ``` SELECT * FROM details WHERE data ? 'city'; ``` Checking every key in all nested objects from the json column requires a recursive [CTE](http://w...
You can use `?`: ``` SELECT * FROM "details" WHERE data->'country'->'state' ? 'city'; ```
Postgresql JSON column check key exists
[ "", "sql", "json", "postgresql", "" ]
I'm having trouble identifying all the querystring parameters that are used on a site. I want to write a T-SQL query that extracts all parameters and counts them, but I don't have permission to write SQL functions, so [this solution](https://stackoverflow.com/a/10083023/896802) isn't much help. The field that I'm work...
You can borrow one of the functions [from here](http://sqlperformance.com/2012/07/t-sql-queries/split-strings) and just inline it into the query. An example below. I would not expect good performance. Creating a CLR function is by far the most efficient way of splitting strings prior to SQL Server 2016. ``` DECLARE @...
More sexy way to approach that: ``` DECLARE @xml xml ;WITH cte AS ( SELECT * FROM (VALUES ('_=1457999955221'), ('tab=profile'), ('tab=tags&sort=votes&page=13'), ('page=5&sort=newest&pagesize=15') ) as T(Query)) SELECT @xml = ( SELECT CAST( ( SELECT '<d><param>' + REPLACE(REPLACE((STUFF(( SELECT '/' + REPLACE(REPLAC...
How to extract URL querystring parameters in SQL Server without writing a function?
[ "", "sql", "sql-server", "string", "query-string", "" ]
I need to add records/rows to an existing table, based on values of a couple fields. The rows are basically the range of months for each different id - most id's will have multiple months but some only one month. I have a first\_date field and a last\_date field and need to fill in rows for however intervening months ...
If you are using for summary you can use FREQ total\_months; in most procs or in proc freq is it WEIGHT. I you really need to expand I think this will suffice. ``` data expand; set <data-name>; do time_id = 1 to total_months; output; end; run; ```
What I think you're going to need is an additional table, a dimension or mapping table, that will give you information on those dates/months. Think you can then join on it a few times to get your complete list. Here's what I did: ``` CREATE TABLE #tblCurrent (ID INT, First_Date VARCHAR(9), Last_Date VARCHA...
Using sas or sql add new records to table based on monthly date variables
[ "", "sql", "insert", "sas", "rows", "" ]
I have a table which stores a `ID`, `Name`, `Code`, `IPLow`, `IPHigh` such as: ``` 1, Lucas, 804645, 192.130.1.1, 192.130.1.254 2, Maria, 222255, 192.168.2.1, 192.168.2.254 3, Julia, 123456, 192.150.3.1, 192.150.3.254 ``` Now, if I have an IP address `192.168.2.50`, how can I retrieve the matching record? **Edit** ...
Painfully. SQL Server has lousy string manipulation functions. It does, however, offer `parsename()`. This approach converts the IP address to a large decimal value for the comparison: ``` select t.* from (select t.*, (cast(parsename(iplow, 4)*1000000000.0 as decimal(12, 0)) + cast(parsename...
Try this simple way checking range ``` DECLARE @IP NVARCHAR(30)='192.168.500.1' SELECT * FROM Branches WHERE CAST (PARSENAME(@IP,4) AS INT)>=CAST(PARSENAME(IPLow,4) AS INT) AND CAST(PARSENAME(@IP,3) AS INT)>=CAST(PARSENAME(IPLow,3) AS INT) AND CAST(PARSENAME(@IP,2) AS INT)>=CAST(PARSENAME(IPLow,2) AS INT) AND CAST(...
Select record between two IP ranges
[ "", "sql", "sql-server", "" ]
I want to know what is the easiest way to extract number from character which representing percentage. For example, I have ``` name, rate Google, 10% Google, 20% Uber, 25% ... ``` I want a query that return the average rate group by name ``` Google, 15% Uber, 25% ```
I'm a fan of regular expressions, but you don't need it in this case, here's an alternative using native functions, with your sample data: ``` WITH nameandrate AS ( SELECT 'Google, 10%' AS namerate UNION ALL SELECT 'Google, 20%' AS namerate UNION ALL SELECT 'Uber, 25%' AS namerate ), split1 AS ( SELECT n...
You can use this Regex for Extracting; ``` ([a-z]+\,[\s]*[\d]+\%) ``` use `InCaseSensitive` Comparison. You can refer these links for how to use Regex in Sql: [Regular Expressions in MS SQL Server 2005/2008](http://www.codeproject.com/Articles/42764/Regular-Expressions-in-MS-SQL-Server) [Create and Run a CLR SQL S...
extract number from character string in sql and perform calculation
[ "", "sql", "regex", "" ]
From a select query I have the result something like this: ``` IdCompany | IdUser | ComapnyName | JobTitle 1 100 Company1 Developer 2 100 Company2 Developer 3 200 Company3 Developer 4 200 Company4 Developer 5 200 Company5 ...
A typical way of doing this uses the ANSI standard window function`row_number()`: ``` select t.* from (select t.*, row_number() over (partition by idUser order by idUser) as seqnum from t ) t where seqnum = 1; ```
You could try this: ``` select * from TABLE group by ´IdCompany´ ```
Don't get a duplicated record on SQL
[ "", "sql", "greatest-n-per-group", "" ]
I have a table called "seekers" which contains a list of people. There is a column called "username" which contains the usernames of the people and a column called "resume\_status" which either has a value of 0 or 1. Currently the the query below does not check the "seekers" table at all. I would like it to only displ...
@Brijesh's answer is good but I think this will be faster -- it will also improve with addition of one index on the seekers table and we want username indexes on the other tables. .. ``` SELECT * FROM ( SELECT a.username, MATCH(a.highlight) AGAINST (\"{$keywords}\" IN BOOLEAN MODE) AS score FROM resume_highlight...
Use below query to sortout ``` SELECT A.username, A.score FROM ( (SELECT username, MATCH(highlight) AGAINST (\"{$keywords}\" IN BOOLEAN MODE) AS score FROM resume_highlights HAVING score>0 ORDER by score desc) UNION ALL (SELECT username, MATCH(skill,skill_list) AGAINST (\"{$keywords}\" IN BOOLEAN MODE) AS ...
WHERE clause after UNION ALL
[ "", "mysql", "sql", "" ]
Basically at current i have some script that allows my users to see all distinct values of 'make' which shows the distinct values of a b c ect. But under each of make there is another column which is models. i would like to be abel to select all distinct values of the models column where the make column is equal to a c...
``` SELECT DISTINCT model FROM table_name WHERE make = 146; ``` Regards
You can do it with simple `distinct` query, e.g.: ``` select distinct model from table where make = '<make>' ```
selecting a distinct value of column 2 where column one is equal to a certain value
[ "", "mysql", "sql", "sql-server", "web", "" ]
I have three tables- A, B, and C that each contain a list of active customers for 2012, 2013 and 2014, respecitvely. I want to get a list of customers who were active in all three years. I am doing it this way: ``` select distinct customer_id from table_A a inner join table_B b on a.customer_id=b.customer_id inner joi...
The order of joins for `inner join` does not make a difference. However, if one of the tables is a "master" table with one row per `customer_id`, then it is more efficient to do: ``` select a.customer_id from table_A a where exists (select 1 from table_B b where a.customer_id = b.customer_id) and exists (select...
No, because you are doing an inner join. Inner joins are an intersection, so only id's that are in all 3 are going to make it through, no matter what order you put the joins together. If you do an outer join, you have to worry more about order.
Inner join Order
[ "", "mysql", "sql", "teradata", "proc", "" ]
I really would like this help. I have two tables lets say t1 and t2. I want update t1 based on value obtain from t2. There is common fields between t1 and t2 which is t1.username = t2.emaiAddress. Is there a way to update t1.username? Below is the t1 and t2 structure ``` create table t1 ( username varch...
This would typically be done using a subquery in Oracle: ``` UPDATE t1 SET username = 'john@gmail.com' WHERE EXISTS (SELECT 1 FROM t2 WHERE t1.username = t2.EMAILADDRESS AND t2.id = 'SCM-026020' ); ```
Let's assume in table t1 there is a record where the username='mary@gmail.com'. And you need to update this username with the email address from t2 where the ID = 'SCM-026020'. Try below query. ``` UPDATE t1 SET t1.username = (SELECT emailAddress FROM t2 WHERE ID = 'SCM-026020')...
Updating a table column based on another table field
[ "", "sql", "oracle", "oracle11g", "" ]
I'm using Oracle 11g database which contains data where in I want to replace a dynamically generated text with a dummy text using a oracle query. For e.g my column in table contain data : `Hello Mike, Your registered no. is 3525. Kindly check the same` . Now the issue is, Name of customer i.e. 'Mike' can be dynamic th...
If the only dynamic part of you string is the name ( and assuming that names do not contain numbers...) you can try: ``` select regexp_replace('Hello Mike, Your registered no. is 3525. Kindly check the same', '([0-9])', 'X' ) from dual ``` This simply r...
You could use **TRANSLATE** which would be much faster than **REGULAR EXPRESSION**. It would simply any occurrence of a number with `X`. For example, ``` SQL> SELECT TRANSLATE('Hello Mike, Your registered no. is 3525. Kindly check the same', 2 '0123456789', 3 'XXXXXXXXXX') str ...
Replace a dynamically created Substring in Oracle query
[ "", "sql", "oracle", "oracle11g", "" ]
I'd like to pick the brains of any sql expert who can tell me how I can select the distinct values from a field and then add a unique ID to each set of distinct values. I can write a quick bit of code to do this but I need it in a query. Important to add that I need the unique value to start at 1 (otherwise yes I know ...
The simplest way in MySQL is to use variables: ``` select p.Patient_ID, (@rn := if(@p = p.Patient_ID, @rn, if(@p := p.Patient_ID, @rn + 1, @rn + 1) ) ) as New_Unique_Value from t cross join (select @rn := 0, @p := -1) params order by patient_id; ```
My solution using a temporary table ``` CREATE TABLE IF NOT EXISTS OAK_origres.TEMP2 (PATID INTEGER, NEWID INTEGER AUTO_INCREMENT, PRIMARY KEY (NEWID)); INSERT INTO OAK_origres.TEMP2 (PATID) SELECT DISTINCT OAK_origres.`Original Results`.`Patient ID` FROM OAK_origres.`Original Results` INNER JOIN OAK_patient.Demogr...
mySQL select distinct and add unique value
[ "", "mysql", "sql", "" ]
Having a bit of trouble with a basic SQL problem. The question is that I have to find the salespersons first and last name, then their Social Insurance Number, the product description, the product price, and quantity sold where the total quantity sold is greater than 5. I'll attach the database information below as a...
Product quantity sold greater than 5 ``` SELECT ProductId FROM ProductsSales HAVING SUM(QuantitySold) > 5 ``` Use that to get the rest: ``` SELECT s.FirstName, s.LastName, s.SIN, p.ProductDescription, ps.UnitSalesPrice, ps.QuantitySold FROM ProductsSales ps LEFT JOIN Products p on p.ProductID = ps.ProductID LEFT JO...
``` SELECT a.FirstName, a.LastName, a.SIN, c.ProductDescription, b.UnitSalesPrice, b.QuantitySold FROM Salesmen a LEFT JOIN ProductsSales b ON a.SalesmanId = b.SellerId LEFT JOIN Products c ON b.ProductId = c.ProductId WHERE b.QuantitySold > 5 ```
Basic SQL Joining Tables
[ "", "sql", "" ]
I have one table with cars, and another table with fuel types. A third table tracks which cars can use which fuel types. I need to select all data for all cars, including which fuel types they can use: Car table has Car\_ID, Car\_Name, etc Fuel table has Fuel\_ID, Fuel\_Name Car\_Fuel table has Car\_ID, Fuel\_ID (on...
Presumably you have no duplicates in `Car_fuel`, so you don't need aggregation. Hence you can do: ``` SELECT c.*, ISNULL((SELECT TOP 1 1 FROM Car_Fuel f WHERE f.Car_ID = c.Car_ID AND f.Fuel_ID = 1), 0) AS Can_Use_Gas ISNULL((SELECT TOP 1 1 FROM Car_Fuel f WHERE f.Car_ID = c.Car_ID AND f.Fuel_ID = 2), 0) ...
Although not a perfect solution, you could use the [pivot clause](https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx): ``` select * from ( select car_name, fuel_name from Car inner join Car_Fuel on Car.car_id = Car_Fuel.car_id inner join Fuel on Car_Fuel...
"If one-to-many table has value" as column in SELECT
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Practicing some SQL, we have to get the name of the employees whose salary is the greatest of his department. But if in any department there were more than one employer with the greatest salary, we would not have to consider that department. We got the first part but not the second one (because there are two employees...
``` SELECT ename, sal, deptno FROM emp a WHERE not exists ( SELECT * FROM emp WHERE deptno=a.deptno and sal >= a.sal and ename != a.ename) ORDER BY sal; ```
``` with cte as ( SELECT ename, sal, deptno , row_number() over (partition by deptno order by sal desc) as rn FROM emp ) select ename, sal, deptno from cte where rn = 1 except select ename, sal, deptno from cte where rn = 2 order by sal ``` if this does not work in oracle - it used to be also ta...
SQL select rows without duplicates
[ "", "sql", "oracle", "" ]
I have a simple SQL statement to create a table like this: ``` Create table tblAccountBalance ( Id int, AccountName nvarchar(200), Balance int ) insert into tblAccountBalance values (1, 'Mark', 1000); insert into tblAccountBalance values (2, 'Mary', 1000); ``` Resulting in ``` Id AccountName Balance ---...
It is because your second experiment is actually successful and executed. When there is a operation that compare 2 different data types, SQL Server will perform implicit conversion.Refer to [Data Type Precedence](https://msdn.microsoft.com/en-us/library/ms190309.aspx) for more details. So there is conversion of your `i...
Your second transaction is successful that's why the `UPDATE` was still executed. The `UPDATE` statement that you changed: ``` update tblAccountBalance set Balance = Balance + 100 where Id = '24' --note the Id here is changed ``` did not cause any error. It simply did not return any rows with `Id = '24'`, but without...
SQL Server Transaction successful with wrong Id
[ "", "sql", "sql-server", "transactions", "sql-server-2014", "" ]
I have a table, **testing**, with the attributes: **id**, **fruits**. We have the following contents in said table: ``` id, fruits 1, Apple 2, Banana 3, Apple ``` I would like a query that groups these by the fruits (Apples in one group, Bananas in another) and returns if there is more than 1 in that group. So, fo...
You can use a subquery to find the duplicates, and an outer query that gets your rows; ``` SELECT * FROM testing WHERE fruits IN ( SELECT fruits FROM testing GROUP BY fruits HAVING COUNT(*)>1 ) ORDER BY id ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!9/130e7/2).
Actually, the most efficient way to do this is probably to use `exists`: ``` select t.* from testing t where exists (select 1 from testing t2 where t2.fruits = t.fruits and t2.id <> t.id ); ``` For optimal performance, you want an index on `testing(fruits, id)`.
SQL Group by attribute and show results if there is more than one in that group
[ "", "mysql", "sql", "" ]
I am looking for someone to help by updating this sql statement, as I want to join two tables but without using " ON AD.[UID] = UI.[UID] " ? ``` SELECT AD.[AdsID] ,AD.[UID] ,AD.[Section] ,AD.[Category] ,AD.[Country] ,AD.[State] ,AD.[City] ,SUBSTRING([AdsTit],1,30)+'...' as AdsTit ,SUBSTRING([AdsDesc],1,85) as AdsDesc ...
You can move condition from 'on' to 'where', it works like inner join ``` SELECT AD.[AdsID] ,AD.[UID] ,AD.[Section] ,AD.[Category] ,AD.[Country] ,AD.[State] ,AD.[City] ,SUBSTRING([AdsTit],1,30)+'...' as AdsTit ,SUBSTRING([AdsDesc],1,85) as AdsDesc ,AD.[AdsPrice] ,AD.[Img1] ,AD.[Currency] ,AD.[Section] ,AD.[Currency] ,...
You can use the [`USING`](https://docs.oracle.com/javadb/10.6.1.0/ref/rrefsqljusing.html) keyword instead of `ON` in your SQL query or use a [natural join](http://www.w3resource.com/sql/joins/natural-join.php), which compares all the common columns in two tables itself without the on condition. Query for your tables l...
SQL Using join but without on Condition
[ "", "sql", "" ]
I'm totaly new in all database stuff. What I would like to do is save a list of movies that belongs to a user. For exemple the user "james" likes the following movies "james bond, matrix, the revenant, batman". I don't know how to assign this list of movies to the user "james", I don't know how to create my tables and ...
user table ``` id | user | other | email ``` movie table ``` id | name | year | etc ``` user\_movie (this is called a pivot table) ``` user_id | movie_id ``` pivot tables are fairly amazing. example ``` users id | name | details 3 | Hakim | xxxxxxx 4 ...
link the user id with the movie id It can be a third table PK, userid, movieid,
Assign a list of movie to an user
[ "", "mysql", "sql", "" ]
I executed this SQL statement in Postgres ``` alter table user modify column 'distinguishedName1' text; ``` and ``` alter table user modify column distinguishedName1 text; ``` * `user` is the table name * `distinguishedName1` is the column name with integer data type. I wanted to modify the data type to boolean or...
Try this: ``` ALTER TABLE "user" ALTER COLUMN distinguishedName1 TYPE text USING code::text; ``` or ``` ALTER TABLE "user" ALTER COLUMN distinguishedName1 TYPE text ``` Also do note that the USING is optional. See the [manual](http://www.postgresql.org/docs/current/static/sql-altertable.html) here: > The optional ...
`POSTGRES` syntax for altering column type : ``` ALTER TABLE user ALTER COLUMN distinguishedName1 TYPE text; ```
ERROR: syntax error at or near "modify" - in postgres
[ "", "sql", "postgresql", "ddl", "alter-table", "" ]
I'm struggling to create a SQL statement that returns both the parent and child records in a single query. These are my tables.... **COURSE** ``` COURSE_ID | COURSE_CODE ----------+------------ 912689 | AUS_COURSE 912389 | AUS_FH1 912769 | AUS_FH2 912528 | AUS_SSMOC1 912293 | AUS_UNIT1 912295 | AUS...
You can join the tables by using IN(child,parent) and distinct to drop the duplicates, like this: ``` SELECT distinct c.course_ID,c.course_code FROM COURSE c INNER JOIN COURSE_LINKS cl ON(c.course_ID in(cl.course_id_from,cl.course_id_to)) ```
I'd go for a subselect instead of a join. ``` select COURSE_ID, COURSE_CODE from COURSE where COURSE_ID in (select COURSE_ID_FROM from COURSE_LINKS) OR COURSE_ID in (select COURSE_ID_TO from COURSE_LINKS) ```
SQL join for parent and child records in a link table
[ "", "sql", "oracle", "join", "" ]
I have three tables with following data Table 3 : ``` Table1_id Table2_id 1 1 1 2 1 3 2 1 2 3 3 2 ``` Table 2 : ``` Table2_id Name 1 A 2 B 3 C ``` Table 1 : ``` Tabl...
Using `NOT IN` with excluding `LEFT JOIN` in a subselect with a `CROSS JOIN` ``` select * from table1 where Table1_id not in ( select t1.Table1_id from table1 t1 cross join table2 t2 left join table3 t3 using (Table1_id, Table2_id) where t3.Table1_id is null ) ``` VS using `COUNT()` ``` select ta...
You can use the following query: ``` SELECT DISTINCT t1.* FROM Table2 AS t2 CROSS JOIN Table1 AS t1 WHERE NOT EXISTS (SELECT 1 FROM Table3 AS t3 WHERE t1.Table1_id = t3.Table1_id AND t2.Table2_id = t3.Table2_id) ``` to get `Table1` records not having...
Returning ids of a table where all values of other table exist with this id using all() or exists()
[ "", "mysql", "sql", "database", "dbms-output", "" ]
I have a table ``` EmpId EmpName ManagerId Gender 1 Shahzad 2 M 2 Santosh 1 F 3 Sayanhi 2 M ``` By mistake 'M' is assigned to female employees and 'F' is assigned to male employees. So I need to write a query to make...
here is a simple solution that will fix both cases at once: ``` UPDATE Employee SET Gender = CASE Gender WHEN 'M' THEN 'F' WHEN 'F' THEN 'M' END ```
Try this instead: ``` SELECT empid, empname, CASE WHEN gender = 'M' THEN 'F' ELSE 'M' END AS Gender INTO #tmp FROM Employee ``` If you're happy with what you see in there, then: ``` UPDATE Employee SET Employee.Gender = #tmp.Gender FROM Employee INNER JOIN #tmp ON Employee.empid = #tmp...
Using more than two where clauses in the single update query in SQL Server
[ "", "sql", "sql-server", "" ]
Returns `45.2478` ``` SELECT CAST( geography::STPointFromText( 'POINT(-81.2545 44.1244)', 4326 ).Lat + 1.12342342 AS VARCHAR(50) ) ``` Returns `4.524782342440000e+001` ``` SELECT CONVERT( VARCHAR(50), geography::STPointFromText( 'POINT(-81.2545 44.1244)' , 4326 ).Lat + 1.1...
The [link](https://msdn.microsoft.com/en-us/library/ms187928.aspx) to the docs that you included in the question has an answer. `CAST` is the same as `CONVERT` without explicitly specifying the optional style parameter. > float and real Styles > > ``` > Value: 0 (default) > Output: A maximum of 6 digits. Use in scie...
It is due to the `style` part you mentioned in `CONVERT` function Your query with `style = 2` ``` SELECT CONVERT(VARCHAR(50),geography::STPointFromText('POINT(-81.2545 44.1244)',4326).Lat+1.1234234244,2) ``` **Result :** `4.524782342440000e+001` But when I remove the `Style` part from `Convert` function ``` SELECT...
Is this a casting bug in SQL Server 2016 RC0?
[ "", "sql", "sql-server", "sql-server-2016", "" ]
In SQL Server 2008, I want to get the list of columns (column names) that the Primary Key spans. I have tried ``` SELECT * FROM sys.key_constraints LEFT JOIN sysconstraints ON (sys.key_constraints.object_id = sysconstraints.constid) WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.permissioncache')...
Try this way `INFORMATION_SCHEMA` method ``` SELECT TC.TABLE_NAME, COLUMN_NAME, TC.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cc ON cc.Constraint_Name = tc.Constraint_Name AND cc.Table_Name ...
``` SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col ON Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name WHERE Constraint_Type = 'PRIMARY KEY' ``` and if you want to get the list of all prima...
Getting list of columns for a PK
[ "", "sql", "sql-server", "" ]
Can someone check what is wrong with this codes? I already check the other questions for reference but its still not working. [![enter image description here](https://i.stack.imgur.com/zD3nD.png)](https://i.stack.imgur.com/zD3nD.png) ``` declare @sourceTable varchar(500) declare @year varchar(22) declare @month varch...
You need dynamic query ``` SET @string2 = 'select convert(varchar(55),refdate)+''-''+convert(varchar(55),refcount) FROM ' + Quotename(@sourceTable) EXEC (@string2) ```
You are not declaring @sourcetable , the error shouts it loud and clear. Add this At the beginning : ``` declare @sourcetable varchar(50) ``` Also, I believe you need to use dynamic SQL for this sort of queries and variable using.
SQL Server: set 2 column into 1 variable from variable table
[ "", "sql", "sql-server", "" ]
i have a quick question please. I am trying to write a query that combines "NOT" and "AND" in MS access. But for some reason I am not getting the correct result. For example, if i have a table: ``` ID| Name1| Name2| 1 | a | a | 2 | b | b | 3 | a | | 4 | | a | 5 | a | b | 6...
Avoiding the NULLs by only using equality testing, applying deMorgan's laws: ``` SELECT * FROM Names WHERE NOT (Name1 = 'b' AND Name2 = 'b') ; ``` The idea is: conditions with `NULL` values never test true: `NULL = 'x'` is false, and `NULL <> 'x'` also is false. (even `NULL = NULL` is false!) In short: the condit...
Use parentheses to help break up bits of logic, and prefer `<>` over `NOT` ``` SELECT * FROM TABLE Names WHERE (Name1 <> 'b') OR (Name2 <> 'b') ``` You may have to coerce null values to get 3 and 4: ``` SELECT * FROM TABLE Names WHERE (NZ(Name1, "") <> 'b') OR (NZ(Name2, "") <> 'b') ```
Combining "NOT" and "AND" in SQL (MS Access specifically)
[ "", "sql", "ms-access", "" ]
So I'm counting activity records from users in my system. I get the activity counter for each day in a certain month and year, just like the query that follows ``` SELECT CONVERT(date, VIS_DATETIME) AS DATETIME, COUNT(*) AS ACTIVITY FROM ACTIVITY WHERE DATEPART(year, VIS_DATETIME) = 2016 AND DATEPART(month, VIS_...
Create a table that contains all dates. Then do a left join with the Activity table. Group on the date, and do a `COUNT` on Activity.id. The left join ensures that all dates from the date table are included in the result set, even if they are not matched in the join clause.
``` Declare @DayOfMonth TinyInt Set @DayOfMonth = 1 Declare @Month TinyInt Set @Month = 1 Declare @Year Integer Set @Year = 2016 Declare @startDate datetime Declare @endDate datetime -- ------------------------------------ Select @startDate = DateAdd(day, @DayOfMonth - 1, DateAdd(month, @Month - 1, ...
Get "zero" for a count at dates without records
[ "", "sql", "sql-server", "" ]
I am trying to get count value 0 if there are no rows that matches the condition. I have a big table. But, I am posting a truncated table as it explains what I want. Example Table1: ``` **name year title** name1 2008 title1 name2 2009 title2 name3 2010 title1 name1 2008 title2 name4 2009 ...
Try this: ``` select p.name, count(case when p.year=2008 then 1 end) as count from table1 p group by p.name ``` The query uses *conditional aggregation* so as to conditionally count `year=2008` occurrences of `p.name` values.
You could also do it using **DECODE**. Of course, **CASE** is pretty clear and verbose. ``` SELECT NAME, COUNT(DECODE(YEAR, 2008, 1)) COUNT FROM your_table GROUP BY NAME ORDER BY COUNT DESC; ``` For example, ``` SQL> WITH sample_data AS( 2 SELECT 'name1' NAME, 2008 YEAR FROM dual UNION ALL 3 SELECT 'nam...
How to get count(*) value 0 in select from where group by
[ "", "sql", "oracle", "" ]
Goal: Keep a running table of student class ranks each month of the year Haves: I have code that provides me with columns ``` StudentID; '+@DateTXT+' ``` The DateTXT is dynamic variable, returns whatever month I'm running the code in. Needs: I'm trying to use the MERGE, UPDATE, INSERT functions to where I can run t...
Change your ALTER TABLE to: ``` EXEC('ALTER TABLE StudentRanking ADD ' + @DateTXT + ' smallint NULL') ``` Assuming the down votes are because I didn't offer an alternative that was normalized, I'd recommend using PIVOT for this type of problem. Setup: ``` CREATE TABLE dbo.StudentRanking ( MonthID CHAR...
Always open for a different, better, approach @GarethD! I actually got it to work by doing: ``` EXEC('ALTER TABLE StudentRanking ADD ' + @Date_TXT + ' smallint DEFAULT(null)') WHEN MATCHED AND TARGET.' + @Date_TXT + ' IS NULL THEN UPDATE SET TARGET.' + @Date_TXT + ' = SOURCE.' + @Date_TXT + ' ```
MERGE, UPDATE, INSERT T-SQL Cannot INSERT value NULL
[ "", "sql", "sql-server", "merge", "null", "" ]
I'm trying to SET more than one value within the if else statement below, If I set one value it works, but if I set two values, it doesn't work: ``` DECLARE @test1 varchar(60); DECLARE @test2 varchar(60); IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10) SET @test1 = 'test1' SET @test2 = 'test2'...
If you have more than one statement in a if condition, you must use the `BEGIN ... END` block to encapsulate them. ``` IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10) BEGIN SET @test1 = 'test1' SET @test2 = 'test2' END ELSE BEGIN SET @test1 = 'testelse' SET @test2 = 'testelse' END ```
Use `BEGIN` and `END` to mark a multi-statement block of code, much like using `{` and `}` in other languages, in which you can place your multiple `SET` statements... ``` IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10) BEGIN SET @test1 = 'test1' SET @test2 = 'test2' END ELSE BEGIN S...
How to set multiple values inside an if else statement?
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following query to return userids that are not in the message\_log table ``` select * from likes where userid not in(select to_id from message_log) ``` I have an index on the userid column in the likes table and an index on the to\_id column in the message\_log table but the index are not being used accord...
You can try this ``` select * from likes lk where not exists (select 1 from message_log where to_id = lk.userid ) ```
``` select * from likes left join message_log ml on ml.to_id=likes.userid where ml.to_id is null ``` Try the query with LEFT JOIN instead and leave the only userids without mesages
Query taking a very long time
[ "", "sql", "postgresql", "postgresql-performance", "" ]
I have 2 columns in the Table1: `Time_Stamp` and `RunTimeMinute`. How can I subtract the `Time_Stamp` value where RunTimeMinute=0 from the `Time_Stamp` value corresponding to RunTimeMinute=1 (which would give me the time taken to get the machine running)? ``` Time_Stamp RunTimeMinute 2016-03-0...
To accomplish the task you have described (provided the `Time_Stamp` field is type of `DateTime` and `RunTimeMinute` is an Integer Number), you may use SQL `SELECT` Query/Subquery technique and `DATEDIFF()` function as shown in the following example: ``` SELECT [YourTable].Time_Stamp AS t1, (SELECT YourTable.Time_Stam...
For example we have a sample like this: ``` CREATE TABLE Table1 ( Time_Stamp datetime, RunTimeMinute int ) INSERT INTO Table1 VALUES ('2016-03-01 04:32:10.000', 1), ('2016-03-01 04:33:11.000', 2), ('2016-03-01 04:34:13.000', 3), ('2016-03-01 04:35:15.000', 4), ('2016-03-01 ...
SQL Statement to Calculate DateTime Difference between Two Rows of the same Table
[ "", "sql", "sql-server", "subquery", "datediff", "" ]
I want to subtract 2 dates in MS SQL Server. Example: ``` Current date Last used date '2016-03-30' '2015-02-03' ``` Current date refers to today's date, "Last used date" is a measure. How to write a query in SQL Server? I have this but doesn't work (it says "Operand data type is invalid for subtract oper...
``` SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate ``` Output DiffDate 61 More practice please refer below W3 school: <https://www.w3schools.com/sql/func_sqlserver_datediff.asp>
Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows ``` SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays FROM TableName ```
Subtract two dates in Microsoft SQL Server
[ "", "sql", "sql-server", "database", "sql-server-2012", "data-warehouse", "" ]
i have a table with a column have value seperated by semi colon. the concern is value in the column are not fixed. it starts from 1 and end upto 80 semicolon sepaeration. i am trying to put each individual value to seperate column **SQL SERVER 2008 code** ``` DECLARE @Table TABLE( Val VARCHAR(50) ) INSERT IN...
Try it like this: ``` DECLARE @Table TABLE( Val VARCHAR(50) ) INSERT INTO @Table (Val) SELECT '2Xcalcium; kidney' union all SELECT '3XMagnessium; liver' union all SELECT '2-ECG;3XSODIUM;DIALYSIS'; ;WITH Splitted AS ( SELECT * ,CAST('<x>' + REPLACE(Val,';','</x><x>') + '</x>' AS XML) Values...
Most of the link provided extract the element into rows. If you prefer to use your existing logic and extract the individual element into separate column, you can use multiple cascaded CROSS APPLY. ``` SELECT t.Val, v1.V as V1, v2.V as V2, v3.V as V3 FROM @Table t cross apply ( selec...
Semicolon seperated value to other column in sql server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Folks, I've read the fixes for this issue but I have a variation that I can't solve. Firstly the following syntax throws the error ``` Case when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-') when #TFs.lTFID = 1161166 then 'Administrator' when #TFs...
Based on the error message, the result of the `CASE` expressions gets converted to `INT`. Also of the return value of your `WHEN`s is known to be `VARCHAR`, except for `AssetID`, so I assume this must be an `INT` value. The error happens because when using a `CASE` expression, all return values must be of the same dat...
Try and cast the AssetID to a varchar in the case statement. ``` Case when #TFs.lTFID = 1161165 then REPLACE(CONVERT(VARCHAR(11), cast([dCreatedUTC] as datetime), 106), ' ', '-') when #TFs.lTFID = 1161166 then 'Administrator' when #TFs.lTFID = 1161167 then '' when #TFs.lTFID = 1161168 then CAST(AssetID...
SQL Select Case Conversion failed when converting the varchar value to data type int.
[ "", "sql", "sql-server", "" ]
I have a student table with the below structure. ``` StudentId StudentName SubjectId 123 Lina 1 456 Andrews 4 123 Lina 3 123 Lina 4 456 Andrews 5 ``` Need to write a query to get the stu...
Try with grouping: ``` Select studentId from student where subject_Id in ('1', '3', '4') group by studentId having count(distinct subject_Id) = 3 ``` **Note:** You might consider changing `('1', '3', '4')` to `(1, 3, 4)` if `subject_Id` field is of type `int`. **Note2:** `distinct` keyword inside `count` should ...
The easiest way would be ``` select StudentId from student where SubjectId in (1,3,4) group by StudentId having count(distinct SubjectId) = 3 ```
Sql query to find Id tagged to multiple rows
[ "", "mysql", "sql", "oracle10g", "" ]
`Suppliers` table ``` Part Number Supplier XXX A XXX B YYY C ``` `Part Numbers` table ``` PK_ID Part Number 1 XXX 2 YYY ``` I want to select it with additional column `FK_ID` based on `PK_ID` from `Part Numbers`: ``` FK_ID Part Number Supplier ...
Never use commas in the `FROM` clause. Always use explicit `JOIN` syntax: ``` SELECT s.`Part Number`, s.Supplier, p.PK_ID` FROM Suppliers JOIN `Part Numbers` p ON s.`Part Number` = p.`Part Number` ; ``` I would encourage you to name your tables and columns without spaces, so you don't need to escape the na...
Try: ``` SELECT s.`Part Number`, s.`Supplier`, p.`PK_ID` FROM `Suppliers` AS s JOIN `Part Numbers` AS p ON s.`Part Number` = p.`Part Number` ```
SQL select column from other table with corresponding value
[ "", "mysql", "sql", "join", "" ]
im using Oracle for doing database personal learning purpose. For my current knowledge i can't solve this question... here i'll show my problem. Here is my 2 table structure: ``` CREATE table "HOSPITAL" ( "HOSPITAL_ID" NUMBER NOT NULL, "NAME" VARCHAR2(255), "ADDRESS" VARCHAR2(255), ...
I dont see easy way to do this. So the cumbersome way is ``` SELECT * FROM "HOSPITAL" H JOIN "HOSPITAL_SPECIALIZE" HS ON H."HOSPITAL_ID" = HS."HOSPITAL_ID" WHERE DECODE("MATERINITY", 'YES', 1, 0) + DECODE("ENT", 'YES', 1, 0) + DECODE("DERMATOLOGY", 'YES', 1, 0) + DECODE("ORTHOPEDICS", 'YES', 1, ...
Try: ``` SELECT a.HOSPITAL_ID, a.NAME, b.MATERNITY, b.ENT, b.DERMATOLOGY, b.ORTHOPEDICS FROM HOSPITAL AS a JOIN HOSPITAL_SPECIALIZE AS b ON a.HOSPITAL_ID = b.HOSPITAL_ID WHERE CASE MATERNITY WHEN 'YES' THEN 1 ELSE 0 END + CASE ENT WHEN 'YES' THEN 1 ELSE 0 END + CASE DERMATOLOGY WHEN...
SQL queries to determine more than 1 specialize and display in table
[ "", "sql", "oracle", "" ]
I'm joining two tables on three fields. The problem I'm having is that I need to use a default row from table b if a.baz is not in b.baz. The problem is some will have a match in b but also have a default and that is causing a cross-product that I don't want. ``` select a.foo, a.bar, a.baz, b.fee, b.fie from a join b ...
You have to add a `NOT EXISTS` so as to exclude the `b` record having `baz = 'DEFAULT'` when a match `a.baz = b.baz` also exists: ``` select a.foo, a.bar, a.baz, b.baz, b.fee, b.fie from a join b on a.foo = b.foo and a.bar = b.bar and ((a.baz = b.baz) OR b.baz = 'DEFAULT') where not exists (select 1 ...
Your query is quite fine, as it already contains the rows you want. Now you must must remove the unwanted rows. You do this by ranking your matches and only keeping the better match. This can be done with `ROW_NUMBER`, giving the better record row number 1. ``` select foo, bar, abaz, bbaz, fee, fie from ( select ...
Join with default values but not wanting a cross product
[ "", "sql", "postgresql", "" ]
I have a data set like this (see below) and I try to extract digits which are in form {variable\_number\_of\_digits}{hyphen}{only\_one\_digit}: ``` with mcte as ( select 'ILLD/ELKJS/00000000/ELKJS/FHSH' as addr from dual union all select 'ILLD/EFECTE/0116988-7-002/ADFA/ADFG' as addr from dual union all select 'IIODK/...
If you want to get the results from the second and third `/` delimited groups then: ``` with mcte ( addr ) as ( select 'ILLD/ELKJS/00000000/ELKJS/FHSH' from dual union all select 'ILLD/EFECTE/0116988-7-002/ADFA/ADFG' from dual union all select 'IIODK/1573230-0/2216755-7/' from dual union all sel...
Combining the [**delimiter split query**](https://stackoverflow.com/questions/31601828/how-to-select-values-within-a-column/31606666#31606666) with `REGEXP_LIKE` and *pivot*-ing the result you get this query working for up to 6 numbers. You will need to update the `cols` subquery and teh `pivot` list to be able to proc...
How to parse data using REGEXP_SUBSTR?
[ "", "sql", "regex", "oracle", "oracle11g", "regex-greedy", "" ]
I have a table that accommodates data that is logically groupable by multiple properties (foreign key for example). Data is sequential over continuous time interval; i.e. it is a time series data. What I am trying to achieve is to select only latest values for each group of groups. Here is example data: ``` +--------...
Postgres offers the convenient `distinct on` for this purpose: ``` select distinct on (relation_id, code) t.* from t order by relation_id, code, date desc; ```
Other option: ``` SELECT DISTINCT Code, Relation_ID, FIRST_VALUE(Value) OVER (PARTITION BY Code, Relation_ID ORDER BY Date DESC) Value, FIRST_VALUE(Date) OVER (PARTITION BY Code, Relation_ID ORDER BY Date DESC) Date FROM mytable ``` This will return top value for what ever you partition by, and for whatever you order...
Select latest values for group of related records
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I have a query that joins my customers and transactions table, lets alias this joined query as `jq`. I want to create a ranking of each customer's purchases (transactions) by order timestamp (`order_ts`). So I did, ``` SELECT customer_id, order_id, order_ts, RANK() OVER (PARTITION BY customer_i...
If I understood you correctly, you can achieve this with `CASE EXPRESSION` : ``` SELECT customer_id,min(order_id),min(order_ts), CASE WHEN rnk < 5 then rnk else 5 end as rnk,sum(amount) FROM( SELECT customer_id, order_id, order_ts, RANK() OVER (PARTITION BY customer_id ORDER BY ...
> **Though this produces the correct result, sagi's [answer](https://stackoverflow.com/a/36303500/2203084) is more efficient.** --- You can use a `SELECT` on the result and filter for `RANK < 5`. Then do a `UNION ALL` on the aggregated values for `RANK >= 5` ``` WITH Cte AS( SELECT customer_id, ...
Aggregating rows with rank or index >= N
[ "", "sql", "sql-server", "postgresql", "" ]
I have two tables. One consists of customers and another consists of products they have purchased: Table customer ``` CustID, Name 1, Tom 2, Lisa 3, Fred ``` Table product ``` CustID, Item 1, Toaster 1, Breadbox 2, Toaster 3, Toaster ``` I would like to get all the custo...
``` SELECT distinct * FROM Customer LEFT JOIN Product ON Customer.CustID=Product.CustID WHERE Item = 'Toaster' AND Customer.CustID NOT IN ( Select CustID FROM Product Where Item = 'Breadbox' ) ```
This is my first post so forgive any missteps. There is a "many to one" relationship between the Customer and Product tables. To make the logical restrictions you want to apply, you would either need to aggregate the Product table or join the Product table twice. In effect, you are seeking to collapse the many to one r...
Select all customers except if they have another product - SQL
[ "", "mysql", "sql", "" ]
I'm doing my SQL exercises but I got stuck in one. I need to retrieve the employees with the two highest salaries, but I can't use any type of subquery or derived table. I do it with a subquery like this: ``` SELECT * FROM (SELECT * FROM emp ORDER BY sal DESC) new_emp WHERE ROWNUM < 3; ``` I also know that this can b...
This is actually a pathetic method, in my opinion, but you can use a `join`: ``` select e.col1, e.col2, . . . from emp e left join emp e2 on e2.salary >= e.salary group by e.col1, e.col2, . . . having count(distinct e2.salary) <= 2; ``` Note: this is really equivalent to a `dense_rank()`, so if there are ti...
If you are Oracle version 12.1 or above you can use a row limiting clause. In your case you would just use the subquery plus the row limiting clause like so: ``` SELECT * FROM emp ORDER BY sal DESC FETCH FIRST 5 ROWS ONLY; ``` Source: <https://oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1#...
ORACLE SQL retrieve n rows without subqueries or derived tables
[ "", "sql", "oracle", "oracle11g", "window-functions", "row-number", "" ]
I have created a foreign key without specifying the name so sql server has created it with auto generated name. Now I want to drop the column which has this foreign key. The problem is that i don't know the name of this foreign key. Is there any way to drop all the foreign keys for particular column in particular table...
If you want to get more information about FK and specifically about a particular scheme and table than you can use. ``` SELECT t.Name as TableName, c.name as ColumnName, fk.name as FK_NAME FROM sys.foreign_keys as fk inner join sys.tables as t on fk.parent_object_id = t.object_id inner join sys.col...
You can get all the constraint list along with the names assigned to particular tables with the help of the below query: ``` SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='YourTableName'; ``` Once you find the constraint you want to delete you can do it with the help of below query: ``` ALTER T...
How to drop foreign keys of a particular column
[ "", "sql", "sql-server", "t-sql", "" ]
I'm reading a documentation about SQL injections, and there is a strange statement that i don't understand: ``` concat(col1,col2)x ``` What is the use of the `x` ?
> *What is the use of the x ?* It is column [alias](https://en.wikipedia.org/wiki/Alias_%28SQL%29): ``` CREATE TABLE tab(col1 VARCHAR(100), col2 VARCHAR(100)); INSERT INTO tab(col1, col2) VALUES ('a','b'); ``` Query: ``` SELECT concat(col1,col2)x FROM tab ``` same as ``` SELECT concat(col1,col2) AS x FROM tab; ``...
`concat` - returns a string that is the result of concatenating two or more string values. The confusion is about the x. The x is the concated single name, so you can access it. You can also place `AS` before the x. **Query:** ``` SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' ) AS Result; ``` **Output:** > ...
In SQL what does concat(col1,col2)x does?
[ "", "sql", "" ]
I'm trying to determine how many people have purchased a pair of goods out of all distinct pairs of products that can exist. E.g. I have three products, A, B, C and I would like to determine how many % of customers bought A and B, B and C, and A and C out of the number of customers who own either product within each pa...
Iterative query development... If you don't have a `product` table, and only have the `customer_country_product` table, you can use an inline view to create a distinct list of products for each country. To get products by country... ``` SELECT ccp.product_id , ccp.country_id FROM customer_country_produc...
You need to generate all pairs of products along with the country. Then you need to calculate the number of matching customers that purchased either and the number that purchased both. Let me assume you have a products table and a countries table. Then, I think that subqueries might be the simplest solution: ``` sele...
Percentage of Cross product purchase
[ "", "sql", "sql-server", "" ]
I have an `INSEE` table in my SQL Server 2008 R2. I have some duplicate values (15 000 lines out of 54 000 have to be deleted). This is my current script ``` declare @datainsee table ( di_nom varchar(100), di_departement varchar(5), di_type varchar ) declare @datainseeidentifian...
With the help of a CTE and ROW\_NUMBER. This should be enough: ``` with x as ( select ROW_NUMBER() OVER ( PARTITION BY iee_nom, iee_departemen, iee_type ORDER BY <pick your priority column here> )rID, * from insee ) delete from x where rID > 1 ```
I suggest you to use traditional way like below, Using `Temp` Table ``` SELECT DISTINCT * INTO #TmpTable FROM insee DELETE FROM insee --OR Use Truncate to delete records INSERT INTO insee SELECT * FROM #TmpTable DROP TABLE #TmpTable ```
Optimise SQL request for duplicate Value
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table called `widgets` that has a string column named `version`. Data for version is in period-separated string format, similar to semantic versioning. e.g. "1.2.4" When I do the traditional `ORDER BY widgets.version` then I get the following order ``` +--------------+ | Widgets | +----+---------+ | id...
The easiest way is to convert the version string to an integer array and then sort on that array: ``` select id, version from widgets order by string_to_array(version, '.')::int[] ``` Note that this will fail if the version contains non-numeric values.
Have you tried? ``` SELECT id, split_part(version, '.', 1)::int as major, split_part(version, '.', 2)::int as minor, split_part(version, '.', 3)::int as patch FROM widgets ORDER BY major, minor, patch ```
Is it possible to order by substrings in postgreSQL?
[ "", "sql", "postgresql", "version-sort", "" ]
I'm trying to get the correct `ORDER BY` for my MySQL query, however I can't get the order by correct. I have two columns: 1. `breaking_news` = values are `NULL` or `1` 2. `news_published_dt` = values are `DATETIME` How can I sort so that the first output are `breaking_news NOT NULL` sorted by `DATETIME`, and then t...
Looks like, you are looking for this: ``` SELECT * FROM tableName ORDER BY breaking_news DESC, news_published_dt ASC ```
``` SELECT * FROM table_name ORDER BY news_published_dt DESC ```
MySQL order by first column, sorted by second column
[ "", "mysql", "sql", "sorting", "datetime", "sql-order-by", "" ]