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 make SQL query, that would give me count of buyers per month, who made at least one purchase in that month, NOT COUNTING this buyer's first purchase ever. For example, I have this table: ``` id bill_date 1 2014-01-14 1 2014-02-14 2 2014-02-14 2 2014-02-18 1 2014-02-19 2 2014-03-14 1 2014-03-1...
This may help you : ``` SELECT date_format(t1.bill_date, '%Y-%m') AS dt, Count(DISTINCT t1.id) AS cnt FROM tempt t1 JOIN (SELECT id, Min(bill_date) AS bill_date FROM tempt GROUP BY id) AS t2 ON t1.id = t2.id AND t1.bill_...
You want to first get distinct buyers for each month, then do your counting. This is a portable solution and more in line with the way you would process it mentally. select x.period, count(x.buyer\_id) accounts from (SELECT distinct DATE\_FORMAT(bill\_date, '%Y-%m') period, buyer\_id from billing)x group by x.period ...
Get count of entries per period excluding first one (SQL query)
[ "", "mysql", "sql", "" ]
A credit card company has several credit cards issued to each consumer. ``` CREATE TABLE card ( cardnumber int PRIMARY KEY, customer int, balance decimal(9,2), status varchar(10) ); INSERT INTO card VALUES ('100', '1', 100.00, 'active'); INSERT INTO card VALUES ('101', '1', 100.00...
You should create a separate Table for the "status" of the card. So you could create a simple "CASE WHEN" block in the SQL to handle all that. Example: ``` CREATE TABLE card_status ( status_id int PRIMARY KEY, message varchar(255) ); INSERT INTO card_status VALUES (1, 'active'); INSERT INTO card_status VALUES (2, 'e...
Normalize the table by changing status to integer and insert a foreign key relationship to a status table then you can select min(status) in the select query
MySQL how to group by and select certain text from multiple rows?
[ "", "mysql", "sql", "group-by", "" ]
I have two talbles a login table and a login attempts table for track worng login attempts login table ``` | id | username | password | | 1 | Jon | 1234 | | 2 | Danny | ttttt | | 7 | Martin | fffff | ``` attempts table ``` | id_attempts| time | ...
Instead of "if jon username and password are wrong query must return only 3 (number of jon wrong attempt)" I recommend using an additional column instead to return the authorization status. e.g. Also, since the username is being specified in the query, there is not much point in returning the userid or username. ``` ...
I don't know which database engine you are using since you have specified both mysql and postgresql as tags but here is how the select statement looks like in PostgreSQL: ``` SELECT (CASE WHEN l.password = ? THEN l.id END) AS userId, COUNT(a.id_attempts) AS numAttempts FROM login l LEFT JOIN attempts a ON a.id_attem...
Sql query with count() join and where on to tables
[ "", "mysql", "sql", "postgresql", "" ]
I have three tables: Pupils, KS3Assessments and AssessmentSets. * Pupils each have a StudentID, FName, SName etc. * AssessmentSet contains the title of the assessment, the deadline, the year group that must complete it, etc. New ones are created throughout the year, so their titles/ids can't be named explicitly in the...
try ``` DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Title) from AssessmentSet FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT StudentID, FName, SName' + @cols + ' from ...
Give this a try: ``` DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) SELECT @cols = STUFF(( SELECT DISTINCT ',' + QUOTENAME(title) FROM AssessmentSet FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @query = N' SELECT StudentID, FName, SName, ...
How do I turn this SQL pivot into an inner join pivot?
[ "", "sql", "sql-server", "" ]
I have a query and a result as follows. In the database NULL and 0 represent the same meaning. Now I want a counter based on Null+0 or 1 Eg:in the following example I want the result like this: ``` IsVirtual Category counter NULL+0 3 343+8 = (351 is Total) ``` **Query** ``` select * from ( ...
I think you want this : ``` SELECT COALESCE(IsVirtual, 0) as [IsVirtual], Category, Count(*) as [Counter] FROM yourtable GROUP BY COALESCE(IsVirtual, 0),Category ``` This will give you expected result without using subquery.
try with this ``` select * from ( Select CASE ISNULL(IsVirtual,0) WHEN 0 Then 'NULL + 0' ELSE IsVirtual END AS IsVirtual, Category, count(*) as counter from [Hardware] group by ISNULL(IsVirtual,0), Category )innercat ```
Update innerquery result
[ "", "mysql", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I am trying to write a script which drops some obsolete tables in Postgres database. I want to be sure the tables are empty before dropping them. I also want the script could be kept in our migration scripts where it is safe to run even after these tables are actually dropped. There is my script: ``` CREATE OR REPLAC...
You must use `EXECUTE` if you want to pass a table name as parameter in a Postgres function. Example: ``` CREATE OR REPLACE FUNCTION __table_is_empty(param character varying) RETURNS bool AS $$ DECLARE v int; BEGIN EXECUTE 'select 1 WHERE EXISTS( SELECT 1 FROM ' || quote_ident(param) || ' ) ' INT...
No, no, no. For many reasons. [@kordirko](https://stackoverflow.com/a/26944582/939860) already pointed out the immediate cause for the error message: In plain SQL, variables can only be used for *values* not for *key words* or *identifiers*. You can fix that with [**dynamic SQL**](https://stackoverflow.com/questions/t...
Check if table is empty in runtime
[ "", "sql", "postgresql", "stored-procedures", "plpgsql", "dynamic-sql", "" ]
I've got a table in postgres, with a column with int(8) values: Table TABLE: ``` number | name ---------------------- 1111 | a 1122 | b 1133 | c 1144 | d 1155 | e 2211 | f 2222 | g 2233 | h 2244 | i 2255 | k ``` I wanna select all ...
I would do this with explicit conversion: ``` select * from TABLE where cast(number as varchar(255)) like '11%'; ``` Be very careful when you write SQL code that does implicit conversion.
``` SELECT * FROM table WHERE number::text LIKE '11%' ```
Postgres - Selecting rows begining with value
[ "", "sql", "postgresql", "" ]
I have a table and I need to get unique rows with latest called\_date but adding phones to the right if phones do not match but name is the same. There could be even more different phones with the same name. I need to add them all to the right. I am working on it all day. Is it even possible? How to do that? Database ...
First it'd be nice to have some nicely formatted sample data to use: ``` SELECT * INTO ##CallData FROM ( SELECT '1245' as ID, 555963 as Phone, '2014-11-01' as Called_date, 'some_name' as Name, 'some@gmail.com' as Email UNION SELECT '5896' as ID, 896111 as Phone, '2014-11-05' as Called_date, 'other_na...
Try this ``` SELECT id, Phone, Called_date, Name, Email FROM( SELECT id, Phone, Called_date, Name, Email, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Called_date DESC) as rn FROM yourTable ) a WHERE rn = 1 ``` Updated Answer: ``` SELECT a.id, a.Phone, a.Called_date, a.Name, a.Email, c.Phone as SecondPh...
SQL Server : select how to?
[ "", "sql", "sql-server", "select", "" ]
What I am trying to accomplish: ``` Dataset 1 Name1 Name2 Name3 Dataset 2 Number1 Number2 Number3 ``` will become 2 columns: ``` dataset1 dataset2 Name1 Number1 Name2 Number2 Name3 Number3 ``` My datasets 1 & 2 will always have equal rows. Which name linked to which...
If you don't want to add an identity column to the tables, you can use the ROW\_NUMBER() function like this: ``` SELECT T1.Col1, T2.Col1 FROM (SELECT Col1, ROW_NUMBER() OVER (ORDER BY Col1) AS N FROM Table1) T1 INNER JOIN (SELECT Col1, ROW_NUMBER() OVER (ORDER BY Col1) AS N FROM Table2) T2 ON T1.N = T2...
Add identity columns to both the tables and perform join on basis of these column ``` ALTER TABLE Table1 ADD ID INT IDENTITY(1,1) NOT NULL ALTER TABLE Table2 ADD ID INT IDENTITY(1,1) NOT NULL SELECT Table1.dataset1col , Table2.dataset2Col From Table1 INNER JOIN Table2 ON Table1.ID = Table2.ID ```
TSQL merge 2 dataset with even number of rows next to eachother
[ "", "sql", "sql-server", "t-sql", "" ]
I am a complete noob to SQL and trying to understand why this query returns "115": ``` select datediff(yy, -3, getdate()) ```
`datediff` takes three Parameter. The first is the `interval`, the second the `start date` and the third the `end date`. You are passing -3 as start date, there we can show: ``` SELECT CAST(-3 AS datetime) -- results in '1899-12-29 00:00:00.000' ``` And because 2014 - 1899 is 115, you will get this as result.
Because DATEDIFF() calculates an interval between 2 dates, and you specified year -3 in one of them. Firstly, the date "zero" is 12/30/1899 on SQL server. Secondly, your "-3" was an incorrect date format and it thus replaced it with its 0 2014 - 1899 = 115 Use DATEADD() instead to achieve what you want to do.
SQL datediff with negative parameter
[ "", "sql", "sql-server", "date", "" ]
I have a database with two tables: `members` and `profilefields`. `members` has the columns: `ID, name, email` `profilefields` has the columns: `ID, field1, field2, etc.` I'd like to select the `name` and `email` of each row in `members`, based on a query of `profilefields` I think this is how it works, but I don'...
You could use the `in` operator: ``` SELECT name, email FROM members WHERE id IN (SELECT id FROM profilefields WHERE field1 = 'X' and field2 = 'Y') ```
This should do the trick: ``` SELECT m.name, m.email FROM members m INNER JOIN profilefields pf ON m.ID = pf.id WHERE pf.field1=X AND pf.field2=Y ``` Here we use an `INNER JOIN` in the `FROM` clause to link the tables ON their `id` field. The filter goes into the `WHERE` clause, and the fi...
MySQL Query Of Two Tables
[ "", "mysql", "sql", "database", "" ]
How do I construct my left join to produce this output? Table 1: Main Table ``` | ID | Team | Color | | 1 | A | Red | | 2 | A | Blue | | 3 | B | Green | | 4 | B | Green | | 5 | C | Yellow | ``` Table 2: Lookup Table ``` | Te...
You can use the AND keyword in your JOIN clause: ``` SELECT * FROM Table1 INNER JOIN Table2 ON Table1.Team = Table2.Team AND Table1.Color = Table2.Color ```
Try this untested query: ``` SELECT Table1.ID, Table1.Team, Table1.Color, case Table1.Team when "A" then case Table1.Color when "READ" then Table2.Final else Table1.Team end else Table1.Team end Table2.Final FROM Table1 FROM Table1 INNER JOIN Table2 ON Table1.Team = Table2.Team; ```
INNER JOIN Using IF logic
[ "", "mysql", "sql", "" ]
I have a CRM database with primary table columns `createon` (`date`) & `createat` (`time`). We'll call it table A There is a secondary table that is used to log data concerning activity taken in an attempt to contact records created in A, let's call this table B. I'm trying to write a tSQL query that will show the av...
one way to do is do get minimum ontime for each user in a subquery and join with table A. ``` SELECT T.userid, ISNULL(avg(cast(datediff(MINUTE, cast(A.createat as datetime)+A.createdon, T.MinOnTime) as float)),0) AS [AVG TIME FROM LEAD CREATION TO FIRST LOGGED ACTIVITY] FROM TableA A LEFT JOIN ( SELECT K...
``` SELECT t.userid ,case when A.createon = B.ondate then avg(cast(datediff(MINUTE, A.createat, B.ontime) as float)) else avg(datediff(MINUTE, A.createon, B.ondate)+(cast(datediff(MINUTE, A.createat, B.ontime) as float))) end as 'AVG TIME FROM LEAD CREATION TO FIRST LOGG...
tSQL: Get average amount of time from record creation to first contact
[ "", "sql", "sql-server", "t-sql", "average", "" ]
sql Query: ``` Select * from tabEmployee where city='Delhi' OR locality='' OR pincode='' OR salary Between '' AND '' OR designation='' ``` I am quite new for sql server. I want to write a sql query where city is mandatory and other fields may or may not be provided by the user. I mean to say if one user enters ...
Try this: ``` Select * from tabEmployee where city='Delhi' AND ISNULL(locality_parameter,locality)=locality AND (pincode=pincode_parameter OR pincode_parameter=0) AND ISNULL(designation_parameter ,designation)=designation AND salary BETWEEN ISNULL(lower,salary) AND ISNULL(upper,salary) ``` Set...
Try this : ``` Select * from tabEmployee where city='Delhi' and (locality='Kirti Nagar' OR pincode='411521' OR (salary Between '5000' AND '10000') OR designation='Engineer') ```
Sql Query which filters according to one or more fields
[ "", "sql", "sql-server", "" ]
I have two tables named `Evaluation` and `Value`. In both tables, there are four columns. But three of the four are the same. In other words, they both have the `CaseNum`, `FileNum`, `ActivityNum` columns. In addition to those, the `Evaluation` table has the `Grade` column, and the `Value` table has the `Score` column...
**Yes: You can use `Inner Join`** to join on multiple columns. ``` SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E INNER JOIN Value V ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum ``` Create table ``` CREATE TABLE MyNewTab(CaseNum int, Fi...
No, just include the different fields in the "ON" clause of 1 inner join statement: ``` SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum ```
How to join two tables by multiple columns in SQL?
[ "", "mysql", "sql", "sql-server", "" ]
I'm using Oracle 10g and want to delete approx 5 million records from Persons table (Having total 15 million records) which doesn't have any reference in Order table (Having total 5 million records) Since deteting 5 million records in one go would cause undo log issues, I've decided to delete in batches of 100k. I'm u...
If you want this query to run faster, add the following two indexes: ``` create index idx_persons_city_pid on persons(city, p_id); create index idx_orders_pid on orders(p_id); ```
From my experience, the fastest way to delete lot of rows is : solution 1 (recommended by Tom Kyte) ``` `SET TRANSACTION USE ROLLBACK SEGMENT <your_seg> DELETE FROM <tab1> WHERE <cond> COMMIT` ``` OR solution 2 ``` `create table new_table unrecoverable as select * from old_table where ....; drop table old_table;...
How to delete large amount of data from Oracle table in batches
[ "", "sql", "database", "oracle", "oracle10g", "" ]
Good day. I have the following question: Is it possible to check the existence of the table when sql script running first time? I'm using Advantage Data Architect 11.10. I want to clarify my question. In my script I need to create a temporary table each time when sql script starting. For do this I delete my tempor...
One solution is this: ``` TRY DROP TABLE #tmp; CATCH ALL END TRY; CREATE TABLE #tmp ... ``` Another solution: ``` IF NOT EXISTS (SELECT 1 FROM (EXECUTE PROCEDURE sp_GetTables (NULL, NULL, 'tmp', 'LOCAL TEMPORARY')) getTables ) THEN CREATE TABLE #tmp ... END IF; ``` See also here: <http://devzone.advantagedataba...
``` --first variant --if table exist then drop table IF OBJECT_ID('Tempdb..#tmp') IS NOT NULL DROP TABLE #tmp CREATE TABLE #tmp ( ID INT , Definitions VARCHAR(30) ) ------------------------------------------------------------------------- --second variant --if table exist then delete all record...
Check the existence of the table when sql script runnnig first time (Advantage data architect)
[ "", "sql", "advantage-database-server", "" ]
I have a table. this table has usage period of user. example is follow ``` |user_id|start_at |end_at | |1 |2014/11/02|2014/11/05| |2 |2014/11/03|2014/11/07| |3 |2014/11/08|2014/11/09| ``` I would like to get maximum concurrent number of users above case, Between 2014/11/03 ~ 2014/05, 2 user use...
The maximum is going to occur at one of the `start_at` times. So, you can do this with a self-join: ``` select u.start_at, count(*) as numconcurrent from usage u join usage u2 on u.start_at between u2.start_at and u2.end_at group by u.start_at ``` If you want the maximum number, then add: ``` order by coun...
sounds like you may have mis-stated the question. Do you really mean "max" ? or just the number of users between two dates ? If that is so, then ``` Select count(*) from table where start_at < @end and end_at > @start ```
In SQL, how can you calculate maximum concurrent number of users
[ "", "mysql", "sql", "" ]
In full disclosure, I was kind of thrown into a project this week using SQL and, unfortunately, have very little experience using it up until now outside of very basic querying. I'm going to start studying up, but really could use some help here in the short-term. In this example, the tables are named `Person_PR` and ...
The syntax to create a new table in sql server is ``` SELECT p.record_num , p.person_num , c.cme_variable1 , c.cme_variable2 , p.pr_variable1 , p.pr_variable2 INTO new_table FROM Person_PR p INNER JOIN Person_CME c ON p.person_num = c.person_num AND p.record_num = b.record_num ``` How...
You'll want to use a stored procedure, not a new table: ``` CREATE PROCEDURE [dbo].GetPersonData AS BEGIN SET NOCOUNT ON; SELECT cme.record_num , cme.person_num , cme.cme_variable1 , cme.cme_variable2 , pr.prvariable1 , pr.prvariable2 FROM ...
Creating new table from columns in multiple tables
[ "", "sql", "sql-server", "" ]
I tried the UNION but it doesn't work it says #1221 - Incorrect usage of UNION and ORDER BY. ``` SELECT members.Name, friends.MemberNumber1 FROM friends INNER JOIN members ON friends.MemberNumber1= members.MemNo WHERE friends.MemberNumber2 LIKE 1 ORDER BY members.Name UNION SELECT members.Name, friends.MemberNumber2...
You can do a derived table, then order by. The column names have to match up. I know this answer is close to Barmar's, but the aliasName for the second column is important. You can also look up the difference between UNION and UNION ALL, I use the latter typically. ``` SELECT Name , MemberNumber FROM ( SELECT memb...
You need to put the `UNION` into a subquery, then order the entire thing. ``` SELECT * FROM ( SELECT members.Name, friends.MemberNumber1 FROM friends INNER JOIN members ON friends.MemberNumber1= members.MemNo WHERE friends.MemberNumber2 LIKE 1 UNION SELECT members.Name, friends.MemberNumber2 ...
Merging two SELECTs into one from the same table?
[ "", "mysql", "sql", "select", "union", "" ]
To be able to explain the situation, let's say I have a table ``` Product price Cola 2 Cola null Fanta 1 Fanta 2 Sprite 2 Sprite null ``` I need to write a query that would return the maximum price per product and if the price is null, would consider it the maximum. So for this table it should return Co...
Standard SQL allows you to specify where `NULL` values should be sorted using the expression `NULLS FIRST` or `NULLS LAST` in the `ORDER BY` statement. This can be combined with a window function to get the desired behaviour: ``` select product, price from ( select product, price, row_number() o...
``` select product, case when sum(case when price is null then 1 else 0 end) > 0 then null else max(price) end as price from your_table group by product ```
How can I make null values be considered as MAX in SQL?
[ "", "sql", "postgresql", "max", "" ]
I am trying to create a table with a constraint where the date column should only accept any dates in the month of May or November. How should I write the constraint like?
There are two ways to achieve this: Using `CHECK CONSTRAINT` on the column or a `TRIGGER`. The `CHECK Constraint` could look like this: ``` create table tbl( date_col date check( MONTH(date_col) = 5 OR MONTH(date_col) = 11) ) ``` You have not specified a particular database so treat this as a pseudo-code on...
I may be misunderstanding your question. If you're just trying to retrieve values in may and nov, you can do this: ``` SELECT column1, column2, column3 FROM yourTable WHERE MONTH(yourTimeStamp)=5 or MONTH(yourTimeStamp)=11 ``` If you're trying to keep values from other months out of the DB, you should really do tha...
sql query accept only dates of two months
[ "", "sql", "date", "" ]
**Group by Date -Month -Day Hour and Time Query** I would like to group by Rundate and then JobDateStamp by yy/mm/dd hh:mm no seconds **Results** ``` [RunDate] [count] 12/11/2014 21:00 3 13/11/2014 21:00 1 ``` 3 lots of jobs were run on 12/11/2014 (3 date and time) 1 lots of jobs were run on 13...
you can do it by converting time to minutes and using `count(distinct .. )` As you need further filter by jobdatestamp, need to use it in count ``` SELECT dateadd(minute, datediff(minute, 0, rundate), 0) , count( distinct dateadd(minute, datediff(minute, 0, JobDateStamp), 0)) FROM tbl_tasks GROUP by dateadd(m...
Just truncate the datetime to the previous minute and group by that value: ``` select dateadd(minute, datediff(minute, 0, Rundate ), 0) RunDate, COUNT(*) Count FROM tbl_tasks GROUP BY dateadd(minute, datediff(minute, 0, Rundate ), 0) ```
Group by Date -Month -Day Hour and Time Query
[ "", "sql", "sql-server", "" ]
I am a SQL noob in need of some help with a specific query using the NYC 2013 Taxi Trips Dataset [located here](https://bigquery.cloud.google.com/table/833682135931:nyctaxi.trip_data). I want to analyze dropoffs at JFK Airport, but want to build my query so that I can include the next subsequent pickup that a taxi doe...
This should give you all the dropoffs with next pickups ``` SELECT * FROM (SELECT medallion, dropoff_datetime, dropoff_longitude, dropoff_latitude, LEAD(pickup_datetime, 1, "") OVER (PARTITION BY medallion ORDER BY pickup_datetime) ...
I think that N.N. has the right idea, except that you want LEAD instead of LAG to get the next pickup. For example, this query will produce the next pickup time, lat and long after a pickup at JFK. ``` SELECT medallion, pickup_datetime, pickup_longitude, pickup_latitude, LEAD(pickup_datetime, 1, ""...
Self-Join with Subquery in Google BigQuery
[ "", "sql", "google-bigquery", "" ]
This question has been asked before, but they all referenced to single and not composite keys, and the solutions don't seem to work for me. Basically, please consider the following table: ``` CREATE TABLE IF NOT EXISTS `my_answers` ( `id` int(11) NOT NULL auto_increment, `question_id` int(11) NOT NULL default ...
If you do not specify a name of the unique key in case of composite key then by default the first column name is used as the name. Here is the example ``` mysql> CREATE TABLE IF NOT EXISTS `my_answers` ( -> `id` int(11) NOT NULL auto_increment, -> `question_id` int(11) NOT NULL default 0, -> `...
Try the following command: ``` show index from `my_answers`; ``` then inspect the key name of your index and drop it by its name.
How to drop composite UNIQUE KEY in MySQL?
[ "", "mysql", "sql", "" ]
Before a `select SOMETHING into v_something`, I would like to know if my query returns a row. Here are a good methods, but it cost two `select` if the row exists : ``` select count(1) into isRowExists from PERSON where CONDITION='Something'; if (isRowExists > 0) then select NAME into v_name from PERSON where CON...
You could do: ``` BEGIN BEGIN select NAME into v_name from PERSON where CONDITION='Something'; exception when no_data_found then --do_something END; BEGIN select MODEL into v_model from CAR where CONDITION='Something'; exception when no_data_found then ...
For the second method, you can just wrap each in a `begin`/`end` block: ``` begin select NAME into v_name from PERSON where CONDITION='Something'; exception when no_data_found then --do_something end; begin select MODEL into v_model from CAR where CONDITION='Something'; exception when no_data...
Fastest way to check if row exist
[ "", "sql", "oracle", "plsql", "" ]
The following query executes as expected, giving me the expected output given the fields being queried ``` SELECT 1 as SEQ, TERM_DESC as TERM, PRIMARY_COLLEGE_DESC as COLLEGE, LEVEL_GROUPING_CODE as LEVEL_CODE, LEVEL_GROUPING_DESC as LEVEL_DESC FROM SECopy as SE ``` However, when I add the function SUM() on a fie...
1. Alias Name for Table is not needed 2. You Should Use All Columns in Group BY Clause except Aggregate Function > ``` > SELECT 1 as SEQ, > TERM_DESC as TERM, > PRIMARY_COLLEGE_DESC as COLLEGE, > LEVEL_GROUPING_CODE as LEVEL_CODE, > SUM(ID_COUNT) as HEADCOUNT > from SECopy > GROUP BY TERM_DESC,PRIMARY_COLLEGE_D...
You'll need to stick any of your fields that are in your SELECT statement, but are not being aggregated by a SUM(), AVG(), MIN(), etc... into a GROUP BY clause: ``` SELECT 1 AS SEQ, TERM_DESC AS TERM, PRIMARY_COLLEGE_DESC AS COLLEGE, LEVEL_GROUPING_CODE AS LEVEL_CODE, LEVEL_GROUPING_DESC AS LEVEL_...
Why is my query failing upon adding SUM function?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I've read through a couple similar posts, but not found a solution for this issue: I have a form with an unbound rich text, multiline textbox named tbxNote. When the textbox is exited, I use VBA code to create an SQL string which I subsequently execute to UPDATE a table field [Note] with the value in the unbound textb...
@HansUp's suggested trying a DAO recordset to update the table. That did the trick! Thank you, HansUp. HansUp requested that I post the answer, so, here is the code that worked for anyone else who comes across this thread: ``` Dim dbs As DAO.Database Dim rsTable As DAO.Recordset Dim rsQuery As DAO.Recordset Set dbs =...
Unfortunately, you posted test code works, but you FAILED to post your actual update string that fails. A common (and known) problem is if you include a function (especially aggregates) in your SQL, then you are limited to 255 characters. In fact this can apply if you have function(s) that surrounds the unbound text b...
Access SQL to save value in unbound textbox cannot save more than 255 characters
[ "", "sql", "ms-access", "vba", "ms-access-2013", "" ]
I need to calculate the year a week is assigned to. For example the 29th December of 2003 (Monday) was assigned to week one of year 2004 (this is only for europe, I think). You can take a look at this with this code: ``` SELECT DATEPART(isowk, '20141229'); ``` But now I need an easy way to get the year this week is a...
~~This solution~~ The code in the question does not return the correct value for the date `'1-1-2027'`. The following will return the correct value with all dates i tested (and i tested quite a few). ``` SELECT YEAR(DATEADD(day, 26 - DATEPART(isoww, '2012-01-01'), '2012-01-01')) ``` As taken from: <https://capens.ne...
This is the most compact solution I could come up with: ``` CASE WHEN DATEPART(ISO_WEEK, @Date) > 50 AND MONTH(@Date) = 1 THEN YEAR(@Date) - 1 WHEN DATEPART(ISO_WEEK, @Date) = 1 AND MONTH(@Date) = 12 THEN YEAR(@Date) + 1 ELSE YEAR(@Date) END ``` Can be used directly inside a SELECT statement. Or you could...
SQL Get "ISO Year" for ISO Week
[ "", "sql", "sql-server", "t-sql", "date", "" ]
Cant figure out how to get this result: ``` ProductID Variantno 53121 5197, 5198,5199 ``` From this data collection. ``` ProductID Variantno 53121 5197 53121 5198 53121 5199 ``` Tried with group by but no good result, total sql noob...
Try this.. ``` SELECT ProductID, GROUP_CONCAT(Variantno) FROM tbl GROUP BY ProductID ```
``` select ProductID , group_concat(Variantno) from table group by ProductID ```
Select multiple values from multiple rows
[ "", "mysql", "sql", "" ]
In oracle will the below query works for getting 3rd highest salary. ``` select empname, salary from (select empname,salary from employee order by salary desc) where rownum==3 ``` I have seen answers in other threads but they seem to be complicated. If above query works then it is simple solution for oracle What w...
I did some exploration and found below link which explains the difference between `row_number()`, `rank()` and `dense_rank()`. From the below link I found `dense_rank()` is suitable answer for this question. <http://www.dwbiconcepts.com/tutorial/24-interview-questions/190-top-20-sql-interview-questions-with-answers.ht...
Use `Dense_Rank()` ranking function in `SQL SERVER` to find the 3rd highest salary. `Row_number()` returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.The `ORDER BY` clause determines the sequence in which the rows are assigned their unique `ROW_...
SQL query in Oracle and SQL server to get 3rd highest salary
[ "", "sql", "sql-server", "oracle", "" ]
I want to retrieve distinct rows from each column in this sql table My table ``` 1 Apple 2 Banana 3 Apple 2 Apple 1 Orange ``` I want the result like this: ``` 1 Apple 2 Banana 3 Orange ``` Please help me with this
Please try it ``` select *,row=rank() over(order by name) from (SELECT distinct name FROM abc) as cte ``` or ``` with cte as ( SELECT distinct name FROM abc ) select *,row=rank() over(order by name) from cte ``` Output ``` | row | Name | |-----------|----------| | 1 | Apple | | 2 | ...
You can get the distinct names by doing: ``` select distinct name from table t; ``` You can add the first column by doing: ``` select row_number() over (order by name) as id, name from (select distinct name from table t ) t; ``` Most databases support the ANSI standard row number. You haven't tagged this...
How to select distinct records from individual column in sql table
[ "", "sql", "datatable", "distinct", "" ]
I have a table of winners for a prize draw, where each winner has earned a number of points over the year. There are 1300 registered users, with points varying between 50 and 43,000. I need to be able to select a random winner, which is straight forward, but the challenge I am having is building the logic where each po...
Your script would look something similar to this: Script 1 : ``` DECLARE @Name varchar(100), @Points int, @i int DECLARE Cursor1 CURSOR FOR SELECT Name, Points FROM Table1 OPEN Cursor1 FETCH NEXT FROM Cursor1 INTO @Name, @Points WHILE @@FETCH_STATUS = 0 BEGIN SET @i = 0 WHILE @i < @Points BEGIN ...
So you want a winner with 1000 points have double the chances as another with only 500 points. Sort the winners by whatever order and create a running total for the points: ``` id points winner1 100 winner2 50 winner3 150 ``` gives: ``` id points from to winner1 100 1 100 winner2 50 ...
Create a random selection weighted on number of points, SQL
[ "", "sql", "sql-server", "" ]
table master ``` | id | user | | 1 | user1 | | 3 | user2 | | 4 | user3 | ``` table ver ``` | id_v | value | | 2 | value1 | | 3 | value2 | ``` I must delete id\_v 2 on table ver I' have this query ``` DELETE FROM `ver` WHERE id_v in (SELECT v.id_v FROM master m RIGHT JOIN ver v ON m.i...
It could be done using the following ``` delete v from ver v left join master m on m.id = v.id_v where m.id is null ``` **[Demo](http://www.sqlfiddle.com/#!9/40155/2)**
Try this ``` DELETE FROM `ver` WHERE id_v in ( SELECT id_v from (SELECT v.id_v FROM master m RIGHT JOIN ver v ON m.id = v.id_v WHERE m.id IS NULL) as temp ) ```
Asql select join and delete together
[ "", "mysql", "sql", "" ]
I have the following query: ``` this->getDoctrine()->getManager(); $sql = "SELECT shop.* FROM instagram_shop shop LEFT JOIN instagram_shop_picture picture ON picture.shop_id = shop.id WHERE COUNT(picture) = 0 AND shop.isLocked = 0...
``` SELECT shop.id FROM instagram_shop shop LEFT JOIN instagram_shop_picture picture ON picture.shop_id = shop.id WHERE shop.isLocked = 0 AND shop.expirydate IS NOT NULL AND shop.expirydate > now() AND shop.deletedAt IS NULL GROUP BY shop.id HAVING COUNT(picture.shop_id) = 0 ```
You can do what you want *without* a `group by` or `count()`. Just find the places where the `left join` fails: ``` SELECT shop.* FROM instagram_shop shop LEFT JOIN instagram_shop_picture picture ON picture.shop_id = shop.id WHERE picture.shop_id is NULL AND shop.isLocked = 0 AND shop.expirydate...
one to many relationship query with count
[ "", "mysql", "sql", "" ]
I have a simple table for the events log: ``` uid | event_id | event_data ----+----------+------------ 1 | 1 | whatever 2 | 2 | 1 | 3 | 4 | 4 | 4 5 | ``` If I need the latest event for a given user, that's obvious: ``` SELECT * FROM events WHERE uid=needed_uid ORDER BY ...
A Postgres specific solution is to use `distinct on` which is usually faster than the solution using a window function: ``` select distinct on (uid) uid, event_id, event_data from events where uid in (1,4) order by uid, event_id DESC ```
try below query : ``` select DesiredColumnList from ( select *, row_number() over ( partition by uid order by event_id desc) rn from yourtable ) t where rn = 1 ``` `Row_Number` will assign unique number starting from 1 to each row order by `event_id desc` and `partition by` will ensure that numbering should...
Postgres: getting latest rows for an array of keys
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I have found no other specific problem like this on here. This is a single table query in MySQL. I have a 'book' table that holds the 'title' and 'price' columns. The problem is to find the minimum book price and display the titles with that minimum value. My problem is that I can only return one title but there is mu...
You can find the title(s) of the books with the lowest price with a sub query. ``` SELECT TITLE FROM book WHERE PRICE = (SELECT MIN(PRICE) FROM book); ``` The query in your question is not valid standard SQL and would be rejected by most other RDBMSs. MySQL does not raise an error ([yet - though...
You can calculate the minimum price in one subquery, and then find all the books whose price matches that in an outer query. ``` SELECT a.title, a.price FROM book AS a JOIN (SELECT MIN(price) AS minprice FROM book) AS b ON a.price = b.minprice ``` Another way to write it is: ``` SELECT titla, price FROM book ...
Select Multiple Book Titles that share the MIN(PRICE) value | MySQL
[ "", "mysql", "sql", "min", "" ]
**Description :** I have a table of users as following students ``` id ------ name 1 ------ John 2 ------ Sarah 3 ------ Peter ``` and friends table as Buddies ``` person1 ------ person2 1 ------ 2 2 ------ 3 ``` Now I want all the friends of 2 and all other my friends whose fr...
Maybe this? I have tested it only with your example data. ``` select name from students where id in ( select p2 from buddies where p1 in ( select p2 from buddies where p1=[serach_for_id])); ```
Join twice to get friends of friends: ``` select distinct name from buddy_circle a join buddy_circle b on b.p1 = a.p2 join students on id = b.p2 where a.p1 = $reg_no ``` Note the order of tables in the query is such that the where clause applies to the first named table and joined tables flow on from that, which give...
how to find friends of friends in mysql
[ "", "mysql", "sql", "hierarchical-data", "recursive-query", "" ]
## My Issue I am trying to select one row from multiple tables based on parameters, but my limited knowledge of SQL joining is holding me back. Could somebody possibly point me in the right direction? Consider these table structures: ``` +-----------------------+ +---------------------+ | Customers |...
Since you're not really joining tables together, just selecting a single row from each, you could do this: ``` SELECT (SELECT Warning FROM Customers WHERE Customer_ID = @Customer_ID) AS Customer_Warning, (SELECT Warning FROM Sellers WHERE Seller_ID = @Seller_ID) AS Seller_Warning ```
The problem is you're getting a cartesian product of rows in each table where *either* column has the value you're looking for. I think you just want `AND` instead of `OR`: ``` SELECT c.Warning 'Customer_Warning', s.Warning AS 'Seller_Warning' FROM Customers c JOIN Sellers s ON c.Customer_ID = @Customer_ID AND s...
UNION or JOIN for SELECT from multiple tables
[ "", "sql", "sql-server", "join", "union", "" ]
I want to select items from TableB that have Start Date between one of the date ranges in VacationHistory (TableA) table. Lets say I have VacationHistory datatable (TableA) that has Start and End date values. What I need to do is to compare a date from another datatable (TableB) to be between date ranges in VacationHi...
If you just want to find the rows in TableB that have a Start Date in any of the date ranges in TableA you can use a correlated`exists`: ``` select * from TableB b where exists ( select 1 from TableA a where b.StartDate between a.StartDate and a.EndDate ) ``` [Sample SQL Fiddle](http://www.sqlfiddle.co...
A Simple `INNER JOIN` is what you need. ``` SELECT DISTINCT b.id, b.StartDate FROM TableB b JOIN TableA a ON b.StartDate BETWEEN a.StartDate AND a.EndDate ``` Or ``` SELECT * FROM TableB INNER JOIN (SELECT Min(StartDate) StartDate, Max(EndDate) EndDate ...
Compare Date from TableB to several date ranges in TableA: Building WHERE statement
[ "", "sql", "sql-server", "t-sql", "date", "between", "" ]
**sample\_data** ``` id_type,seq_no,acct_name,_acct#,address 12345,67,jiimm,,167 s.40th st 12345,67,jiimm joe the 3rd,,167 s.40th st 12345,67,jiimm 12345,67,,0981_1,po box 1234 12345,80,Lee,,1234 street ave 12345,80,Lee 12345,80,,588_1,109 road st ``` **CODE** ``` SELECT `ID`_type, seq_no, MAX(`acct_na...
This gives you what you're looking for, but read my comment / question underneath your question above. There is an ambiguous "pick one row from many" situation that needs clarification. In that ambiguous situation, you imply that rules call for delivering the minimum non-blank account name, which this code does, but yo...
``` SELECT D1.id_type , D1.seq_no , IFNULL(D1.acct_name, (SELECT MIN(acct_name) FROM data D WHERE D.id_type = D1.id_type AND D.seq_no = D1.seq_no)) t , IFNULL(D1.acct_no, (SELECT MAX(acct_no) FROM data D WHERE D.id_type = D1.id_type AND D.seq_no = D1.seq_no)) s , D1.address FROM data D1 WHERE D1.address IS NO...
combining rows in same table sql
[ "", "mysql", "sql", "max", "" ]
we develop the sql scripts in oracle sql developer and in production dba execute the same in oracle sql plus. The problem is if we insert a line break ``` Create table test( text number(10) ``` The line break is causing the scripts to fail, do you know how to fix this in sqlplus? Also we generate the scripts u...
Try adding: ``` set sqlblanklines on ``` to the start of your sql script.
It's not the line break, it's the empty line that causes the problem: ``` Create table test( -- here you have it text number(10) ``` The solution is simple - delete the empty line.
line breaks in sqlplus
[ "", "sql", "oracle", "oracle11g", "sqlplus", "" ]
I'm guessing there is a quick and easy solution to this but I've tried a number of different methods and keep hitting a stone wall. Tried searching a LOT both here and elsewhere but I don't think I am using the right words to clarify what I want to know (as per my confusing subject!). My apologies if this is a duplicat...
I'm not 100% that I understand what you are looking for. I think it is fees of a certain type applied to a particular meeting for a particular client. If so, your basic query is on the right track, but it needs a `group by` and some simplification in the `case` (the `case` is redundant with the `where`): ``` select c....
To find the instances where the system may have erroneously charged multiple copies of the same type of fee to a client, we can use `GROUP BY` and then check total clients in the meeting and total fee\_ids per meeting are matching using `HAVING` clause. The below query will return all such meetings, where there is dis...
Finding IDs that join with multiple alternate IDs matching criteria
[ "", "sql", "oracle", "" ]
java datetime (date.getTime()) is stored as string in mysql field. How can we convert this to sql date using sql query. I am using mysql database. Is there any sql function available? For example - This is stored (1416231812348) for today's date in db. Thanks for suggestions.
Java is returning the date as a long, to convert it you can use: ``` SELECT FROM_UNIXTIME(event_time) FROM MY_TABLE ``` If you get an error, try the following (after testing, I can see that your data is stored in milliseconds so you need to use this method): ``` SELECT FROM_UNIXTIME(event_time/1000) FROM MY_TABLE ``...
most probably you have recorded from: ``` System.currentTimeMillis() ``` so: ``` select DATE_FORMAT ( from_unixtime( your_table_field / 1000 ) , '%e %b %Y'); ``` you can change the date format as you like.
converting java time to sqldate in query
[ "", "mysql", "sql", "" ]
I have a column called `Indicator` in a table. It contains `Y`, `N`, `NULL`, or just blank. What does the following two logic do? ``` coalesce(Indicator, 'N') = 'N' coalesce(Indicator, 'N') = 'Y' ``` It doesn't seem just to return the rows where `Indicator` equals `N` or `Y`. Is there something else going on?
For each condition there's a different answer For ``` coalesce(Indicator, 'N') = 'N' ``` You get ``` coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False coalesce(Null, 'N') = 'N' --> 'N' = 'N' --> True ``` and for ``` coalesce(Indicator, 'N') = 'Y' ``` you get ``` co...
The logic does two things. Functionally, the first expression is equivalent to: ``` (Indicator = 'N' or Indicator is null) ``` In addition, it also prevents an index from being used on `indicator` (in most databases). For a binary indicator, the use of the index is typically of minor importance. In addition, SQL opt...
coalesce in SQL
[ "", "mysql", "sql", "sql-server", "" ]
I am a beginning SQL programmer - I am getting most things, but not EXISTS. It looks to me, and looks by the documentation, that an entire EXISTS statement returns a boolean value. However, I see specific examples where it can be used and returns part of a table as opposed to all or none of it. ``` SELECT DISTINCT P...
Subqueries such as with EXISTS can either be correlated or non-correlated. In your example you use a correlated subquery, which is usually the case with EXISTS. You look up records in SP for a given P.PNO, i.e. you do the lookup for each P record. Without `SP.PNO = P.PNO` you would have a non-correlated subquery. I.e...
You have actually created a `Correlated subquery`. `Exists` predicate accepts a subquery as input and returns TRUE if the subquery returns **any** rows and FALSE otherwise. The outer query against table `P` doesn't have any filters, so all the rows from this table will be considered for which the EXISTS predicate retu...
How does EXISTS return things other than all rows or no rows?
[ "", "sql", "sql-server", "" ]
I have a table called TransferRequest with two columns that are (receivingPrison, currentPrison). They both reference a table Prison with columns (prisonID, location). I need to have some sort of join to display the 'location' of both prison eg. Result: "Washington", "New York". I know to get the location from one tabl...
Maybe I'm missing something but if you just want to get the location names for the current and receiving prisons you could get them by joining the`prison`table twice: ``` SELECT rec_prison.location as 'Recieving Location', cur_prison.location as 'Current Location' FROM TransferRequest tr INNER JOIN Prison rec_pri...
A correlated subquery could do it: ``` SELECT P1.location AS location1 , (SELECT Prison.location FROM Prison JOIN TransferRequest ON Prison.prisonID = TransferRequest.receivingPrison ) AS location2 FROM Prison P1 JOIN TransferRequest T1 ON P1.prisonID = T1.currentPrison; ```
Select data from two rows of the same table
[ "", "mysql", "sql", "join", "" ]
I have a table that has 4 columns: Item, Year, Month, Amount. Some of the values for Amount are null and when that happens I want to fill those values in with the previous Amount value that is not null. I can easily do this with the LAG function when there is only one null value but when there are multiple in a row I a...
**last\_value** with IGNORE NULLS works fine in Oracle 10g: ``` select item, year, month, amount, last_value(amount ignore nulls) over(partition by item order by year, month rows between unbounded preceding and 1 preceding) from tab; ``` `rows between unbounded precedin...
Here is an approach. Count the number of non-null values before a given row. Then use this as a group for a window function: ``` select t.item, t.year, t.month, t.amount, max(t.amount) over (partition by t.item, grp) as new_amount from (select t.*, count(Amount) over (Partition by item order by yea...
Fill null values with last non-null amount - Oracle SQL
[ "", "sql", "oracle", "" ]
In my oracle DB, I have a table 'action' containing two columns, start\_time and end\_time (both date). I can query action duration for each action in seconds like this: ``` select (end_time-start_time)*24*60*60 as actionDuration from action ``` We have a 2 hour maintenance window, 00:00 - 02:00. I'd like to ignore t...
If my guess in comments is correct, then: ``` select a.id, max((end_time - start_time) * 1440) - sum(nvl((mend2 - mbeg2), 0) * 1440) duration from (select id, start_time, end_time, mbeg, mend, case when start_time between mbeg and mend then start_time else maint.mbeg end mbeg2, case wh...
This approach could really kill performance if there's a lot of time between the dates, and if you're running a report on multiple records, but might be worth a look. It requires a primary key for the action. I would consider adding a column to your table to store the elapsed time, and calculating it in an update trigg...
Oracle SQL - seconds between two dates, ignoring a maintenance window
[ "", "sql", "oracle", "date", "" ]
Records without customerId always have DT01-DT09 and WT01 and records with customerId have WIF... `CustomerId` is essentially missing from records with `DT` but it's that same customer. How could I select records to get them in one row? ![enter image description here](https://i.stack.imgur.com/vCSjQ.png) [Full Size](...
Figured it out myself. Problem in all answers above is that if you eliminate CustomerId before filtering on it - you will get other customer's data **(transactionversion 9 and 10 has two customers)**, the trick is to filter the records on customerid without selecing customerid from inner select - that way the rows wi...
you can use `GROUP BY` and get the maximum value among the Qcode value based on customer id, transaction detail id, product id, transaction version in your Sub query before the `PIVOT` ``` select tqs.transactiondetailid as transactiondetailid, q.productid as pr...
Oracle combine 2 rows into one with different join criteria
[ "", "sql", "oracle", "pivot", "" ]
I am trying to search and update record which start which a partcular number or fall with a range. I have made a query which works where values start with a particular number. I can't figure out how to do it with a range. for example I want to update the following values in products\_ean with " " ``` 255 201-230 -...
This will be a full table scan anyhow, so you can use a function on `products_ean` with no loss of performance. This said, you can get the query more readable, but probably not much faster. However, you can still try whether it is faster, to take the three leading digits and compare these: ``` UPDATE products SET prod...
I don't think its going to be faster but its another alternative: To Find: ``` SELECT * FROM products WHERE products_ean REGEXP '^(200|020|023|027|042|221|209|041|049|026|025|299)' ``` To Replace: ``` UPDATE products SET products_ean = '' WHERE products_ean REGEXP '^(200|020|023|027|042|221|209|041|049|026|025|2...
is there a better way to write this query
[ "", "mysql", "sql", "" ]
I have following query which I am trying to optimize, the query runs in 3 seconds if I remove the join condition **I.ident\_id in (select distinct(ident\_id) from MISSING\_Images miss )** from below query but with this I takes 3 mins to execute. ``` SELECT IDENT_ID FROM tbl_IDENT I JOIN tbl_TA AN ON (AN...
You may try to replace ``` I.ident_id in (select distinct(ident_id) from MISSING_Images miss) ``` with ``` EXISTS (select 1 from MISSING_Images miss where miss.ident_id = I.ident_id) ``` And create an index on MISSING\_Images.ident\_id **EDIT**: The most direct solution will be: ``` EXISTS (select 1 from MISSING_...
Try a union instead, to begin with? ``` SELECT IDENT_ID FROM tbl_IDENT I JOIN tbl_TA AN ON AN.IDENT_ID = I.IDENT_ID AND AN.anchor_point = I.c_id JOIN tbl_AB A ON A.A_ID = I.A_ID JOIN tbl_FULL_ARCHIVE FT ON FT.ARCHIVE_ID = I.ARCHIVE_ID WHERE (I.DATA_STATUS = 'ACTIVE' OR I.DATA_STATUS = 'INACTIVE') AND ...
Slow query with multiple joins
[ "", "sql", "oracle", "oracle10g", "" ]
I am trying to display **all the columns** available in the table **EXCEPT IDENTITY COLUMN**. Is it possible? Pseudo code would be something like this. ``` SELECT * FROM Tab1 WHERE IDENTIY = NULL ``` or ``` SELECT * FROM Tab1 WHERE IDENTIY <> 'YES' ``` This is obviously invalid. But I want to achieve something lik...
try like this: `sys.columns`=Contains All Columns regarding to Particular Database `sys.tables`=Contains All Tables regarding to Particular Database `sys.identity_columns`=Contains All identity Columns regarding to Particular Database So Result Can be Generated By `joins` with `is_identity=1` and Exclude Identity c...
Try this. Use `Sys.columns` table to get the column list without `identity column`. Then use `Dynamic SQL` to generate column list and execute the query ``` declare @ collist varchar(max)='',@ sql nvarchar(max) select @collist += ','+name from sys.columns where object_name(object_id)='Tab1' and is_identity <> 1 select...
Selecting All the columns except IDENTITY Column
[ "", "sql", "sql-server", "vbscript", "" ]
Yesterday I posted a question regarding oracle sql query being repeated. [How to remove repeated lines in an Oracle SQL query](https://stackoverflow.com/questions/26965909/how-to-remove-repeated-lines-in-an-oracle-sql-query) How do I modify the SQL Query with JOIN if I have multiple parent and child tables? ``` SELE...
USE `UNION` and get the values from all tables and then do one JOIN with COMMON\_TABLE ``` SELECT table_id FROM ( SELECT t1.table_id FROM TABLE_ONE t1 WHERE t1.table_name = 'TEST_ONE' UNION SELECT t2.table_id FROM TABLE_TWO t2 WHERE t2.table_name = 'TEST_TWO' UNION SELECT tc1.table_id FROM T...
Did you try this? ``` select table_id from ( select table_id, cmn.column_one, cmn.column_two etc ) derived_table where column_one > 20 and column_two <= 30 ```
How to remove repeated lines in an Oracle SQL query for multiple parent and child tables
[ "", "sql", "oracle", "join", "" ]
I am trying to find the difference between today's date and a value that is a concatenation of mulitple values but begins with an 8 digit date without any dashes or forward slashes. There's something wrong with my syntax I believe, but I'm not yet skilled enough to see what I'm doing incorrectly. Here is what I have so...
I think your have data where the left 8 is not a valid date in yyyymmdd format. Your can run the following query to find them ``` select batchid, isdate(Left(batchid, 8)) from [Table] where isdate(Left(date, 8)) = 0 ``` This is the correct syntax to your query. Your original example had an extra parenthesis which I a...
This was may error. I was working with another table and forgot batchID was not the same for both. The concatenated batchID in the table I posted a question about can't be converted to a date.
Using DateDiff() to find the difference between getDate() and a concatonated value
[ "", "sql", "sql-server", "concatenation", "datediff", "date-conversion", "" ]
I would like to change the manner in which the mileage is represented in the database. For example, right now the mileage is represented as 080+0.348; this would mean that this particular feature is at mileage point 80.348 along the roadway corridor. I would like to have the data represented in the database in the latt...
One thing you could try is to pick the string value apart into its component pieces and then recombine them as a number. If your data is in a table called TEST you might do something like the following: ``` select miles, fraction, nvl(to_number(miles), 0) + nvl(to_number(fraction), 0) as milepoint from (selec...
Using the answer provided above, I was able to expand it to get exactly the answer i needed. Thanks a ton to everyone who helped! Here is the query i ended up with: ``` select distinct nrlg_dept_route,corridor_code_rb,nrlg_county,next_county, nvl(to_number(miles), 0) + nvl(to_number(fraction), 0) as milepoint ...
How to change mileage representation forms in sql
[ "", "sql", "oracle", "data-conversion", "" ]
There is table of numbers containing values [1,1,2,3,7,3,4,2,7] I want to select only duplicates so output set would contain [1,2,3,7] so 4 is filtered out. I have code that I did like this: ``` DROP TABLE #tempTable; SELECT [numbers] as nums, COUNT(*) as cny INTO #tempTable FROM [testBase].[dbo].[numbers] group b...
The same in one query. Conditions that are made after **GROUP BY** should be added to **HAVING** clause. ``` SELECT [numbers] as nums, COUNT(*) as cny FROM [testBase].[dbo].[numbers] GROUP BY numbers HAVING COUNT(*) > 1 ``` More on this [HAVING (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms180199.aspx...
Try this:- ``` SELECT [numbers] AS NUM FROM TAB_NAME HAVING COUNT([numbers]) > 1; ```
Select from another select without temporary table?
[ "", "sql", "sql-server", "" ]
## Question I would like to pull all assets from a database which is a certain amount of years old. Is this statement correct? ## Background The database is called `AssetRegister` The table is called `dbo.Assets` the column is called `AcquiredDate` ## Statement so far ``` SELECT * FROM dbo.Assets WHERE AcquiredD...
``` SELECT * FROM dbo.Assets WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8 ``` For an performance optimized query look at [@Horaciuxs answer](https://stackoverflow.com/a/26993036/575376).
The answer by @Juergen bring the right results: ``` SELECT * FROM dbo.Assets WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8 ``` But, the SQL optimizer can't use an index on AcquiredDate, even if one exists. It will literally have to evaluate this function for every row of the table. For big tab...
SQL Server: How to get rows where the date is older than X years?
[ "", "sql", "sql-server", "" ]
I have a very simple script in TSQL that *tries* to convert a timestamp in milliseconds to a `DATETIME` data type. This also includes the local time offset. ``` DECLARE @Time AS BIGINT SET @Time = 1413381394000 SELECT DATEADD(MILLISECOND, @Time - DATEDIFF(MILLISECOND, GETDATE(), GETUTCDATE()), CAST('1...
Your calculation for local offset has the potential to be wrong by an hour due to Daylight Savings Time. `DATEDIFF(MILLISECOND, GETDATE(), GETUTCDATE())` will only get the current offset and not the offset for the given date. Conversions to and from UTC and local time are generally best handled in application or SQLCLR...
[`DateDiff()`](http://msdn.microsoft.com/en-us/library/ms189794.aspx) does indeed return an int, but I suspect that it's [`DateAdd()`](http://msdn.microsoft.com/en-us/library/ms186819.aspx) that's giving you the error message. You'll need to work in that precision, unfortunately, as you said you wanted to avoid, as yo...
T-SQL - Arithmetic overflow while working with milliseconds
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a View which has a SQL Script as: ``` Select a.iAssetId, ac.eEventCode, vm.dtUTCDateTime, g.iGeofenceId, g.sGeofenceName, c.sCategoryName, c.iCategoryId, s.sSiteName, s.iSiteId, CASE WHEN ac.eEventCode = 6 THEN vm.dtUTCDateTime ...
If your eventcode is always going to be 6 and 7, then you can just join to that table twice using that clause in the join itself. I think I've got the rest of your schema joined up properly below, but if not, you can adjust it around to fit. ``` Select a.iAssetId, vmEnter.dtUTCDateTime, g.iGeofenceId, ...
Im gonna guess that eventcode = 6 means thats the intake time if so two of your data paris dont make much sense as the exit time is before the intake time, The Query below only accounts for when amd if eventcode 6 = intake time and the fact that exit time should be before entertime. query is based on the output you p...
Merge two rows with condition SQL View
[ "", "sql", "sql-server", "sql-view", "" ]
I have a standard user table. Now each user can add an unknown number of languages to his profile. What is the best way of storing the languages for each user? I want to query only **once** to fetch a user and all his corresponding languages. What is the best design? Example: ``` User ==== id name ---------- ...
That's a many to many relationship (a user can have many languages, and viceversa) so to normalize the DB you should do a new table containing the two Foreign Keys (call it user\_x\_languages): ``` user_x_languages ================ user_id lang_id 99 44 99 45 ``` you would need to remove the userid...
You may create a many-to-many relationship table. Like this: Table "Users" ``` user_id | name 99 peter 100 tim ``` Table "Languages" ``` language_id | language 44 en 45 fr ``` Table "User\_to\_language" ``` User_id | Language_id 99 45 100 45 100 46 ``` Or, if...
How to store variable number of languages per user?
[ "", "mysql", "sql", "" ]
I have got a table in DataBase. Table consists of two columns. First column for DeliveryDate it has a type of DATETIME Second column for DeliveryTime it has a type of VARCHAR Here is a little example of table data ``` DeliveryDate - DeliveryTime 2014-11-06 00:00:00.000 - 15:00 2014-11-...
This is due to the Query Optimizer and how it optimizes the query. It most likely assumed it could rearrange a step or two to make things faster, not realizing that the data issue existed. This is why * doing the `TOP 620` worked when there were only 92 rows as it was likely affecting the way the optimizer built the p...
It's strange but when I've separated `CAST` in a scalar function all begin to work fine. But very slow :( ``` CREATE FUNCTION [dbo].[ConcatDateAndTime] ( @DatePart DATETIME, @TimePart VARCHAR(50) ) RETURNS DATETIME AS BEGIN RETURN @DatePart + RIGHT(COALESCE(@TimePart,'00:00'),5) END ```
strange CAST() behaviour in SQL Server 2008 R2
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I need to generate alphanumeric random number with 6 character length and it should contain Numerics, Alphabets (Both Lowercase and Uppercase) check the query below. **I NEED TO IMPLEMENT IN FUNCTION. (In function is it possible to use NEWID(), RAND()).** ``` SELECT SUBSTRING(CONVERT(VARCHAR(255), NEWID()),0,7) ``` ...
As in function we cannot use NEWID() OR RAND() first need to create VIEW **For Function** ``` CREATE VIEW NewID as select newid() as new_id DECLARE @new_id VARCHAR(255) SELECT @new_id = new_id FROM newid SELECT @Password = CAST((ABS(CHECKSUM(@new_id))%10) AS VARCHAR(1)) + CHAR(ASCII('a')+(ABS(CHECKSUM(@new_id)...
Try this: ``` select cast((Abs(Checksum(NewId()))%10) as varchar(1)) + char(ascii('a')+(Abs(Checksum(NewId()))%25)) + char(ascii('A')+(Abs(Checksum(NewId()))%25)) + left(newid(),5) Random_Number ``` Also, ``` DECLARE @exclude varchar(50) SET @exclude = '0:;<=>?@O[]`^\/' DECLARE @c...
How to Generate Alphanumeric Random numbers using function in SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "select", "stored-procedures", "" ]
I dont know how I can do this sql query, probably its simple but I don't know how i can do it. I have 2 tables: ``` Table_Articles: COD NAME 1 Bottle 2 Car 3 Phone Table_Articles_Registered COD_ARTICLE DATE 1 05/11/2014 1 06/11/2014 1 07/11/2014 2 ...
Can't you just do this?: ``` SELECT Table_Articles.COD, Table_Articles.NAME, ( SELECT MAX(Table_Articles_Registered.DATE) FROM Table_Articles_Registered WHERE Table_Articles.COD_ARTICLE=Table_Articles.COD ) AS DATE FROM Table_Articles ```
I think this is a basic aggregation query with a `join`: ``` select a.cod, a.name, max(ar.date) as date from Artiles a join ArticlesRegisterds ar on ar.cod_article = a.cod group by a.cod, a.name ```
How to get a correlated subquery as column
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I want to retrieve records for certain days . ``` DateTime BETWEEN DATEADD(dd,-1* 30,GETDATE()) and GETDATE() ``` The above code gets all the records from todays date to 30 days back, but I only want the records thats on the 30th day and not all in between.How do I achieve this? But its not always going to be 30 da...
Return data for the date that is -30th day from today. ``` SELECT * FROM TABLENAME WHERE DATEDIFF(day, CONVERT(VARCHAR(10), GETDATE(),110), CONVERT(VARCHAR(10), COLUMNNAME,110)) = -30 ```
try this: this is Returns Todays Date=`18` ``` DATEPART(Day,MyColumn)=30 ```
how to retrieve records in sql when you pass in a certain day
[ "", "sql", "sql-server", "" ]
I'm working with a database structure similar to this one: <http://dev.mysql.com/doc/employee/en/sakila-structure.html> Table: **employees** Table with information about each employee. ``` +---------+----------+ | emp_no* | emp_name | +---------+----------+ | emp1 | John | | emp2 | Mike | | emp3 | R...
Assuming `emp_dept.Emp_no` is the relation between `employees.Emp_no` ``` Select * from employees e join emp_dept ed on e.emp_no = ed.emp_no and from_date = (Select Max(from_date) from emp_dept ed2 where ed2.emp_no = e.emp_no) ```
you can get the maximum date in a subquery and join with it. looks like you have a typo in the emp\_dept table entries, the emp\_no is not matching with employees table. In case a employee is currently working in deparment, does to\_date will be NULL? In such as case, you need to handle it in the sub query. ``` SEL...
Querying all data from a table joining ONLY the latest record from a junction table
[ "", "mysql", "sql", "database", "junction-table", "" ]
We have a table with events (as in calendar event with start and end times) that is regularily queried: ``` TABLE event ( `id` varchar(32) NOT NULL, `start` datetime, `end` datetime, `derivedfrom_id` varchar(32), `parent_id` varchar(32) NOT NULL ) ``` * The `parent_id` points to a calendar table that provid...
Try this: ``` SELECT e.* FROM `event` e # 'e' from 'event' LEFT JOIN `event` d # 'd' from 'derived'; `LEFT JOIN` gets ALL entries from `e` ON e.id = d.derivedfrom_id # match an event `e` with all those `d` derived from it WHERE d.id IS NULL # keep only events `e` without derived events `...
I suggest to group the events by their DERIVEDFROM\_ID or - if it is not a derived event their ID using MySQL's `IFNULL` method, see [SELECT one column if the other is null](https://stackoverflow.com/questions/5697942/select-one-column-if-the-other-is-null) ``` SELECT id, start, parent_id, text, IFNULL(derivedfrom_id,...
MySQL filter out self-references
[ "", "mysql", "sql", "performance", "" ]
I have example data in the table as follows: ``` id, name , parentid -------------------- 1 , jason , null 2 , john , 1 3 , abe , 2 4 , mary , 2 5 , yong , 4 6 , albert, 5 7 , jane , 3 8 , alex , 7 ``` How do I get the middle part of the tree data if I only want 2 levels from the selected `parentid` example ...
Check this query: just selected the Childs of current parent and child's childs. ``` DECLARE @SelectedID INT SET @SelectedID = 1 SELECT ID, NAME, PARENTID FROM #TABLE1 WHERE PARENTID = @SelectedID UNION ALL SELECT ID, NAME, PARENTID FROM #TABLE1 WHERE PARENTID IN (SELECT ID FROM #TABLE1 WHERE PARENTID = @Select...
This should get you what you need: ``` WITH CTE AS( SELECT ID,Name,parentID, 1 Depth FROM YourTable UNION ALL SELECT E.ID,E.Name,E.ParentID,Depth+1 Depth FROM YourTable E INNER JOIN CTE ON E.ParentID=CTE.ID) SELECT * FROM CTE WHERE Depth = 2 ``` NOTE that the where clause in the second select gets the depth, and...
SQL Server recursive function getting middle data tree
[ "", "sql", "sql-server", "performance", "" ]
## Problem I am trying to add a second join to a query however when i add the secone line ``` INNER JOIN dbo.Assets ON Assets.AssetTypeID = AssetTypes.AssetTypeID ``` SQL Server throws this error ``` Msg 1013, Level 16, State 1, Line 1 The objects "dbo.Assets" and "dbo.Assets" in the FROM clause have the same expos...
``` INNER JOIN dbo.Assets ON Assets.AssetTypeID = AssetTypes.AssetTypeID ``` here is some issue, assettypes is also a table? then why you are not join in your query. Always give alias name and try to make sort to understand as ``` SELECT Distinct --to remove un-wanted duplicate rows --I don't know, so you will add a...
This error happens when you reference a table at least twice in the `FROM` clause and you did not specify a table alias to either table so that SQL Server can distinguish one from the other. In your query you added `Assets` table in the `FROM` clause without any Alias name also `Assets` table in the `Inner Join` witho...
Correlation Names, how to use them?
[ "", "sql", "sql-server", "join", "" ]
I need the time difference between two times in minutes. I am having the start time and end time as shown below: ``` start time | End Time 11:15:00 | 13:15:00 10:45:00 | 18:59:00 ``` I need the output for first row as 45,60,15 which corresponds to the time difference between 11:15 and 12:00, 12:00 and 13:...
The following works as expected: ``` SELECT Diff = CASE DATEDIFF(HOUR, StartTime, EndTime) WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10)) ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) + REPLICATE(',60', DATEDIFF(HOUR, ...
Use [DateDiff](http://msdn.microsoft.com/en-us/library/ms189794.aspx) with MINUTE difference: ``` SELECT DATEDIFF(MINUTE, '11:10:10' , '11:20:00') AS MinuteDiff ``` Query that may help you: ``` SELECT StartTime, EndTime, DATEDIFF(MINUTE, StartTime , EndTime) AS MinuteDiff FROM TableName ```
Calculate time difference in minutes in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "datetime", "difference", "" ]
If I want to add 5 days to a date, I can do it using the `INTERVAL` function: ``` select create_ts + interval '5 days' from abc_company; ``` However, my table has a field called `num_of_days` and I want to add it to my create\_ts. Something like this: ``` select create_ts + interval num_of_days || ' days' from abc_c...
Simply multiply the value with an interval: ``` select create_ts + num_of_day * interval '1' day from abc_company; ``` Since Postgres 9.4 this is easier done using the `make_interval()` [function](https://www.postgresql.org/docs/9.4/functions-datetime.html): ``` select create_ts + make_interval(days => num_of_day) ...
You just need a working type cast. This kind is standard SQL. ``` select current_timestamp + cast((num_of_days || ' days') as interval) from abc_company; ``` This is an alternative syntax, peculiar to PostgreSQL. ``` select current_timestamp + (num_of_days || ' days')::interval from abc_company; ``` I prefer not tr...
Postgres INTERVAL using value from table
[ "", "sql", "postgresql", "" ]
I need to query for rows from 3 different tables based upon certain `WHERE` criteria. My tables are: * regions * profiles * usermeta The profiles table has two foreign keys, user\_id and region\_id which reference the following tables. The users table has an id, first\_name and last\_name column. I need to get the ...
Do a `JOIN` between all the tables. Below query is the assemble of the information provided by you in posts ``` select users.first_name, users.last_name, regions.name, profiles.id, profiles.certs, profiles.title from users left join profiles on profiles.user_id = users.id left join region on profiles.region_id = re...
The syntax for a join looks something like this: ``` SELECT stuff FROM firstTable JOIN secondTable ON firstTable.someColumn = secondTable.matchingColumn ``` In this case, I also recommend using table aliases (just adding an alias right after the table name is enough). This is just a simple push in the right direction...
Syntax for joining multiple tables
[ "", "mysql", "sql", "wordpress", "join", "" ]
How can I change column text Not Exists when it is empty or null ? My query : ``` Select TOP 1 ISNULL(NULLIF(DR.Name,''),'Not Exists') as Name, DR.Name as Name ,Coalesce(NullIf(rtrim(DR.Name),''),'Not Exist') as Name, Name = case when DR.Name is null then 'Not Exists' when DR.Name='' then 'Not Exists' el...
If you just need a single column, then you can use a sub-select, this way when no rows are returned by the query you will still get `not exists`: ``` SELECT Name = ISNULL(( SELECT TOP 1 NULLIF(DR.Name,'') FROM Transfer AS TR INNER JOIN Driver AS DR ...
I'm not entirely sure I understand your question, but if you are trying to catch nulls and empty strings "in one go", try this: ``` select TOP 1 case when length(trim(coalesce(DR.Name, ''))) = 0 then 'Not Exists' else DR.Name as Name .... ``` The `coalesce` catches the `NULL`s and sets a replacement va...
Check and Change for empty or null value of column in SQL?
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
Is there a way, through the `information_schema` or otherwise, to calculate how many percent of each column of a table (or a set of tables, better yet) are `NULL`s?
[Your query](https://stackoverflow.com/a/27019681/939860) has a number of problems, most importantly you are not escaping identifiers (which could lead to exceptions at best or SQL injection attacks in the worst case) and you are not taking the schema into account. Use instead: ``` SELECT 'SELECT ' || string_agg(conca...
In PostgreSQL, you can easily compute it using the statistics tables if your autovacuum setting is on (check it by SHOW ALL;). You can also set the vacuum interval to configure how fast your statistics tables should be updated. You can then compute the NULL percentage (aka, null fraction) simply using the query below: ...
Count how many percent of values on each column are nulls
[ "", "sql", "postgresql", "information-schema", "" ]
I am trying to run the below query in order to get ordered data from category\_child table and accordingly from the category table. select \* from category where id in (select child\_id from category\_child where category\_id=1 order by sequence); It's like ``` select * from category where id in (2,3,4); ``` and ``...
following query ``` select c.* from category c, category_child cc where cc.category_id=1 and c.id=cc.child_id order by cc.sequence; ``` will work, just a little change in condition in the answer given by Nir-Z and removing join.
Why not doing ``` Select c.* from category c join category_child cc on cc.id=c.category_id where cc.category_id=1 order by cc.sequence ```
how to get ordered result set while using in keyword in mysql
[ "", "mysql", "sql", "" ]
I have a table in SQL that is a list of users checking in to a website. It looks much like this: ``` id | date | status ------------------ ``` Status can be 0 for not checking in, 1 for checked in, 2 for covered, and 3 for absent. I'm trying to build one single query that lists all rows with `status = 0`, but also ...
# MySQL VERSION just join a count that is joined by id. ``` SELECT t.*, COALESCE(t1.status_3_count, 0) as status_3_count FROM yourtable t LEFT JOIN ( SELECT id, SUM(status=3) as status_3_count FROM yourtable GROUP BY id ) t1 ON t1.id = t.id WHERE t.status = 0 ``` note: this is doing the boolean sum (aka c...
Try a dependent subquery: ``` SELECT t1.*, ( SELECT count(*) FROM sometable t2 WHERE t2.id = t1.id AND t2.status = 3 ) As somecolumnname FROM sometable t1 WHERE t1.status=0 ```
SELECT with a COUNT of another SELECT
[ "", "mysql", "sql", "select", "" ]
I had written an stored procedure where selecting from one table(some columns have null data) and inserting into other table with out duplicates. part of my stored procedure code: ``` LOOP BEGIN SELECT ID INTO ROWCOUNT FROM TBL_EMPLOYEE WHERE NAME = TEMPTABLE.NAME AND AGE =...
I think you want to do this: ``` NAME = VALUE {in case of Some Value} ``` and ``` NAME IS NULL {in case the value is null} ``` ORACLE doesn't handles it by its own. I think this is a logical condition and this should be handled logically. Let me know if I have answered/understood you correctly?
You are going about the check in the wrong way. Eliminate both the `ROWCOUNT` variable and the loop altogether and use `NOT EXISTS()`: ``` BEGIN INSERT INTO TARGET_TABLE SELECT ..... FROM DUAL WHERE NOT EXISTS ( SELECT * FROM TBL_EMPLOYEE WHERE nvl(NAME,0000) = nvl(TEMPTABLE.NAME,0000) AND nvl...
what is the alternative way to check for null with out using is null operator in oracle
[ "", "sql", "oracle", "plsql", "" ]
Is there a way to generate unique (distinct) random numbers in posgresql (and redshift in particular)? The following code generates 5 random integers from 1 to 10 *with* replacement: ``` SELECT round(random()*(10 - 1) + 1) from generate_series(1, 5); ``` Is there a way to generate a set of 5 random integers from 1 to...
You could use `generate_series` to generate all the numbers between 1 and 10, shuffle them in the `order by` clause and then take the top 5: ``` SELECT num FROM GENERATE_SERIES (1, 10) AS s(num) ORDER BY RANDOM() LIMIT 5 ```
Try These selects **1.)** ``` SELECT (9 * random())::int + 1 r_num FROM generate_series(1, 10) GROUP BY 1 LIMIT 5; ``` **2.)** ``` SELECT round(random()*(10 - 1) + 1)::int r_num FROM generate_series(1, 10) GROUP by 1 LIMIT 5; ```
Unique random integers in postgresql
[ "", "sql", "postgresql", "random", "amazon-redshift", "" ]
I need help with a SQL server query. I'm trying to update an existing table (#Masterfile), based on the results of left joining the table with another outside source (table 2). Row 6 is basically a flag that says whether the ID exists in table b or not. I am new to sql (just started learning a couple of weeks ago) so m...
You just need to move the case around so it's like this: ``` select distinct a.column1 , a.column2 , a.column3 , a.column4 , a.column5 , case when x.column9 is not NULL then 1 else 0 end AS column6_flag , a.column7 , x.column9 from #Alldata a left join ( select m.column9 from #Masterfile m left join table2 n on m.i...
Replace `a.column6_flag` with just `column6_flag` ``` column6_flag = case when x.column9 is not NULL then 1 else 0 end ```
Updating sql table with results from left join (sql server)
[ "", "sql", "sql-server", "" ]
How to remove the last numbers from the data and group in tsql , Query `select browser from Table1 group by browser` Result ``` Chrome11 Chrome28 Chrome30 Chrome31 Chrome32 Chrome33 Firefox12 Firefox22 Firefox30 Firefox32 Firefox33 IE10 IE7 IE8 IE9 IEMobile IEMobile10 InternetExplorer11 Mozilla Opera9 Sa...
this will Work For You .. ``` select distinct browser from ( select REPLACE (REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE (browser, '0', ''),'1', ''),'2', ''),'3', ''),'4', ''),'5', ''), '6', ''),'7', ''),'8', ''),'9', '') as browser from TestTable group by browser) temp ```
You could do something like this: **Test data:** ``` DECLARE @tbl TABLE(browser VARCHAR(100)) INSERT INTO @tbl VALUES ('Chrome11'),('Chrome28'),('Chrome30'), ('Chrome31'),('Chrome32'),('Chrome33'), ('Firefox12'),('Firefox22'),('Firefox30'), ('Firefox32'),('Firefox33'),('IE10'), ('IE7'),('IE8'),('IE9'),('IEMobile'), ...
Remove last number digit in T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to convert my query from inner join to straight join. My original query was: `SELECT COUNT(*) FROM x AS t1 INNER JOIN x AS t2 USING (id);` And I'd like to simply replace inner join to straight join: `SELECT COUNT(*) FROM x AS t1 STRAIGHT_JOIN x AS t2 USING (id);` The first query executes as expected but the...
Yes, MySQL disallows straight join with USING. The syntax rules in <http://dev.mysql.com/doc/refman/5.6/en/join.html> show this: ``` join_table: table_reference [INNER | CROSS] JOIN table_factor [join_condition] | table_reference STRAIGHT_JOIN table_factor | table_reference STRAIGHT_JOIN table_factor ON condit...
I think you can go for `NATURAL JOIN` in MySQL like ``` SELECT COUNT(*) FROM x AS t1 NATURAL JOIN x AS t2; ```
Does MySQL allow using syntax with straight join?
[ "", "mysql", "sql", "join", "rdbms", "" ]
``` CREATE TABLE GroovyExps_Tgt (EMPNO SMALLINT, FIRSTNAME VARCHAR(20) NOT NULL, MIDINIT CHAR(1) NOT NULL, LASTNAME VARCHAR(15) NOT NULL, SALARY_INT INT, SALARY_Decimal DECIMAL, SALARY_Numeric NUMER...
MS SQL Server supports `Datetime` upto 1000 miliseconds. these queries will explain problem : ``` select CAST('2014-08-22 10:00:00.000000' as datetime) select CAST('2014-08-22 10:00:00.000' as datetime) ```
You're missing the time part of the data you are trying to insert under the `BIRTHDATE` column. Try inserting `'1980-08-22 00:00:00.00'` instead of just `1980-08-22` if you don't have a time part for that value since the `datetime` data type requires both date and time values.
SQL SERVER 2008 data Insertion Error
[ "", "sql", "sql-server-2008", "date", "" ]
i have 10 table and more than 10000 record that contain `` how can search `` and replace this in DB? since the `` equal `0xEF,0xBB,0xBF` how can search this? i use this code ``` WITH foo(myvarbincolumn) AS ( SELECT text from BPM_Letters ) SELECT * FROM foo WHERE CONVERT(VARCHAR(max), myvarbincolumn) COLL...
I wrote a query to find that weird character via the query below: ``` SELECT cast(LEFT(text,1) AS VARBINARY(MAX)) from BPM_Letters ``` and the result was 0xFFFE. So I wrote this query and it worked perfectly: ``` UPDATE BPM_Letters Set text=REPLACE(text,0xFFFE,''); ```
What about this CTE: ``` StripBOM AS ( SELECT CASE WHEN LEFT(text,3) = 0xEFBBBF THEN CONVERT(varbinary(max),SUBSTRING(text, 4, LEN(text))) ELSE text END AS text FROM BPM_Letters ) ``` It should provide you with a new table where all BOM character...
Search and Replace Byte Order Mark In Sql Server
[ "", "sql", "sql-server", "search", "encoding", "byte-order-mark", "" ]
Is there a SQL command for starting at a certain amount of results? Example: ``` SELECT * FROM table WHERE ID=1 BEGIN AT 100 ```
> SELECT \* FROM table WHERE ID=1 LIMIT 100,500; result will show 500 value from 100
Try to create a temporary **Row Number** then use that as criteria for your starting point which is in your case 100, like: ``` SELECT * FROM ( SELECT (@RowNum := @RowNum + 1) as Row, tbl.* FROM tbl, (SELECT @RowNum:=0) ctr ) t WHERE Row >= 100 ``` See `Demo`
MYSQL start at nth result (opposite of LIMIT)
[ "", "mysql", "sql", "sql-limit", "" ]
I am trying to get a selected item from datagridview to show in a combobox. I have done ``` ComboBox1.Text = DataGridView1.CurrentCell.Value ``` However, I need it to display two fields in the combobox from the datagrid. Is there a way to do the above with a SQL query? Because I need to concat a query to display in ...
You could try doing something like this. ``` ComboBox1.Text = DataGridView1.SelectedRows.Item(0).Cells(0).FormattedValue + " " + DataGridView1.SelectedRows.Item(0).Cells(1).FormattedValue ``` or ``` ComboBox1.Text = DataGridView1.SelectedRows.Item(0).Cells(0).FormattedValue + " " + _ ...
try using ComboBox.Add('cellValue1 + 'cellvalue2') ComboBox1.Text will just set the original text, but will not create a list of data
Selected item from Datagridview to Show in ComboBox
[ "", "sql", "vb.net", "drop-down-menu", "datagridview", "combobox", "" ]
I have a problem I can't get my head around. I have a table of events and a table of users. Some events are chargeable and some are not. What I want to establish is the number chargeable days per week month and year for every user. Here is the data... ``` ID FromDate ToDate isChargeable Username 1 2014...
Try this. If you have Unique ID's try this. ``` create table #calen(ID int, FromDate date, ToDate date,isChargeable char(1),Username varchar(20)) INSERT #calen VALUES (1,'2014-11-03','2014-11-04','Y ','AUser'), (2,'2014-11-04','2014-11-06','Y','AUser'), (3,'2014-11-07','2014-11-07','Y','AUser') SE...
If all the ID values are not unique we can have the below query: ``` SELECT ID, FromDate, ToDate, isChargeable, Username, CASE WHEN EXISTS(SELECT ToDate FROM UserTable B WHERE A.FromDate = B.ToDate AND A.UserName = B.UserName AND A.ID <> B.ID) THEN DATEDIFF(day, FromDate, ToDate) ELSE DATEDIFF(day, FromDat...
Working days SQL query
[ "", "sql", "sql-server", "t-sql", "" ]
``` SELECT sku_master.sku , sku_master.description , sku_master.min_on_hand , sku_master.max_on_hand , location_inventory.qty_on_hand FROM [FCI].[dbo].[location_inventory] JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku WHERE min_on_hand > 0 GRO...
This will get you the total by SKU: ``` SELECT sku_master.sku , sum(location_inventory.qty_on_hand) as total_qty_on_hand FROM [FCI].[dbo].[location_inventory] JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku WHERE min_on_hand > 0 GROUP BY sku_master.sku ``` If you want other attributes ...
``` SELECT sku_master.sku , sku_master.description , sku_master.min_on_hand , sku_master.max_on_hand , sum(location_inventory.qty_on_hand) FROM [FCI].[dbo].[location_inventory] JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku WHERE min_on_hand > 0 ...
Remove Duplicates and SUM
[ "", "sql", "" ]
Here is my schema: ``` create TABLE sample ( userId INT, score INT ); INSERT INTO sample VALUES (1,10); INSERT INTO sample VALUES (1,15); INSERT INTO sample VALUES (1,20); INSERT INTO sample VALUES (2,100); INSERT INTO sample VALUES (2,200); INSERT INTO sample VALUES (2,500); INSERT INTO sample VALUE...
I can only say how I would solve this with DB2 SQL I would create a temponary table where you can save the average score for each user and select the maximum value from it. This is possible in sql plus too: [How to create a temporary table in Oracle](https://stackoverflow.com/questions/2671518/how-to-create-a-temporary...
``` select userid from (select userid, rank() over (order by avg(score) desc) rw from sample group by userid) where rw = 1; ``` Calculate avg score for each user, than calculate the rank of each score using analytic functions (which are performed after the grouping). Lastly get the rows with the first rank
SQL- Finding the users with the Maximum average score
[ "", "sql", "oracle", "" ]
My requirement is to get each client's latest order, and then get top 100 records. I wrote one query as below to get latest orders for each client. Internal query works fine. But I don't know how to get first 100 based on the results. ``` SELECT * FROM ( SELECT id, client_id, ROW_NUMBER() OVER(PARTITION BY ...
Assuming that create\_time contains the time the order was created, and you want the 100 clients with the latest orders, you can: * add the create\_time in your innermost query * order the results of your outer query by the `create_time desc` * add an outermost query that filters the first 100 rows using `ROWNUM` Que...
you should use rownum in oracle to do what you seek ``` where rownum <= 100 ``` see also those answers to help you [limit in oracle](https://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-ordering) [select top in oracle](https://stackoverflow.com/questions/345...
How to Select Top 100 rows in Oracle?
[ "", "sql", "oracle", "" ]
Imagine I have this tables: ![this tables](https://i.stack.imgur.com/1vVWk.png). What I need is to get the Data that exists in A but not in B, in this case my SELECT will have to return "2". I've done it before, but right know I can't remember how. I suppose it was something like this: ``` SELECT a.* FROM A as a LEF...
You're just missing a filter: ``` SELECT a.* FROM A as a LEFT JOIN B AS b ON b.column = a.column WHERE B.column IS NULL ```
If `B` could have multiple rows that match `A`, then this query would be more appropriate: ``` SELECT a.* FROM A as a WHERE NOT EXISTS(SELECT NULL FROM B WHERE b.column = a.column) ```
Select data that exists in A but not in B
[ "", "sql", "select", "join", "left-join", "exists", "" ]
I have looked high and low on SO for an answer over the last couple of hours (subqueries, CTE's, left-joins with derived tables) to this question but none of the solutions are really meeting my criteria.. I have a table with data like this : ``` COL1 COL2 COL3 1 A 0 2 A 1 3 A 1 ...
If all you want is the first row with a ColB-ColC combination, the following will do it: ``` select min(id) as id, colB, colC from tbl group by colB, colC order by id ``` [SQL Fiddle](http://sqlfiddle.com/#!3/b8ebca/5)
This should work: ``` ;WITH numbered_rows as ( SELECT Col1, Col2, Col3, ROW_NUMBER() OVER(PARTITION BY Col2, Col3 ORDER BY Col3) as row FROM AppConfig) SELECT Col1, Col2, Col3 FROM numbered_rows WHERE row = 1 ```
Removing rows in SQL that have a duplicate column value
[ "", "sql", "sql-server", "t-sql", "" ]
I have 3 DB table: ``` users: id, name posts: id, user_id, content post_likes: id, user_id, post_id ``` I want to fetch my whole user's likes, except likes that I did on my posts. In other words: Fetch all of my likes to other people's posts. How can I filter by a relationship's column `posts.user_id` when I'm act...
Try this one ``` SELECT * FROM post_likes pl LEFT JOIN posts p ON pl.post_id=p.id WHERE pl.user_id = 3 AND p.user_id != 3 ```
You can try with this ``` SELECT * FROM post_likes pls INNER JOIN posts p ON pls.post_id=p.id WHERE pls.user_id = 3 AND p.user_id != 3 ```
SQL - Filter by a relationship
[ "", "sql", "join", "relationship", "" ]
i am trying to copy table information from a backup dummy database to our live sql database(as an accident happened in our program, Visma Business, where someone managed to overwrite 1300 customer names) but i am having a hard time figuring out the perfect code for this, i've looked around and yes there are several sim...
What error message says is simply **"You cant add same value if an attribute has PK constraint".** If you already have all the information in your backup table what you should do is `TRUNCATE TABLE` which removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. Af...
The `MERGE` statement will be possibly the best for you here, unless the primary key of the `Actor` table is reused after a previous record is deleted, so not autoincremented and say record with id 13 on `F0001.dbo.Actor` is not the same "actor" information as on `FDummy.dbo.Actor` To use the statement with your code,...
Trying to copy one table from another database to another in SQL Server 2008 R2
[ "", "sql", "database", "sql-server-2008", "insert", "duplicate-data", "" ]
Can I have a condition of something like this: ``` SELECT * FROM table WHERE ? LIKE (column || '%') ``` Where the `?` is a string parameter value. For example, these **parameter value `?`** should return true when column is equal to `/admin/products` ``` /admin/products/1 /admin/products/new /admin/products/1/edit `...
The query: ``` SELECT * FROM table WHERE ? LIKE (col || '%'); ``` can be rewritten as (Postgres and MySQL): ``` SELECT * FROM table WHERE col = left(?, length(col)); ``` As commented, the first form should work as well. It can be tricky, though, because **characters with special meaning** for [`LIKE`](http://www.po...
Replacing ``` SELECT * FROM table WHERE ? LIKE (column || '%') ``` by ``` SELECT * FROM table WHERE ? LIKE CONCAT(column, '%') ``` works for me. Maybe || is used as logical or-operation instead of concatenation.
? LIKE (column || '%')
[ "", "mysql", "sql", "postgresql", "pattern-matching", "prefix", "" ]
I'm working on an app that should find 26-letter code in char(26) column out of 5,760,000 rows. I need to know how long it's going to take. I'm using MS SQL Server 2012 Express. I have a database which has only one table, `myTable`: ``` Idcolumn integer CodeColumn char(26) DateAndTimeColumn datetime ``` * Column...
``` ;WITH Numbers AS ( SELECT TOP (5760000) IdColumn = CONVERT(INT, ROW_NUMBER() OVER (ORDER BY s1.[object_id])) FROM sys.all_objects AS s1 CROSS JOIN sys.all_objects AS s2 CROSS JOIN sys.all_objects AS s3 ) INSERT INTO dbo.YourTable SELECT IdColumn, RIGHT(REPLICATE('0',26)+CONV...
Here is another way to do this using Lamak's excellent example. The only difference is this will create a 10 million row cte with zero reads. When you use sys.all\_objects it can get extremely slow because of all the I/O. ``` WITH E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)), ...
How to populate a table with 5 million rows in MS SQL Server?
[ "", "sql", "sql-server", "" ]
Need some help with an issue I'm having. This is the code: ``` Private Sub dtpStartDate_ValueChanged(sender As Object, e As EventArgs) Handles dtpStartDate.ValueChanged startDateChanged = 1 If endDateChanged = 1 Then cbLocation.Enabled = True cbLocation.Items.Clear() cbLocation.Items.A...
Here is the code now it's working: ``` Private Sub dtpStartDate_ValueChanged(sender As Object, e As EventArgs) Handles dtpStartDate.ValueChanged startDateChanged = 1 If endDateChanged = 1 Then cbLocation.Enabled = True Me.Refresh() cbLocation.Items.Add(New ListView...
I think something is wrong here ``` WHERE @startDate <= bookingEndDate AND bookingStartDate <= @endDate ``` try changing it to ``` WHERE bookingStartDate >= @startDate AND bookingEndDate <= @endDate ``` also put in mind to put ".Date" in your parameters.. ``` unbookedLocationsCommand.Parameters.AddWithValue("start...
Trouble with SELECT WHERE NOT IS/EXISTS Subquery (VB.NET, Access)
[ "", "sql", "vb.net", "subquery", "" ]
Suppose I have 2 data frames A and B that both have c1, c2, c3 as columns I wish to get a equivalent of ``` SELECT A.C1 AS "C1", A.C2 AS "C2", (A.C3 - B.C3) AS "C3" FROM A JOIN B ON (A.C1 = B.C1) AND (A.C2 = B.C2); ``` How do I perform the same operation in R without using for-loop? Edit:add example ``` A c1, c2, ...
Lots of possible answers here, but here's one (of the many) using just standard/base functions: ``` > foo <- merge(x = A, y = B, by.x = c("c1", "c2"), by.y = c("c1", "c2")) > foo$c3 <- foo$c3.x - foo$c3.y > foo <- foo[c("c1", "c2", "c3")] ``` Generally speaking, `merge(...)` is the function you seek to replicate SQL-...
Here is a `data.table` alternative. ``` A = read.table(text="c1, c2, c3 1, 1, 3 1, 2, 4 1, 2, 5 2, 1, 5", header=T, sep=",") B = read.table(text="c1, c2, c3 1, 1, 2 1, 2, 4 2, 1, 8", header=T, sep=",") setDT(A); setDT(B) # convert data frames to data tables setkey(A, c1, c2) # key columns c1, c2 for "joining" new_dt...
R data frame equivalence of SQL join and select
[ "", "sql", "r", "" ]
I have the following SQL statement where order by clause is passed dynamically . How can I pass 'order by asc and desc' dynamically to SQL? ``` SELECT table1.prod_id,table2.prod_name from table1 left outer join table2 ON table1.prod1 = table2.prod_id ORDER BY CASE WHEN :odb = 1 THEN prod_i...
You can do solutions like @TonyAndrews by manipulating numeric or data values. For `VARCHAR2` an alternative to dynamic SQL could be to have two expressions: ``` order by case when :sorting='ASC' then col1 end ASC, case when :sorting='DESC' then col1 end DESC ``` When `:sorting` has the value `'ASC'` the result...
If the column you are sorting by is numeric then you could do this: ``` order by case when :dir='ASC' then numcol ELSE -numcol END ``` For a date column you could do: ``` order by case when :dir='ASC' then (datecol - date '1901-01-01') else (date '4000-12-31' - datecol) end ``` I can't think of a sen...
SQL Dynamic ASC and DESC
[ "", "sql", "oracle", "sql-order-by", "" ]
I need to generate a full list of row\_numbers for a data table with many columns. In SQL, this would look like this: ``` select key_value, col1, col2, col3, row_number() over (partition by key_value order by col1, col2 desc, col3) from temp ; ``` Now, let's say in Spark I have an RDD of the form (...
The `row_number() over (partition by ... order by ...)` functionality was added to Spark 1.4. This answer uses PySpark/DataFrames. Create a test DataFrame: ``` from pyspark.sql import Row, functions as F testDF = sc.parallelize( (Row(k="key1", v=(1,2,3)), Row(k="key1", v=(1,4,7)), Row(k="key1", v=(2,2,...
This is an interesting problem you're bringing up. I will answer it in Python but I'm sure you will be able to translate seamlessly to Scala. Here is how I would tackle it: 1- Simplify your data: ``` temp2 = temp1.map(lambda x: (x[0],(x[1],x[2],x[3]))) ``` temp2 is now a "real" key-value pair. It looks like that: ...
How do I get a SQL row_number equivalent for a Spark RDD?
[ "", "sql", "apache-spark", "row-number", "rdd", "" ]
I assume there is a way of doing this from code, at least some good workaround. Please consider that I do not want to delete all tables (I've seen this command), just to delete rows from them but to keep existing schema and all constraints. Maybe I can somehow obtain the list of all tables from metadata and apply TRU...
You may do it this way: * Disable referential integrity using [`SET REFERENTIAL_INTEGRITY FALSE`](https://web.archive.org/web/20200413121749/https://www.h2database.com/html/commands.html#set_referential_integrity) * Get the list of all tables using [`SHOW TABLES`](https://web.archive.org/web/20200413121749/https://www...
For now, I came up with this solution... But still need to test it more thoroughly. ``` private void truncateDatabase () throws SQLException { String tempDir = System.getProperty("java.io.tmpdir"); File tempRestoreFile = new File(tempDir + File.separator + "tempRestore"); Connection connection = dataSource...
H2 - How to truncate all tables?
[ "", "sql", "database", "h2", "" ]