Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've recently imported some spatial data into SQL 2008 from SDF. During the import process, DateTime fields were imported as nvarchar(254). An example of how the data was imported is this: `'20130515103000'` In setting up my view, I used `SELECT CAST(survey_date AS DATETIME) AS Expr1` and have the following Error: > ...
It looks like you need some string manipulation as your date string isn't in a recognized format. There might be a simpler way, but this works in SQL Server: ``` DECLARE @string VARCHAR(255) = '20130515103000' SELECT CAST(LEFT(@string,8)+' '+SUBSTRING(@string,9,2)+':'+SUBSTRING(@string,11,2)+'.'+RIGHT(@string,2) AS D...
This is using `Stuff()` function. First change `yyyymmddHHMMSS` to `yyyymmdd HH:MM:SS` and then convert it to a `Datetime`. ``` --Example: Declare @mydate nvarchar(250) = '20130515103000' Select convert(datetime, stuff(stuff(stuff(@mydate, 9, 0,' '), 12,0,':'), 15,0,':')) --Applied to your table column Select conver...
CAST nvarchar to DATETIME
[ "", "sql", "sql-server", "datetime", "" ]
I am trying to delete a massive amount of users who have the email address from the domain: "shopchristianpump" I have a wordpress site and in the MySQL database trying to just list them all first: ``` SELECT * FROM `wp_users` WHERE `user_email` like 'shopchristianpump' ``` I know there are users in there with this ...
``` DELETE FROM wp_users WHERE user_email like '%@shopchristianpump%'; ```
Use wildcard operator (`%`). Wildcard means, that the content of the symbol's place could be anything. ``` DELETE FROM `wp_users` WHERE `user_email` LIKE '%@shopchristianpump.com'; ``` If shopchristianpump's domain name is different that .com, then replace it.
Delete Users from SQL database with a email like
[ "", "mysql", "sql", "wordpress", "" ]
I have this tables, ``` user id name visit id id_user (fk user.id) date comment ``` If i execute this query, ``` SELECT u.id, u.name, e.id, e.date, e.comment FROM user u LEFT JOIN visit e ON e.id_user=u.id ``` I get, ``` 1 Jhon 1 2013-12-01 '1st Comment' 1 Jhon 2 2013-12-03 '2nd Comment' 1 Jhon 3 20...
This should give you the last comment for every user: ``` SELECT u.id, u.name, e.id, e.date, e.comment FROM user u LEFT JOIN (SELECT t1.* FROM visit t1 LEFT JOIN visit t2 ON t1.id_user = t2.id_user AND t1.date < t2.date WHERE t2.id_user IS NULL ) e ON e.id_user=u.id ```
``` SELECT u.id, u.name, e.id, e.date, e.comment FROM user u LEFT JOIN visit e ON e.id_user=u.id ORDER BY e.date desc LIMIT 1; ```
GROUP BY LAST DATE MYSQL
[ "", "mysql", "sql", "date", "group-by", "having", "" ]
Currently I have this table (#tmp) in my TSQL query: ``` | a | b | |:---|---:| | 1 | 2 | | 1 | 3 | | 4 | 5 | | 6 | 7 | | 9 | 7 | | 4 | 0 | ``` This table contains IDs of rows that I want to delete from another table. The thing is, I cannot have the same 'a' matching up with multiple 'b' and vice-versa, ...
try this: ``` Select * from #tmp t Where Not exists(select * from #tmp where b = t.b and a < t.a) and Not exists(select * from #tmp where a = t.a and b < t.b) ```
Your problem statement is not well-defined. There are multiple ways that you could remove rows from the `@tmp`, enforcing the uniqueness of columns A and B. Here is one approach, which is to make A unique and then make B unique: ``` with todelete as ( select t.*, row_number() over (partition by a order by newid...
Avoiding duplicates in my result table
[ "", "sql", "t-sql", "match", "" ]
I'm having a problem with the query builder in MS Access 2010. I'm not able to join two tables where one has two references to the other. I have one table, Workers, with two columns, HumanFactor1 and HumanFactor2. Both of these point to table HumanFactors which consists of only two fields, ID and HumanFactor. This tabl...
You can add multiple instances of a table in a query that you create with the Query Builder. When you add the table the first time its alias will be just be the table name (e.g., [HumanFactors]) and when you add it the second time its name will be the table name with `_1` appended. You can change the aliases by clickin...
How 'bout this: ![enter image description here](https://i.stack.imgur.com/IqiAX.png) This will give you all the records where either human factor is Fatigue. Not exactly the way you had it, but might serve.
MS Access Inner Join Or
[ "", "sql", "ms-access", "ms-access-2010", "" ]
I think I am not doing the best thing I can in my designed DB architecture. Also I am using MySQL; I have 2 main tables: IMEIs and user; IMEIs structure: ``` +---------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+------...
> I can't save all IMEIs data in one table, since that will be huge table. If there is something relational databases a good at, that's managing huge number of rows in a single table. Assuming you use indexing properly, performance will scale **logarithmically** (i.e. the time to do various operations will raise much ...
`I can't save all IMEIs data in one table, since that will be huge table.` Why do you think this? One big table is often better than a database full of tables. If each table is the same, seriously consider making a big table. Then, if it goes slow, you can go about partitioning it (into PHYSICAL seperate parts), but ...
What do you think about my DB architecture?
[ "", "mysql", "sql", "database", "" ]
I'm building a SSIS package where I need to get data from the day before at 4:15:01 pm to today's date at 4:15:00 pm, but so far the only query that I know is how to get the day before. I am not sure how to also add hour, minute, and second to the same query. Can someone please show me how to add the hour, minute, and ...
Be very careful about precision here - saying you want things from 4:15:01 PM yesterday, means that at some point you could possibly lose data (e.g. 4:15:00.500 PM). Much better to use an open-ended range, and I typically like to calculate that boundary outside of the query: ``` DECLARE @today DATETIME, @today_at_1615...
I'd think this would work similarly. ``` DECLARE @today DATETIME, @today_at_1615 DATETIME; SELECT @today = CONVERT(DATE, GETDATE()), @today_at_1615 = DATEADD(MINUTE, 16.25*60, @today); SELECT Posted_Date, Total_Payment FROM dbo.Table1 WHERE Posted_Date between DATEADD(DAY, -1, @today_at_1615) AND @today_at_1615 ...
Sql query to select data from the day before at 4:15:01 pm to today at 4:15:00 pm
[ "", "sql", "sql-server", "sql-server-2005", "ssis", "" ]
Here's my situation (or **see TLDR at bottom**): I'm trying to make a system that will search for user entered words through several documents and return the documents that contain those words. The user(s) will be searching through thousands of documents, each of which will be 10 - 100+ pages long, and stored on a webs...
Rather than building your own search engine using SQL Server, have you considered using a C# .net implementation of the lucene search api's? Have a look at <https://github.com/apache/lucene.net>
Good question. I would piggy back on the existing solution of SQL Server (full text indexing). They have integrated a nice indexing engine which optimises considerably better than your own code probably could do (or the developers at Microsoft are lazy or they just got a dime to build it :-) Please see [SQL server](ht...
SQL Most effective way to store every word in a document separately
[ "", "sql", "sql-server", "database", "search", "document", "" ]
I have 2 columns in MS SQL one is Serial no. and other is values. I need the thrird column which gives me the sum of the value in that row and the next 2. Ex ``` SNo values 1 2 2 3 3 1 4 2 5 6 7 9 8 3 9 2 ``` So I need third column which has sum of 2+3+1, 3+1+2 and So on, so the 8th and 9th row will not have any val...
Here is the [**SQL Fiddle**](http://sqlfiddle.com/#!3/87dcd/82/0) that demonstrates the following query: ``` WITH TempS as ( SELECT s.SNo, s.value, ROW_NUMBER() OVER (ORDER BY s.SNo) AS RowNumber FROM MyTable AS s ) SELECT m.SNo, m.value, ( SELECT SUM(s.value) FROM TempS AS s WHERE RowNumber >= m.RowNum...
In case the `sno` field is not sequential, you can use `row_number()` with aggregation: ``` with ss as ( select sno, values, row_number() over (order by sno) as seqnum from s ) select s1.sno, s1.values, (case when count(s2.values) = 3 then sum(s2.values) end) as avg3 from ss s1 left outer join ...
Moving Average / Rolling Average
[ "", "sql", "sql-server", "sql-server-2008", "statistics", "subquery", "" ]
I have one table t1 with clientdivisionid, planid, memberid and values are 154 | 722 | 27510, 154 | 722 | 22222, 154 | 725 | 27510 I need to pull only members where planID = 722 for members who are not part of plan 725. So result should be 154| 722 | 22222 here is my SQL ``` Select memberid,planid from t1 ...
``` SELECT t1.clientdivisionid, t1.planid, t1.memberid FROM t1 LEFT JOIN ( SELECT memberid FROM t1 WHERE planid = 725 ) AS subExclude ON t1.memberid = subExclude.memberid WHERE t1.planid = 722 AND subExclude.memberid Is Null; ``` If you want to alter ...
Try doing: ``` SELECT memberid,planid FROM tab1 t1 WHERE planid = 722 AND NOT EXISTS ( SELECT 1 FROM tab1 t2 WHERE t1.memberid = t2.memberid AND t2.planid = 725 ) ``` `sqlfiddle demo` EDIT: If you only want to select the ones that have planid = 722, and no other planid you can put planid <> 722 in...
How to exclude results from my resultset based on a different row?
[ "", "sql", "ms-access", "" ]
I'm trying to restore my dump file, but it caused an error: ``` psql:psit.sql:27485: invalid command \N ``` Is there a solution? I searched, but I didn't get a clear answer.
Postgres uses `\N` as substitute symbol for NULL value. But all psql commands start with a backslash `\` symbol. You can get these messages, when a copy statement fails, but the loading of dump continues. This message is a false alarm. You have to search all lines prior to this error if you want to see the real reason ...
I received the same error message when trying to restore from a binary pg\_dump. I simply used [`pg_restore`](https://www.postgresql.org/docs/current/app-pgrestore.html) to restore my dump and completely avoid the `\N` errors, e.g. `pg_restore -c -F t -f your.backup.tar` Explanation of switches: ``` -f, --file=FILEN...
psql invalid command \N while restore sql
[ "", "sql", "postgresql", "dump", "" ]
I'm inserting a bunch of rows into another table, and watch to generate an unique batch id for every X rows inserted (in this case X will be 100 or so). So if I'm inserting 1000 rows, the first 100 rows will have batch\_id = 1, the next 100 will have batch\_id = 2, etc. ``` INSERT INTO BatchTable(batch_id, col1) SELE...
We can take advantage of integer division here for a simple way to round up to the next 100: ``` ;WITH x AS ( SELECT col1, rn = ROW_NUMBER() OVER (ORDER BY col1) FROM dbo.OtherTable ) --INSERT dbo.BatchTable(batch_id, col1) SELECT batch_id = (99+rn)/100, col1 FROM x; ``` When you're happy with the output, uncommen...
Try this using `row_number()` function: ``` declare @batchGroup int = 100 Insert into BatchTable(batch_id, col1) Select ((row_number() over (order by col1)-1)/@batchGroup)+ 1 As batch_id, col1 From OtherTable ```
SQL server: Inserting a bunch of rows into a table, generating a "batch id" for every 100?
[ "", "sql", "sql-server", "" ]
I'm doing some work in MS Access and I need to append a prefix to a bunch of fields, I know SQL but it doesn't quite seem to work the same in Access Basically I need this translated to a command that will work in access: ``` UPDATE myTable SET [My Column] = CONCAT ("Prefix ", [My Column]) WHERE [Different Column]='s...
``` UPDATE myTable SET [My Column] = "Prefix " & [My Column] WHERE [Different Column]='someValue'; ``` As far as I am aware there is no CONCAT
There are two concatenation operators available in Access: `+`; and `&`. They differ in how they deal with Null. `"foo" + Null` returns Null `"foo" & Null` returns `"foo"` So if you want to update Null `[My Column]` fields to contain `"Prefix "` afterwards, use ... ``` SET [My Column] = "Prefix " & [My Column] ``` ...
CONCAT equivalent in MS Access
[ "", "sql", "ms-access", "ms-access-2010", "" ]
I'm looking for how I can combine between "IN" and "LIKE" in a request like this one ``` SELECT * FROM Users WHERE Location LIKE IN (SELECT name FROM CITIES) ``` (I want to retrieve users who have a city mentioned in the table "cities" ) i get an error in my SQL syntax (i'm using Mysql). thank you.
``` SELECT u.* FROM Users u INNER JOIN Cities c ON u.Location like concat('%',c.Name,'%') ```
Not sure on MySQL syntax but try ``` SELECT * FROM Users INNER JOIN Cities ON Users.Location = Cities.Name ```
combine between IN and Like in a request Mysql
[ "", "mysql", "sql", "request", "" ]
I have a language table and want retrieve specific records for a selected language. However, when there is no translation present I want to get the translation of another language. **TRANSLATIONS** ``` TAG LANG TEXT "prog1" | 1 | "Programmeur" "prog1" | 2 | "Programmer" "prog1" | 3 | "Programista" "prog2" | ...
I canabalized the solutions of @fossilcoder and @Smandoli and merged it in one solution: ``` SELECT IIf ( NZ(TRANSLATION.Text,"") = "", DEFAULT.TEXT, TRANSLATION.TEXT) FROM TRANSLATIONS AS TRANSLATION, TRANSLATIONS AS DEFAULT, PROGDATA WHERE TRANSLATION.Tag="prog_" & PROGDATA.Id AND DEFAULT.Tag="p...
A `SWITCH` or `CASE` statement may work well. But try this: ``` SELECT IIf(TEXT="", (SELECT TEXT AS TEXT_OTHER FROM TRANSLATIONS, PROGDATA WHERE TRANSLATIONS.TAG="prog" & PROGDATA.ID AND TRANSLATIONS.LANG=2),TEXT) AS TEXT_FINAL ``` I am using `TEXTOTHER` and `TEXTFINAL` to reduce ambiguity in your fi...
Replace empty/null string with result from another record
[ "", "sql", "ms-access-2003", "" ]
I am having troubles combining multiple queries into one output. I am a beginner at SQL and was wondering if anyone can provide me with some feedback on how to get this done. Here is my code: ``` SELECT [status], [queryno_i] as 'Query ID', [assigned_to_group] as 'Assigned To Group', [issued_date] as 'Issuing Date', C...
If you want all in one row just put all together ``` SELECT [status], [queryno_i] as 'Query ID', [assigned_to_group] as 'Assigned To Group', [issued_date] as 'Issuing Date', CASE WHEN [status] = 3 THEN [mutation] ELSE NULL END AS 'Closing Date', CASE WHEN [status] = 3 THEN 'CLOSED' ELS...
You can use a UNION clause <http://www.w3schools.com/sql/sql_union.asp> ``` SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 ``` However, from looking at your 3 statements, all 3 selects are coming from the same table, so you may be able to just combine and use CASE statements to get your results without using a ...
SQL how to combine multiple SQL Queries into one output
[ "", "sql", "" ]
I have the following value in a nvarchar 0011223344 This value will always be an even length. I need to convert this value to 00\11\22\33\44 Using MSSQL.
This works in SQL Server.. ``` DECLARE @test nvarchar(20) = '0011223344' DECLARE @i int = 3 WHILE @i < LEN(@test) BEGIN SELECT @test = STUFF(@test, @i, 0, '\') SET @i = @i + 3 END SELECT @test ``` You could probably implement a more elegant solution using a numbers table.
``` create function changeFormat( @BeginWord varchar(10)) returns varchar(20) as begin declare @finalWord varchar(20) SET @finalWord=''; SET @finalWord= @finalWord + substring(@BeginWord,1,2)+ '/'; SET @finalWord= @finalWord + substring(@BeginWord,3,2)+ '/'; SET @finalWord= @finalWord + substr...
In SQL, how do I insert a character every 2 spaces in a nvarchar?
[ "", "sql", "sql-server", "" ]
I have three tables (products, product\_info and specials) ``` products(id, created_date) product_info(product_id, language, title, .....) specials(product_id, from_date, to_date) ``` product\_id is foreign key which references id on products When searching products I want to order this search by products that are s...
If not every product is in specials table, you should do a LEFT JOIN with specials instead and put the validations of the dates of specials in the ON CLAUSE. Then you order by products.id but put the specials first, by validating it with a CASE WHEN: ``` SELECT products.*, product_info.* FROM products INNER JOIN produ...
Try this ``` SELECT products.*, product_info.* FROM products INNER JOIN product_info ON product_info.product_id = products.id INNER JOIN specials ON specials.product_d = products.id WHERE product_info.language = 'en' AND product_info.title like ? AND specials.from_date < NOW() AND specials.to_date > NOW() ORDER BY spe...
MySql query to order by existence in another table
[ "", "mysql", "sql", "" ]
I have multiple `IF` statements that are independent of each other in my stored procedure. But for some reason they are being nested inside each other as if they are part of one big if statement ``` ELSE IF(SOMETHNGZ) BEGIN IF(SOMETHINGY) BEGIN..END ELSE IF (SOMETHINGY) BEGIN..END ELSE BEGIN..END --T...
IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored. ``` IF(@Var1 Condition1) BEGIN /*Your Code Goes here*/ END ELSE IF(@Var1 Condition2) BEGIN ...
To avoid syntax errors, be sure to always put `BEGIN` and `END` after an `IF` clause, eg: ``` IF (@A!= @SA) BEGIN --do stuff END IF (@C!= @SC) BEGIN --do stuff END ``` ... and so on. This should work as expected. Imagine `BEGIN` and `END` keyword as the opening and closing bracket, respectively.
Multiple separate IF conditions in SQL Server
[ "", "sql", "sql-server", "if-statement", "" ]
I have a table ``` url lastcached lastupdate ----- ---------- ---------- url1 0 1 url2 0 1 url3 1 1 ``` I want to make a query that returns a row for every record in which lastcached and lastupdate is not same. So result should be ``` url lastcached lastupdate ----- ---------...
``` select url, lastcached, lastupdate from your_table where lastcached <> lastupdate ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!7/d48f1/1)
``` SELECT * FROM your_table WHERE lastcached <> lastupdate ``` produces the right result
SQLite Select rows with not same values in two columns
[ "", "sql", "sqlite", "" ]
My situation: I have a table in a SQL Server 2012 database ``` id | created | sum ------------------------------ 1 | 2013-12-10 12:00:00 | 200 2 | 2013-12-10 13:00:00 | 300 3 | 2013-12-10 14:00:00 | 400 4 | 2013-12-09 08:00:00 | 100 5 | 2013-12-09 15:00:00 | 600 6 | 2013-12-10 12:00:00 | 50 ......
You could try something like this: * have a CTE (Common Table Expression) extract the 20 date-only values from your table * join your base table against the CTE output to get all the rows from the base table, for those selected dates only Try something like this: ``` -- replace this with your own, base table - this ...
Try this: ``` SELECT rowNo, createdDate, sumCol FROM ( SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY CONVERT(DATE, a.created)) rowNo, CONVERT(DATE, a.created) createdDate, '' sumCol FROM tableA a GROUP BY CONVERT(DATE, a.created) UNION SELECT B.id AS rowNo, b.created AS createdDate, b.sum AS s...
T-SQL: select top 20 root nodes with children
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Suppose I have a table MATCHES(OPPONENT, DATE, GOALS\_FOR, GOALS\_AGAINST) If I want an SQL query which returns the most recent match where GOALS\_FOR was greater than 2, then I can use ``` SELECT * FROM MATCHES WHERE GOALS_FOR > 2 AND DATE = ( SELECT MAX(DATE) FROM MATCHES WHERE GOALS_FOR > 2) ``` How can I do thi...
Just select the top 1 order by date desc, example in tsql ``` SELECT top 1 * FROM MATCHES WHERE GOALS_FOR > 2 ORDER BY DATE Desc ``` (use rownum for oracle, limit for mysql, fetch first for db2, etc)
You can simple join it against a subquery that gets the latest `DATE` for every `GOALS_FOR`. ``` SELECT a.* FROM `matches` a INNER JOIN ( SELECT GOALS_FOR, MAX(DATE) Date FROM `matches` WHERE GOALS_FOR > 2 GROUP BY GOALS_FOR ) b ON a....
SQL MAX( ) function
[ "", "sql", "" ]
I am using LLBLGEN where there is a method to execute a query as a `scalar query`. Googling gives me a definition for `scalar sub-query`, are they the same ?
A scalar query is a query that returns one row consisting of one column.
For what it's worth: > Scalar subqueries or scalar queries are queries that return exactly > one column and one or zero records. [Source](https://books.google.co.uk/books?id=jfKoCwAAQBAJ&pg=PA155&lpg=PA155&dq=Scalar+subqueries+or+scalar+queries+are+queries+that+return+exactly+one+column+and+one+or+zero+records.+They&...
What is a "Scalar" Query?
[ "", "sql", "database", "executescalar", "llblgen", "" ]
What's the easiest way to select a single record/value from the n-th group? The group is determined by a material and it's price(prices can change). I need to find the first date of the last and the last date of the next to last material-price-groups. So i want to know when exactly a price changed. I've tried followin...
You will need to use the windowed function ROWNUMBER in a subquery,... something like this will get you there: ``` ROW_NUMBER() OVER(PARTITION BY Price ORDER BY Claim_Submitted_Date DESC) AS Row ``` Here's the update based on your fiddle: ``` DECLARE @material VARCHAR(20) SET @material = '1271-4303' SELECT * FROM...
Following your last comments, only solution I came with is counting the different price groups according to their `Claim_Submitted_Date`, and then include the obtained group indexes as part as the grouping criteria. Not sure it will be highly efficient. Hope it will help though. ``` declare @materialId nvarchar(max), ...
Get first/last row of n-th consecutive group
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
what;s wrong with my query ... i get the error message #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '. mail\_time FROM ibc\_messages m , ibc\_msg\_queue q AND m . id = q . msgid AND q' at line 1 ``` SELECT distinct q.msgi...
remove the comma after your third column ``` SELECT distinct q.msgid , q.mail_time,m.status FROM ```
You have an extra comma before the "FROM" clause
what;s wrong with my sql query?
[ "", "mysql", "sql", "" ]
I have a DB with this layout... ``` contracts --------- id name description # Etc... locations --------- id contract_id # FK to contracts.id name order_position # Etc... ``` I need to find contracts by the `name` of their current location (and by other `contracts` columns at the same time). The current location is...
I worked on it some more and found that this solves the problem... ``` SELECT c.* FROM contracts c, locations l WHERE c.id = l.contract_id AND c.name LIKE '%bay%' AND l.name LIKE '%admin%' AND l.order_position = ( SELECT MAX(order_position) FROM `locations` WHERE `contract_id` = c.id ); ```
Maybe ``` SELECT c.name FROM contracts c JOIN locations l ON c.id=l.contract_id AND c.name IN(SELECT name FROM locations WHERE locations.order_position IN(SELECT MAX(order_position) FROM locations GROUP BY locations.name)) ```
How can I find records using only certain rows in a joined table?
[ "", "mysql", "sql", "" ]
Given Table: **student** ``` | course | Name| --------------- | science | A | | math | B | | english | A | | physics | A | | chem | A | | bio | B | | geology | B | | history | C | ``` I will order this table alphabetically. Tmp table: **ordered\_student** ``` | course | Name| ---------...
This should do it: ``` WITH s AS ( SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY course) rank, * FROM student ) SELECT course, name FROM s WHERE RANK <= 2 ORDER BY course ``` Output: ``` course name ------- ---- bio B chem A english A geology B history C ``` See it working [here...
Try this: ``` ; with temp as ( select DENSE_RANK() OVER (PARTITION BY Name ORDER BY Course) AS Rank, Name, course from student ) SELECT Course, Name FROM temp WHERE Rank<=2 order by Course ``` Result: ``` Course Name bio B chem A english A geology B history C ```
SQL help, limiting number of rows
[ "", "sql", "sql-server", "aggregate-functions", "" ]
I need to write a query in my project where I want sum of a column on every date range of another table (for ORACLE database). TABLE1 – It has number of pax booked on every date: ``` DT NO_OF_PAX -------- --------------- 01-JAN-14 10 02-JAN-14 5 03-JAN-14 8 05-JAN-14 5 : : 28-DEC-14 20 30-D...
This is the correct SQL: ``` SELECT T2.ST_DT, T2.END_DT, ( SELECT SUM(T1.NO_OF_PAX) FROM TABLE1 T1 WHERE T1.DT BETWEEN T2.ST_DT AND T2.END_DT ) NO_OF_PAX FROM TABLE2 T2 ORDER BY T2.ST_DT ASC ``` See on SQLFiddle <http://sqlfiddle.com/#!4/2e9e9/1/0>
Try it this way ``` SELECT st_dt, end_dt, COALESCE(SUM(no_of_pax), 0) total FROM Table2 t2 LEFT JOIN Table1 t1 ON t1.dt BETWEEN t2.st_dt AND end_dt GROUP BY st_dt, end_dt ``` Sample output: ``` | ST_DT | END_DT | TOTAL | |-----------|------------|-------| | 01-JAN-14 | 31-JAN-14 | 28 | | 12-JAN-14...
Oracle Query to sum a column by every date range in another table
[ "", "sql", "oracle", "" ]
I am using following SQL command with `sp_rename` to rename a column. ``` USE MYSYS; GO EXEC sp_rename 'MYSYS.SYSDetails.AssetName', 'AssetTypeName', 'COLUMN'; GO ``` But it is causing an error: > Msg 15248, Level 11, State 1, Procedure sp\_rename, Line 238 > Either the parameter @objname is ambiguous or the claim...
Try this: ``` USE MYSYS; GO EXEC sp_rename 'SYSDetails.AssetName', 'AssetTypeName', 'COLUMN'; GO ``` sp\_rename (Transact-SQL) ([msdn](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql)): > [ @objname = ] 'object\_name' > > Is the current qualified or nonquali...
Double-check that your table `SYSDetails` exists. If the target table doesn't exist you get this error.
Whats wrong with sp_rename with column?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have .csv which content is like this ``` "aa839","340000","2350444" ``` When I do the `BULK INSERT`, I use `FIELDTERMINATOR = ','` Thus, the data has quote `"`. I want to remove the quote `"`, so that my database has only `aa839, 340000, 2350444`.
Dont bother about replacing while doing bulk insert , you can replace later after bulk insert . So do bulk insert as it is originally and later fire update query as below. This is the fastest way too ``` update table set field= REPLACE(field, 'search', 'replace'); ``` where search is "" and replace is blank
while reading the file replace all (") with blank (), then replace (,) with space ( )
Bulk insert .csv - fieldterminator
[ "", "sql", "sqlbulkcopy", "" ]
I have tables like, **Table A** ``` field1 | field2 | field3 | field4 | field5 ``` **Table B** ``` id | field_names -------------------- 1 field2 2 field3 ``` I have to delete field2 and field3 from `Table A` ( means field names in `Table B` ). Is there any way to drop field names which present in...
Not sure why you need this. anyway MySQL has no such feature. but if you want really do that, execute following query and execute each rows. ``` SELECT CONCAT('ALTER TABLE TableA DROP ', field_names, ';') FROM TableB; ``` for examples with PHP, (all error check is omitted) ``` $query = "SELECT CONCAT('ALTER TABLE Ta...
This would help: ``` SELECT @s := CONCAT('ALTER TABLE tableA DROP COLUMN ', GROUP_CONCAT(field_names SEPARATOR ', DROP COLUMN '), ';') FROM tableB; PREPARE stmt FROM @s; EXECUTE @s; ```
DROP columns of a table,according to the values in another table
[ "", "mysql", "sql", "alter-table", "" ]
Is there any app for mac to split sql files or even script? I have a large files which i have to upload it to hosting that doesn't support files over 8 MB. \*I don't have SSH access
You can use this : <http://www.ozerov.de/bigdump/> Or Use this command to split the sql file ``` split -l 5000 ./path/to/mysqldump.sql ./mysqldump/dbpart- ``` The split command takes a file and breaks it into multiple files. The -l 5000 part tells it to split the file every five thousand lines. The next bit is the ...
This tool should do the trick: [MySQLDumpSplitter](https://github.com/rodoic/mysqldumpsplitter) It's free and open source. Unlike the accepted answer to this question, this app will always keep extended inserts intact so the precise form of your query doesn't matter; the resulting files will always have valid SQL syn...
How to split sql in MAC OSX?
[ "", "sql", "macos", "phpmyadmin", "splitter", "" ]
I'm relatively new to SQL, and am trying to find the best way to attack this problem. I am trying to take data from 2 tables and start merging them together to perform analysis on it, but I don't know the best way to go about this without looping or many nested subqueries. What I've done so far: I have 2 tables. Tabl...
Here's one way to do this: ``` SELECT alias1.user_id, MAX(alias1.user_name) As user_name, SUM(Table2.price) As UsersTotalPrice, MAX(Table2.price) As UsersHighestPrice FROM Table1 As alias1 LEFT JOIN Table2 ON alias1.user_id = Table2.user_id WHERE cou...
This should work ``` select table1.*, t2.total_price, t2.max_price, t2.order_count ``` from table1 join (selectt user\_id, sum(table2.price) as total\_price, max(table2.price) as max\_price, count(order\_id) as order\_count from table2 as t2 group by t2.user\_id) on table1.user\_id = t2.user\_id where t1.country = 'u...
Best solution for SQL without looping
[ "", "sql", "" ]
I've got an Oracle table that holds a set of ranges (RangeA and RangeB). These columns are varchar as they can hold both numeric and alphanumeric values, like the following example: ``` ID|RangeA|RangeB 1 | 10 | 20 2 | 21 | 30 3 | AB50 | AB70 4 | AB80 | AB90 ``` I need to to do a query that returns only the r...
You can test each column with a regular expression to determine if it is a valid number: ``` SELECT COUNT(1) FROM table_of_ranges WHERE CASE WHEN REGEXP_LIKE( RangeA, '^-?\d+(\.\d*)?$' ) THEN TO_NUMBER( RangeA ) ELSE NULL END < 10 AND REGEXP_LIKE( RangeB, '^-?\d+(\.\d*)?$' ); ``...
Try this query: ``` SELECT COUNT(*) FROM table R WHERE translate(R.RangeA, 'x0123456789', 'x') = 'x' and translate(R.RangeB, 'x0123456789', 'x') = 'x' ``` First, you don't need the subquery for this purpose. Second, using `to_number()` or `upper()`/`lower()` are prone to other problems. The function `tr...
ORACLE - Select Count on a Subquery
[ "", "sql", "oracle", "count", "subquery", "" ]
I have a pl/sql loop which looks like below: ``` IF A IN (1,2,3,4,5) OR B IN (1,2,3,4,5) OR C IN (1,2,3,4,5) THEN --Do Something-- ELSIF A IN (6,7) AND B IN (6,7) AND C IN (6,7) THEN --Do Something Else-- ELSE --Do Nothing-- END IF; ``` Is there a better way to write the above loop? The above example is j...
Create a [collection](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/collections.htm) (nested table) type to hold the values and the test conditions then you can use [`MULTISET'](http://docs.oracle.com/cd/B19306_01/server.102/b14200/operators006.htm) operations to compare them: * `(a MULTISET INTERSECT DISTINCT...
Try `CASE` statement. It will be more readable than `IF` statement. [Check here for more](http://docs.oracle.com/cd/B10500_01/appdev.920/a96624/04_struc.htm)
PL/Sql IF loop with multiple OR - IN's
[ "", "sql", "oracle", "plsql", "" ]
I'm attempting to use an alpha between in SQL; however, I want it to be based on the beginnings of the words only. I am using T-SQL on Microsoft SQL Server 2005. My current SQL is: ``` SELECT * FROM table WHERE LEFT(word,1) BETWEEN 'a' AND 't ``` However, this only works for first letter. I'd like to expand this to ...
You need to use the [STUFF](http://technet.microsoft.com/en-us/library/ms188043.aspx) function to achieve what you are looking for explicitly. If you follow the link says it deletes a specified number of characters at the end of the string and replaces them with another string. Combine the with the LEN function and we ...
This should work: ``` SELECT * FROM table WHERE LEFT(word,3) BETWEEN 'a' AND 'ter' ``` There's no reason why BETWEEN shouldn't be able to compare your three-letter data string to the one-letter 'a'. Any 'axx' will be "greater than" just 'a' by itself, and so will be included.
SQL Between Begins With
[ "", "sql", "t-sql", "sql-server-2005", "between", "" ]
I have 2 tables, which are joined by a left join. Table1: * Id (int) * Name (string) Table2: * Id (int) * Table1Id (int) * Allowed (bit) Based on the name saved in table one, I can get all records in table 2. When one or more records in table 2 have the value of allowed = 0 the result of my query should return 0. ...
``` SELECT Table1.Name, min(case when Table2.Allowed = 0 then 0 else 1 end) FROM Table1 LEFT JOIN Table2 on Table1.Id = Table2.Table1Id GROUP BY Table1.Name ``` ## [SQLFiddle demo](http://sqlfiddle.com/#!3/22197/1)
While the question might not have been clear, I have found a second solution to my problem: ``` SELECT [Name] AS [Name], MIN(Allowed) FROM( SELECT [Table1].[Name] AS [Name], CAST(ISNULL([Table2].[Allowed], 1) as int) AS [allowed] FROM [Table1] AS [T1] LEFT JOIN [Table2] AS [T2] on [T1].[Id] = [T2].[Table1Id...
selecting a distinct value based on 1 value
[ "", "sql", "sql-server-2012", "" ]
I'm trying to search a SQL database using this SQL query: > SELECT \* FROM Reservations WHERE fDate=06/12/13 Here is an image of my SQL Reservations table with dummy data: ![Data](https://i.stack.imgur.com/kE84C.png) What am I doing wrong here? Thanks, C.
Try changing date format from 'dd/mm/yyyy' to 'yyyy/mm/dd'. Like this: SELECT \* FROM Reservations WHERE fDate='2013/11/08' See sample [SQL Fiddle I created](http://sqlfiddle.com/#!2/0798a26/1)
You'll need to put the date inside '' ``` SELECT * FROM Reservations WHERE fDate='06/12/13' ``` But, if what you're showing us a view, then you'll need to use the standard format for dates: ``` SELECT * FROM Reservations WHERE fDate='2013-12-06' ```
Searching a SQL database by 'date'
[ "", "sql", "vb.net", "date", "" ]
I have multiple queries : ``` 1) select Year , Month, Sum(Stores) from ABC ; 2) select Year, Month , Sum(SalesStores) from DEF ; 3) slect Year, Month, Sum(Products) from FGH; ``` I want a result like : ``` Year, Month , Sum(Stores), Sum(SalesStores), Sum(Products) ``` I tried Full Outer Join with a qu...
Here is another way to get this information. This example has a short setup to demonstrate this solution in action. ``` CREATE TABLE #ABC([Year] INT, [Month] INT, Stores INT); CREATE TABLE #DEF([Year] INT, [Month] INT, SalesStores INT); CREATE TABLE #GHI([Year] INT, [Month] INT, Products INT); INSERT #ABC VALUES (201...
You could union the multiple sets like this: ``` SELECT Year, Month, 'Stores' AS Src, Stores AS Value FROM ABC UNION ALL SELECT Year, Month, 'SalesStores', SalesStores FROM DEF UNION ALL SELECT Year, Month, 'Products', Products FROM FGH ``` then [PIVOT](http://msdn.microsoft.com/en-us/library/ms1774...
Combine multiple datasets into a single query
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I'm working with a Pro\*C query, but this question should be general SQL. My research has been a dead end, but I think I'm missing something. Suppose my server has an array of students' names, `{"Alice","Charlie","Bob"}`. I query the `Student_Ids` table for the students' ID numbers: ``` SELECT id_no FROM student_...
The `ORDER BY` expression you've given for your sample data is equivalent to `ORDER BY student_name`. Is that what you intended? If you want a custom ordering that is not alphabetical, I think you might have meant something like this: ``` ORDER BY CASE WHEN student_name = 'Alice' THEN 0 WHEN student_na...
Can you do this? ``` order by student_name ``` To do a custom sort, you only need one `case`: ``` ORDER BY (CASE WHEN student_name = 'Alice' THEN 1 WHEN student_name = 'Bob' THEN 2 WHEN student_name = 'Charlie' THEN 3 ELSE 4 END) ```
Custom Ordering of SELECT Results
[ "", "sql", "oracle", "" ]
I have a table with columns CompanyID, EmployeeCode. EmployeeCode is unique and CompanyID can be repeated. So we can keep a list of employees in Google, Apple etc. I want a way to ensure that the same employee cannot be added if he/she is already in the database. What would be a good way to do this ? I'd prefer not to...
Create a UNIQUE constraint on the column where you want to prevent duplicates: ``` CREATE UNIQUE INDEX [IX_YourTableName_EmployeeCode] ON [YourTableName] (EmployeeCode) ```
Try this.. ``` Create table UniqueTable ( CompanyID int, EmployeeCode int ) --Insert dummy data INSERT INTO UniqueTable(EmployeeCode ,CompanyID ) Values(1,200) --When are Going to insert duplicate Ecmployeecode '1' then it will not insert data into table INSERT INTO UniqueTable(EmployeeCode ,CompanyID ) Select 1,...
Prevent insertion of duplicates
[ "", "sql", "sql-server", "" ]
i have the following tables: ``` projects: id, name, language 1 |test | php 2 |test | java 3 |hello| php attrs: id, name, value, tb1_id 1 | status | finish | 1 2 | reference | 2 | 1 ``` I need a query to select all projects, which have a attribute "ref...
You can either: * group the joined tables, filtering such groups with suitable aggregate functions within the `HAVING` clause: ``` SELECT projects.id, projects.name FROM projects JOIN attrs ON attrs.tb1_id = projects.id GROUP BY projects.id HAVING SUM(attrs.name='reference') AND SUM(att...
``` SELECT P.id, P.name FROM projects P inner join attrs A on P.id = a.tb1_id WHERE (A.name = 'status' AND value = 'finish') UNION SELECT P.id, P.name FROM attrs A INNER JOIN projects P ON A.value = P.id WHERE A.name='reference' ``` See the result in [this fiddle](http://sqlfiddle.com/#!2/68a94/9)
SQL Query to select multiple rows
[ "", "mysql", "sql", "join", "" ]
I have a basic customer table. The columns are: ``` FirstName LastName Organization PhoneNumber City State Zip ID ``` `ID` is an autoincremented value. I want to insert a new record into the table so I issue this command: ``` INSERT INTO CustomerTable (FirstName, LastName, Organization, PhoneNumber, C...
Put the string values in quotes. Outside quotes those strings will be treated as column or variable names. ``` VALUES (John, Doe, None, 5555555555, Nowhere, NY, 12345) ``` Should be ``` VALUES ('John', 'Doe', 'None', 5555555555, 'Nowhere', 'NY', 12345) ```
John is a string. You need to put in ''.
mysql 1054, unknown column, but I'm not specifying a column
[ "", "mysql", "sql", "insert-statement", "" ]
I am working with MySql 5.1 and am building my first many-to-many database. I understand the concepts, I have 3 tables: * `Albums`, with a unique ID * `Genres`, with a unique ID * `album_genres` with columns for each of the ID's from Albums and Genres. The issue I am having is that, of course, 1 album can have multip...
If I got the question you need output like ``` AlbumName | Genre1,Genre2......... ``` FOr this you need to use **GroupBy** ``` SELECT A.album_name as AlbumName, GROUP_CONCAT(G.genre_name) as GenreName, count(A.ID) as GenreCount FROM Album A JOIN album_genres AG ON (A.ID = AG.album_ID) JOIN Genre G ON (G.I...
Join on the two tables. ``` SELECT cols FROM Albums JOIN album_genres USING (albumID) JOIN Genres USING (genreID) WHERE albumName LIKE :search ```
How to do a many to many subquery in MySql
[ "", "mysql", "sql", "" ]
I am trying to optimize a query and I believe I can do it with joins as opposed to subqueries but I am not sure how to. Bellow is my query: ``` SELECT * FROM accounts WHERE LOWER(firstname) = LOWER('Sam') AND id IN (SELECT account_id FROM addresses WHERE LOWER(name...
Try this: ``` SELECT acc.* FROM accounts acc JOIN addresses addr ON acc.id = addr.account_id JOIN alternate_ids ids ON acc.id = ids.account_id WHERE LOWER(acc.firstname) = LOWER('Sam') AND LOWER(addr.name) = LOWER('Street1') AND ids.alternate_id_glbl = '5'; ``` However, it is not guaranteed that this version will...
Have you checked the execution plan to see if it is already using a join? The query optimiser will do it if possible. You might place indexes on the account table LOWER(firstname) and the addresses table LOWER(name).
Changing a query from subqueries to joins
[ "", "sql", "database", "postgresql", "" ]
I have a table with an event date column. I want to return records in an order in which first the most recent upcoming records show up and when all the upcoming records are over, the past records should show up with the latest passed first. For that, I was planning to first get records with `event date > GETDATE()` so...
``` SELECT * FROM ( SELECT EventName, EventDate, 1 AS OrderPri, ROW_NUMBER() OVER(ORDER BY EventDate) AS Row FROM EventTable WHERE EventDate > GETDATE() UNION ALL SELECT EventName, EventDate, 2 AS OrderPri, ROW_NUMBER() OVER(ORDER BY EventDate DESC) AS Row FROM EventTable WHERE EventDate <= ...
You need to specify an `ORDER BY` that applies to *all* of the results, and if you want the results from the first `SELECT` to appear first, you have to *specify* that too: ``` SELECT EventName,EventDate FROM ( SELECT EventName, EventDate, 1 as ResultSet FROM EventTable WHERE EventDate>GETDATE() UNION ALL ...
Use ORDER BY with UNION ALL
[ "", "sql", "sql-server", "t-sql", "union", "union-all", "" ]
How do I SELECT multiple ranges in MySQL taking in consideration the following scenario: let say I want to get back from my product table products where price 0 - 300 and price 600-1000 price 1200-1600 I was trying the following ``` SELECT * FROM products WHERE price > 0 AND price <= 300 AND price >= 600 AN...
If a number is between `0` and `300` it can't **also** be between `600` and `1000`. Are you looking for `OR`? Perhaps with [`BETWEEN`](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between) just to make things easier? ``` SELECT * FROM products WHERE price BETWEEN 0 AND 300 OR p...
``` SELECT * FROM products WHERE (price > 0 AND price <= 300 ) OR (price > 600 AND price <= 1000) OR (price > 1200 AND price <= 1600 ) ``` you can also use between ``` price BETWEEN 0 AND 300 or price between ... ``` consider that between `price BETWEEN 0 AND 300` will include 0 it will be parsed into `price >= 0 A...
select more ranges in mysql
[ "", "mysql", "sql", "range", "" ]
I'm having a slight issue. I have a PostgreSQL table with such format ``` time (datetime) | players (int) | servers (int) --------------------------------------------------- 2013-12-06 13:40:01 | 80 | 20 2013-12-06 13:41:13 | 78 | 21 etc. ``` I would like to group them by 5 minute periods an...
``` SELECT grid.t5 , min(t."time") AS min_time -- , array_agg(extract(min FROM t."time")) AS 'players_on' -- optional , avg(t.players) AS avg_players , avg(t.servers) AS avg_servers FROM ( SELECT generate_series(min("time") , max("time") , interval '...
Try this, it should group minutes 0-4, 5-9, 10-14 and so on... ``` SELECT MIN(time), AVG(Players), AVG(Servers) FROM MyTable t GROUP BY date_trunc('hour', time), FLOOR(datepart('minute', time)/12) ``` EDIT: Changed the grouping to hour first and then to the `Floor` of minutes. I Think this should work.
Selecting an average of records grouped by 5 minute periods
[ "", "sql", "postgresql", "timestamp", "aggregate-functions", "generate-series", "" ]
I am having issues with a report after switching the database from SQL Server 7 to SQL Server 2008. The report ran fine on our old server, it was Server 2000, and again was running SQL Server 7. We had to update the DSN driver to point to the new database. Now when someone runs our report, they receive this error: ![e...
After weeks and weeks of working on this issue, I found a work around. So far this has been the only way to solve the issue. I had to open the crystal report view outside of Visual Studio. Then I had to open the report that was casing the issue. After that I ran the app and opened the report in the app. The report woul...
Crystal 8 rpt files keep the data connection information which some times donot get cleared even when you change the details in run time Following is suggested: Change your rpt file to point to your new database and You need to refresh and preview the report assuring it is fetching data from new database. Hope it hel...
Crystal Reports 8 Issues From SQL 7 To SQL 2008 VB6
[ "", "sql", "sql-server", "sql-server-2008", "vb6", "crystal-reports", "" ]
I have two tables ``` Child_id (this is temporary table) -------- 1001 ---------- 1002 ---------- 1003 ---------- 1004 ---------- 1006 ``` - ``` Child_id Amount (this table name is user_details) ------------------- 1001 100 -------------------- 1002 250 -------------------- 1003...
if you have very big table then this variant is better ``` SELECT SUM(u.amount) FROM user_details u where exists (select * from tempTable t where t.child_id = u.child_id) ```
You can do: ``` SELECT SUM(u.amount) FROM tempTable t INNER JOIN user_details u ON t.child_id = u.child_id ``` This will result in the SUM of the amounts for the records that have child\_id in both tables
Adding sums from one table to a second table
[ "", "mysql", "sql", "sql-server", "" ]
I would like to make a single round trip to an MSSQL database to retrieve multiple tables. Each table relies in one way or another on the same somewhat expensive lookup, which will grab a bunch of IDs and handle pagination and very basic filtering. So I'm trying to move the expensive part out so it happens only once, a...
No, there is no way to do this. What you *can* do, is use temp tables, like you said, or use a materialized view.
As stated in my comment even if that syntax worked it would not achieve the objective of a single trip to the database as a CTE is just syntax. Given the t.Row > 1740 AND t.Row <= 1760 I would go #temp over temporary table I like the simplicity of a temporary table but it does not query optimize well This assumes I...
Using the results of a WITH query in multiple subqueries
[ "", "sql", "sql-server", "t-sql", "common-table-expression", "" ]
Consider the following table: ``` CREATE TABLE foo ( id INT PRIMARY KEY, effective_date DATETIME NOT NULL UNIQUE ) ``` Given a set of dates D, how do you fetch all rows from foo whose effective\_date is the greatest value less than each date in D in a single query? For simplicity, assume that each date will ...
Actually, your problem is - that you have a list of values, which will be treated in MySQL as *row* - and not as a set - in most cases. That is - one of possible solutions is to generate your set properly in application so it will look like: ``` SELECT '2013-02-20' UNION ALL SELECT '2013-06-30' UNION ALL SELECT '2...
perhaps this can help : ``` SELECT * FROM foo WHERE effective_date IN ( (SELECT MAX(effective_date) FROM foo WHERE effective_date < '2013-02-20'), (SELECT MAX(effective_date) FROM foo WHERE effective_date < '2013-06-30'), (SELECT MAX(effective_date) FROM foo WHERE effective_date < '2013-12-19') ) ``` resu...
Return rows with maximum date less than each value in a set of dates in SQL
[ "", "mysql", "sql", "" ]
I have two tables, "user", and "user\_things". I want to get all users with one or more things, but I don't want to retrieve the things themselves (I only want one row per user returned). ``` Table 1: id username Table 2: id userid thingname ``` Example: I want to find all users with a "hat" and a "car". If there ar...
Select all users for which a record for 'car' and for 'hat' `exists` in the other table. ``` select * from User u where exists ( select 'x' from Things t where t.userid = u.id and t.thingname = 'hat') and exists ( select 'x' from Things t where t.userid = u.id and t.thingname = 'car...
Use aggregation: ``` select u.userid, u.username from user u join user_things ut on ut.userid = u.id group by t1.userid, t1.username having sum(case when ut.thingname = 'hat' then 1 else 0 end) > 0 and sum(case when ut.thingname = 'car' then 1 else 0 end) > 0 ``` The first part of the `having` clause...
How to do left join without select
[ "", "sql", "" ]
I have a SQL Server database that contains two tables both of which contain email addresses. One contains email addresses that have been created by the organisation for the users, the other contains users personal email addressees. We want to give the user the option to set one of these as the preferred contact email ...
Here is one way to modal this: ![enter image description here](https://i.stack.imgur.com/Ls5cS.png) NOTE: If there are no *(specific fields)* or *(specific constraints)*, just merge all three email tables into one. The EMAIL's composite PK establishes an ordering of emails at the level of the given person. You can t...
I would create an e-mail address table with columns `email_id`, `email_address`, `employee_id`, and `type` (a flag for personal or organizational). I would then add the column `preferred` to my employee table, and have it store the appropriate `email_id`. I would assume email addresses must be DISTINCT, so you likely ...
Two database tables storing email addresses, one of the addresses to be set to default
[ "", "sql", "sql-server", "database", "database-design", "" ]
**Creating Table:** ``` CREATE TABLE test ( charcol CHAR(10), varcharcol VARCHAR2(10)); SELECT LENGTH(charcol), LENGTH(varcharcol) FROM test; ``` **Result:** ``` LENGTH(CHARCOL) LENGTH(VARCHARCOL) --------------- ------------------ 10 1 ``` Please Let me know what is the difference...
Simple example to show the difference: ``` SELECT '"'||CAST('abc' AS VARCHAR2(10))||'"', '"'||CAST('abc' AS CHAR(10))||'"' FROM dual; '"'||CAST('ABC'ASVARCHAR2(10))||'"' '"'||CAST('ABC'ASCHAR(10))||'"' ----------------------------------- ------------------------------- "abc" ...
Although there are already several answers correctly describing the behaviour of `char`, I think it needs to be said that **you should not use it** except in three specific situations: 1. You are building a fixed-length file or report, and assigning a non-null value to a `char` avoids the need to code an `rpad()` expr...
What is the major difference between Varchar2 and char
[ "", "sql", "oracle", "char", "varchar2", "" ]
If any SQL gurus could point me in the right direction on this would be a huge help. I'm learning SQL and want to create a report that would generate the Account #s under the *same* Person ID that were created <= 30 days of each other and exclude any others. All the information needed is in the same table. For example...
I would use a semi join: ``` select accountid, creationdate, personid from Table1 t1 where EXISTS( SELECT 1 FROM Table1 t2 WHERE t1.personid = t2.personid AND t1.accountid <> t2.accountid AND t1.creationdate BETWEEN t2.creationdate - interval 30 day AND t2.creationdate + inte...
``` select distinct(personid, accountID) from Table1 where Table1 personid in ( select distinct(t1a.personid) from Table1 as t1a join Table1 as t1b on t1a.personid = t1b.personid and t1a.creationdate < t1b.creationdate and datediff(dd, t1a.crea...
How to compare dates for multiple rows under the same table and same account
[ "", "sql", "sql-server-2008", "t-sql", "compare", "report", "" ]
I have problem with one query. I have this Orders table: ``` workerID orderID Year orderCount 274 869 2008 14 274 758 2006 2 274 770 2006 13 274 853 2006 10 ``` And I need to create table like this one: ``` workerID orderID Year orderCount sumByYears 274 2005 30...
What you want is commonly called a running total. In SQL Server 2012, you can use `SUM() OVER ()` to calculate it. ``` SELECT workerID, Year, orderCount = SUM(orderCount), sumByYears = SUM(SUM(orderCount)) OVER (PARTITION BY workerID ORDER BY Year) FROM Orders GROUP BY workerID , Year ORDER BY workerID , Yea...
Assuming you want a literal string This should do it: ``` SELECT workerID , Year , SUM(orderCount), '(orderCount for year' + Year + ')' FROM Orders GROUP BY workerID , Year ORDER BY workerID , Year ; ``` If what you're really after is the rolling sum of the order counts by year then I believe this should work: ``` ...
sum amount by next years mssql
[ "", "sql", "sql-server", "sql-server-2012", "" ]
So I have a floating point **41617.063633** and I want to know how its made from a DATETIME . I have worked out the left side of the floating point (number of days since *12/30/1899*). But I'm stuck on the right side. I assume its a count of seconds or something, but I can't get the right side (*063633*) no matter wha...
You're correct about the meaning of the whole number part (the part to the left of the decimal). The fractional part (the part to the right of the decimal) indicates a portion of a 24-hour period. ``` Decimal value Time Value Calculation ============= ========== =========== 0.00094444444 12:01:00 AM ...
It all depends on what type of datetime. There is currently 6 different version in SQL Server 2012. <http://msdn.microsoft.com/en-us/library/ff848733.aspx> As for date time, the value should be interpreted as two 32-bit integers. The number of days since 1/1/1900 and the time since midnight. It is accurate to increm...
How does CONVERT (DATETIME, FLOAT) work?
[ "", "sql", "sql-server", "datetime", "" ]
I have a table: ``` CREATE TABLE passenger_details ( bank_card INT(20) NOT NULL AUTO_INCREMENT, email VARCHAR(20), mobile INT(15) NOT NULL, p_id INT NOT NULL, PRIMARY KEY (bank_card), FOREIGN KEY (p_id) REFERENCES passenger(p_id) ); INSERT INTO passenger_details VALUES (012301230...
`INT` has a [maximum signed value of 2147483647](http://dev.mysql.com/doc/refman/5.0/en/integer-types.html). Any number greater than that will be truncated to that value. What you need to do is change that column to be a `varchar(20)` which will hold strings of up to 20 characters since bank card numbers are strings an...
Something to ask yourself. How did the number get that big? I did not insert 2 billion rows! Well, possibly you 'burned' that many `AUTO_INCREMENT` ids. This can happen in man ways: ``` INSERT IGNORE ... -- when the insert is ignored (because it the row already exists) REPLACE IODKU ``` and probably others.
ERROR 1062 (23000): Duplicate entry '2147483647' for key 'PRIMARY'
[ "", "mysql", "sql", "" ]
I am working on SQL and I have the following problem: ``` select * from( select tname,teacher.tid,grade from teacher inner join _view on(_view.tid=teacher.tid))as D group by grade where // what should I do here to get the rows having the first and the second maxium values? order by g...
ok after too much thinking I got this to work right and smooth, more over TOP would not work just LIMIT in the end of the query , here is my answer: ``` select * from( select tname,teacher.tid,grade from teacher inner join _view on(_view.tid=teacher.tid) )as D where grade in(select grade from _view order by grade de...
Try: ``` ORDER BY grade DESC LIMIT 2 ```
sql where condition for getting the first and second maxium values
[ "", "mysql", "sql", "" ]
I am building an app to support 200,000+ registered users, and want to add an addressbook functionality for each user to import their own contacts (e.g. name, address, email, etc). Each user will have c.150 different contacts, with 10-15 fields for each record. My question is simple: given the volume of users and the ...
**Specific answer in response to specifications** One table for contacts' data, with an indexed foreign key column back to user. Finding a particular user's contacts [will require about 3 seeks](http://dev.mysql.com/doc/refman/5.5/en/estimating-performance.html), a relatively small number. Use a SSD if seeks are bottle...
Have a Single table, but **partition** the table by the starting alphabet of the user like all Last Names starting with A will be loaded into 1 partition. All names starting with B will be loaded into another partition. You could also do some amount of profiling to find the right distribution key.
MySQL Performance: Single table or multiple tables for large datasets
[ "", "mysql", "sql", "performance", "database-performance", "" ]
I'm trying to figure out what the pattern is for using named parameters in go's built-in database/sql package. I looked at the oracle driver, but it seems like just a wrapper for the C library. Have people solved this in an elegant way? So far I've just worked around the problem by putting `{0}`, `{1}` as the parameter...
It would be possible to create a `map[string]interface{}` type that implements `driver.Valuer{}` to serialize it as a `[]byte`, and then convert it back in the driver. But that would be inefficient and unidiomatic. Since your driver would then be used in a nonstandard way anyway, it would probably be better to just fo...
I'm using wrapper on top of database/sql called sqlx <https://github.com/jmoiron/sqlx> You can check here how he did it. Example on how to select into a tuple ``` type Person struct { FirstName string `db:"first_name"` LastName string `db:"last_name"` Email string } jason = Person{} err = db.Get(&jas...
named parameters in database/sql and database/sql/driver
[ "", "sql", "database", "go", "neo4j", "driver", "" ]
Here is my problem: I want to insert a new row in my table but there is already some registers in it. If I need to put this new row at the same row that a already register is, what should I do? For example: I have this table with this rows: ``` ID|Value 1 |Sample1 2 |Sample2 3 |Sample3 ``` But now I want to insert...
> Any thoughts? Yes. Please forget about changing the primary key (the ID) if you have references somewhere. Rather add a column (e.g. ViewOrder) which is handling this explicitly for you: ``` ID|Value | ViewOrder 1 |Sample1 |1 5 |NewSample |2 2 |Sample2 |3 3 |Sample3 |4 ``` Query to select: ``` SELECT I...
The easy way is to add a new column -- set it to the same value as ID and then you have two choices, if you make it numeric you can just add a value in between ``` ID | Value | OrderCol 1 | Sample1 | 1 4 | NewSample | 1.5 2 | Sample2 | 2 3 | Sample3 | 3 ``` your other option is to renumber order -- whic...
SQL How to insert a new row in the middle of the table
[ "", "sql", "sql-server", "" ]
Forever I've used a case sensitive collation in Sql Server (SQL\_Latin1\_General\_CP1\_CS\_AS). I'm trying to move to Sql Azure Database and I've run into an unexpected problem. It looks like it's impossible to have case sensitive column names. Can this be true? I create my database... ``` CREATE DATABASE MyDatabase ...
**I think this is a bug in Windows Azure SQL!** On line documentation states that you can override the collation at the database, column or expression levels. You can not do it at the server level. <http://msdn.microsoft.com/en-us/library/windowsazure/ee336245.aspx#sscs> Lets start with something we know will work, ...
To solve your case you need to add CATALOG\_COLLATION. ``` CREATE DATABASE MyDatabase COLLATE SQL_Latin1_General_CP1_CS_AS WITH CATALOG_COLLATION = DATABASE_DEFAULT ``` Source: [What will happen with CATALOG\_COLLATION and Case Sensitive vs Case Insensitive](https://blogs.msdn.microsoft.com/azuresqldbsupport/2018/02/...
Case Sensitive column names in Sql Azure Database
[ "", "sql", "sql-server", "database", "azure", "" ]
I am trying to execute the following query: ``` UPDATE table1 SET column1 = NULL WHERE column1 = (SELECT column1 FROM table1 WHERE id = @id) ``` on MySQL server but I get the follwing error message: "Error Code: 1093. You can't specify target table 'table1' for update in FR...
``` SET @column1 = (SELECT column1 FROM table1 WHERE id = @id) UPDATE table1 SET column1 = NULL WHERE column1=@column1 ```
Add an extra `SELECT` to the inner query. This will act as a "different" table since you are selecting from `a` instead of `table1`: ``` UPDATE table1 SET column1 = NULL WHERE column1 = ( SELECT column1 FROM ( SELECT column1 FROM table1 WHERE id = @id )a); ``` `sqlfiddle demo`
SQL query works on SQL Server but not on MySQL
[ "", "mysql", "sql", "" ]
I am facing problem with an SQL query: Here is my table data: ``` +------------+--------+--------+------------+------------+ | priceId_PK | mPrice | aPrice | validFrom | validTo | +------------+--------+--------+------------+------------+ | 1 | 0.00 | 0.00 | 2013-07-01 | 2013-08-31 | | 2 | ...
I think you are trying to access the `validFrom` and `validTo` from the case query in the where condition. If that is the case, you need to reformat your query. ``` SELECT t1.* FROM ( SELECT mPrice, aPrice, CASE WHEN validFrom < '2013-11-01' THEN '2013-11-01' ELSE validFrom END AS validFrom, CASE...
Can you try this, added proper `()` for validfrom and validto columns ``` WHERE ( (validfrom BETWEEN '2013-11-01' AND '2013-11-30') OR (validto BETWEEN '2013-11-01' AND '2013-11-30') ) ORDER BY validFrom ```
WHERE condition issue in SQL
[ "", "mysql", "sql", "" ]
I have a query to show customers and the total dollar value of all their orders. The query takes about 100 seconds to execute. I'm querying on an ExpressionEngine CMS database. ExpressionEngine uses one table `exp_channel_data`, for all content. Therefore, I have to join on that table for both customer and order data....
If this is the same table, then the same columns across the board for all alias instances. I would ensure an index on (channel\_id, entry\_id, field\_id\_117 ) if possible. Another index on (author\_id) for the prequery of order totals Then, start first with what will become an inner query doing nothing but a per cust...
Can you post the results of an `EXPLAIN` query? I'm guessing that your tables are not indexed well for this operation. All of the columns that you join on should probably be indexed. As a first guess I'd look at indexing `exp_channel_data.field_id_117`
Slow aggregate query with join on same table
[ "", "mysql", "sql", "expressionengine", "" ]
I have the code for the next button. The data in the database show up normally. The problem is when I click next button, the data will be repeated again as --> data1 > data2 > data3 > data1 > data2... I've to been told that I should count the maximum rows but I didn't know how to do it; I've search for the coding...
A bit more code... this is *bad* code... don't rely on it for production since I'm sure there are plenty of corner cases it doesn't handle, but I wanted to give you a picture of how you could handle it and at least a glimpse of stuff you might need to worry about (e.g. 0 rows in the data table). Please work through thi...
`dt.Rows.Count` is the number of rows in the Rows collection. Anytime you want to check the whether you've reached the maximum number of rows compare the row count to dt.Rows.Count
How to count Maximum rows in Visual Basic
[ "", "sql", "vb.net", "vba", "count", "rows", "" ]
Let's say I have table of number pairs: ``` a | b --+-- 1 | 1 2 | 1 3 | 1 2 | 2 4 | 2 5 | 5 1 | 3 ``` For each `b` I want to pick an `a` such as there are no 2 identical `a`s for different `b`s. If I do a simple query with `group by`: ``` select * from t group by b ``` I get the following results back: ``` a | b ...
I think the first approach will be: ``` select MAX(a) as a, b from t as t1 where NOT EXISTS(select a from t where b<>t1.b and a=t1.a) or NOT EXISTS(select a from t where a in (select a from t where b=t1.b) GROUP BY a HAVING COUNT(*)=1) GROUP BY b ``` `SQLFiddle ...
try this ``` select max(a),b from t group by b; ```
How to select the largest subset of pairs with unique elements?
[ "", "mysql", "sql", "select", "greatest-n-per-group", "" ]
I have a table called votes. ``` ID int(11) pk ai candidate_id int(11) region varchar(75) ``` Can I get an result with an sql statement with something like ``` West 46 East 75 North 28 etc... ``` West, East being regions... Thanks
``` SELECT region, COUNT(region) FROM votes GROUP BY region ORDER BY 2 DESC ``` Hmm, elaborating on your request for totals of votes per candidate, will depend on how your data is laid out. Do you simply have one row per vote for a candidate, if so, then I'd try (although I haven't tested); ``` SELECT region, COUNT(r...
Assuming you want one string, containing both fields, you can use MySQL's CONCAT function to concatenate. Example: ``` SELECT DISTINCT region, SUM(*) as votes_count, CONCAT(region, " ", votes_count) FROM votes ``` [More info on CONCAT()](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat)
count the number of rows with a particular column value
[ "", "sql", "database", "" ]
I looking for way to run select query by O(1). Can I create index in this way that SELECT by primary key will take O (1) time complexity?
A [clustered primary key](http://msdn.microsoft.com/en-us/library/ms177443%28v=sql.105%29.aspx) is organised as a [b-tree](http://en.wikipedia.org/wiki/Hash-Based_Indexes). The clustered key is not a [hash-based index](http://en.wikipedia.org/wiki/Hash-Based_Indexes), which is required for [O(1)](http://en.wikipedia.o...
IIRC, some RDBMS engines have hash table indexes. That would AFAIK give you amortized constant time as you so desire. AFAICT, MS SQL Server does not have this feature.
Select by O(1) from SQL table
[ "", "sql", "sql-server", "select", "indexing", "time-complexity", "" ]
I have this row in my database table with a value of `1/5/2013 5:50:00 PM`, and I want to update only the date part. Time should be same without any change, need to change only the date in this record. I have tried the update statement but it change the time as well..but I can do a ``` UPDATE table1 SET date = '1/10/...
You can do it this way if you're using SQL Server 2008 or higher ``` UPDATE table1 SET [date] = cast('1/10/2013' as datetime) + cast(cast([date] as time) as datetime) WHERE id =1 ``` If you're using SQL Server 2005 or below, you there's no `time` data type, so you have to do: ``` UPDATE table1 SET [date] = cast('1/1...
``` UPDATE table1 SET date = DATEADD(dd,5,date)-- 5 is the number of days FROM table1 WHERE id =1 ```
Update date only in SQL Server
[ "", "sql", "sql-server", "sql-server-2005", "" ]
For example: in my db, there are 10 records: 500, 501, 502, 503, 504, 506, 507, 508, 509, 510. I want to get 505 which is not used. (The start number is 500). If 501, 502, 503 in db, I want to get 500. I use MySQL.
Another way to do it ``` SELECT number + 1 first_unused FROM ( SELECT 499 number UNION ALL SELECT number FROM table1 WHERE number >= 500 ) t WHERE NOT EXISTS ( SELECT * FROM table1 WHERE number = t.number + 1 ) LIMIT 1 ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!2/8d470/2)** demo
if you can get know the total sum (i.e., total sum of 500 to 510 without missing number) then, try ``` SELECT <total sum> - SUM(<field name>) FROM <table name>; ``` Eg: for db 1,2,3,4, 5, 7, 8, 9, 10 code is: ``` SELECT 55 - SUM(id) FROM 'a' ```
Using SQL to get the minimal unused number from a set of continuously increasing numbers
[ "", "mysql", "sql", "" ]
I have a table that contains student IDs and their GPA. ``` _____________ | sID | GPA | ------------- | 1 | 3.7 | | 2 | 3.9 | | 3 | 3.6 | | 4 | 3.7 | | 5 | 3.1 | | 6 | 3.9 | ``` I wanted to create a table that gives me only the students who have the highest, or second highest GPAs. In other words, **I wan...
You can do it like this: ``` select * from gpaTable where gpa in ( select distinct gpa from gpaTable order by gpa desc limit 2 ) ``` The idea is similar to your first solution, except `MAX` is replaced with ordering and a [`LIMIT 2`](http://www.postgresql.org/docs/8.1/static/queries-limit.html) [Demo on sqlf...
Would it not be easier to just select the top 2 entries in the subselect? You could, e.g., use [`LIMIT`](http://www.postgresql.org/docs/8.1/static/queries-limit.html): ``` SELECT * FROM gpaTable WHERE gpa in (SELECT DISTINCT gpa FROM gpaTable ORDER BY gpa DESC LIMIT 2) ORDER BY gpa; ```
Subtracting one table from another in PostgreSQL
[ "", "sql", "postgresql", "" ]
I have this sql query: ``` select ct.ID, t.Tag from links ct inner join tags t on ct.ID_TAG = t.ID_TAG ``` returning this resultset: ``` ID | Tag -------------------------------------------------- 3e39e18a-f741-4ab8-9225-b11d8a6df440 | apps 3e39e18a-f741-4ab8-9225-b11d8a6df440 | te...
Try this: ``` select ct.ID from links ct inner join tags t on ct.ID_TAG = t.ID_TAG where t.Tag in ('github', 'octocats') group by ct.ID having count(distinct t.tag) = 2; ``` This should give you the id's that have both tags
syntax wise simplest is to do `in` ``` where t.Tag in ('github', 'octocats') ```
aggregation in Tsql
[ "", "sql", "t-sql", "join", "aggregate-functions", "" ]
I have two tables. 1. NEW [contains data] [all columns are varchar] 2. NEW2 [empty table] [columns are of different data types] I want to copy all data from New to New2. What i did is, ``` SELECT T.* INTO #tmp FROM (SELECT * FROM [dbo].[new]) AS T ``` then ``` INSERT INTO New2(col1, col2....) SEL...
Yes. Done. What I did is, Imported Excle data in SQL Server table with all columns in a table as varchar data type. The problem was in excel data, the date values, somewhere was NA. So I had to replace all those NA values with null. To check for those invalid date values in a table, I used following command. ``` SEL...
While inserting cast your column to `smalldatetime` ``` SET DATEFORMAT ymd INSERT INTO New2(col1, col2....) SELECT Col1,Col2 , CAST('2007-05-08 12:35:29' AS smalldatetime) As Col_Name,...Col3 FROM #TMP ```
How to copy data from one table to another where column data types are different?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am looking for a SQL-function that gives the last 12 months with Start Date and End Date. Say you pick 10.Dec, it will give a result in: ``` - StartDate -- EndDate - 2013-11-01 - 2013-11-30 - 2013-10-01 - 2013-10-31 - 2013-09-01 - 2013-09-30 ``` and so it goes for the last 12 months. I tried modifyi...
Please try using CTE: ``` ALTER FUNCTION [dbo].[Last12Months] ( @Date datetime ) RETURNS @tbl TABLE (Start datetime, EndDate datetime) AS BEGIN WITH T AS( SELECT DATEADD(month, DATEDIFF(month, 0, @Date), 0) AS Start, DATEADD(d, -DAY(DATEADD(m,1,@date)),DATEADD(m,1,@date)) AS EndDate, ...
This seems to do the job - whether you want to put it in a function or just wherever you need to have the data: ``` ; With Numbers as ( select ROW_NUMBER() OVER (ORDER BY number ) as n from master..spt_values ), Months as ( select DATEADD(month,n,'20010101') as start_date, DATEADD(month,n,'20010...
SQL function for last 12 months
[ "", "sql", "sql-server", "function", "date", "" ]
I have a situation where I have to generate a range of date (say start date and end date). Now I want to fill the records of specific dates on those generated dates. ``` ;WITH DateRange AS ( SELECT @start_date DateValue UNION ALL SELECT DateValue + 1 FROM DateRange WHERE DateValue + 1 <= @end_da...
[updated 2013-12-18 11:22 UTC] [updated 2013-12-18 14:19 UTC] [updated 2013-12-19 11:11 UTC] as i did not know the name of the table you are using, i created one named `yeahyeah`. you should replace that with the name of your own table obviously. i have inserted the values you mentioned (fromdate todate duration a...
You can write a query as below: ``` declare @start_date datetime,@end_date datetime ; set @start_date ='2013-01-01' ; set @end_date = '2013-01-05' ; DECLARE @columns NVARCHAR(MAX),@sql NVARCHAR(MAX); SET @columns = N''; WITH DateRange AS ( SELECT @start_date DateValue UNION ALL SELECT DateValue + 1 FR...
Generate a range of date and compare with another range of date and pivot it
[ "", "sql", "sql-server", "" ]
I've got a table `Customer (ID, Ref, LastName, FirstName)`. I have to bring out all lines whose reference is the same at least four times. I tried this unsuccessfully : ``` SELECT * from MyTable Where (select count(ref) from MyTable Group By ref) >= 4 ``` Of course it is wrong, but I don't know how to do this in on...
You need to use `HAVING` clause like below ``` SELECT * from Customer Where ref in (select ref from Customer Group By ref having count(*) >= 4) ``` **[SQL Demo](http://sqlfiddle.com/#!3/405b3/1)**
If I understand correctly, you can use the [`Having`](http://technet.microsoft.com/en-us/library/ms180199.aspx) clause in the query: ``` SELECT Ref, LastName, FirstName from MyTable group by Ref, LastName, FirstName having count(*) >= 4 ``` I have omitted `ID`, since this is possibly a primary key and probably not ...
SQL Query, get only the line where a value appear 4 time
[ "", "sql", "t-sql", "" ]
So, while I recognize that date formatting etc. should be done in the presentation layer, I am interested to know if anyone has seen or recognized this difference (please try at home, if so inclined) I am a little baffled and mostly curious, the sample code first. *UPDATE: To clarify based on the initial responses, I ...
It is worth mentioning that DATE and DATETIME are completely different datatypes. DATE is not simply DATETIME with the time removed. For example, CAST('17520910' AS DATE) works, while the similar conversion to DATETIME does not. For you history buffs, there was no such day in England or her colonies, the calendar skipp...
can you tried with ``` DECLARE @RawValue NVARCHAR(30), @Value DATE; SET @RawValue = '01.20.1901' -- or '01/20/1901' SET @Value = CAST(@RawValue AS DATE) PRINT @Value ```
DATE vs. DATETIME casting of invalid dates in SQL SERVER 2008 R2
[ "", "sql", "date", "datetime", "sql-server-2008-r2", "" ]
I am getting a date conversion error when trying to execute SQL from and an Access database against a SQL database. Our machines are all running windows 7 with office 2010. The front end is an accde. There is a search form in the database and all the fields work fine, except the two date fields. The query's where cla...
We had this exact same error on just one machine and solved it by removing, then re-adding our reference to DAO360.DLL (Under Visual Basic Tools->References). It never showed as MISSING. This is definitely not a pass-through (i.e. uses a linked table), as the # date literal termination character is definitely an Acces...
The question is, whether your query is a Pass-Through-Query or not (the fact that the table is linked is irrelevant). If the query is Pass-Through then you must write it in the SQL-Server dialect, otherwise in Access dialect. Pass-Through is a property of the query, not a property of the table. Another point is whethe...
Date conversion error - MS Access front end querying sql back end
[ "", "sql", "date", "ms-access", "" ]
In a select query I can make-up columns but how can I assign values for them? Example ``` select a.col1, a.col2, 'column3' from A a union select b.col2, b.col3, b.col3 as `column3` from B b ``` I want to assign a default value of `-1` to the `column3` column I made in the first query. Also, I want the title of the...
Try this ``` select a.col1, a.col2, -1 as column3 from A a union select b.col2, b.col3, b.col3 from B b ``` Or this if b.col3 is varchar ``` select a.col1, a.col2, '-1' column3 from A a union select b.col2, b.col3, b.col3 from B b ``` If A and B table has the same values for the tree columns the database will d...
``` To create a dummy column and assgin values to it we can use select a.col1, a.col2, '-1' as col3 from A a ```
How to assign a values to a column made in a select query
[ "", "mysql", "sql", "" ]
I have boiled down a date query to its fundamental pieces in an effort to make a query easier for me to understand. My trouble is that I am trying to trigger an append event if and only if theier anniversary date is equal to today or in the past. My query works except when I get to the criteria of <=Date(). Here is my ...
I've been experimenting with variations of your `DateSerial` to `Date` comparison. The only way I could trigger *"Data type mismatch in criteria expression"* was with Null in `[WM DOH]`. Exclude any rows where `[WM DOH]` contains Null.
**Assuming you query execute successfully.** I have convert the having cluse to the where claus ePlease @DesertSpider use following SQL query. ``` SELECT ActiveAssociates_3.UserID , ActiveAssociates_3.[WM DOH] , DateValue(DateSerial(Year(Date()),Month([WM DOH]),Day([WM DOH]))) AS Anniversary FROM ActiveAssociates_...
Date Trouble in SQL
[ "", "sql", "ms-access", "" ]
I've searched around for an answer and it seems definitive but I figured I would double check with the Stack Overflow community: Here's what I'm trying to do: ``` INSERT INTO my_table VALUES (a, b, c) RETURNING (SELECT x, y, z FROM x_table, y_table, z_table WHERE xid = a AND yid = b AND zid = c) ``` I get an error ...
@corvinusz answer was wrong for 8.3 but gave me a great idea that worked so thanks! ``` INSERT INTO my_table VALUES (a, b, c) RETURNING (SELECT x FROM x_table WHERE xid = a), (SELECT y FROM y_table WHERE yid = b), (SELECT z FROM z_table WHERE zid = c) ``` I have no idea why the way it's stated in the question is ...
Try this. ``` with aaa as ( INSERT INTO my_table VALUES(a, b, c) RETURNING a, b, c) SELECT x, y, z FROM x_table, y_table, z_table WHERE xid = (select a from aaa) AND yid = (select b from aaa) AND zid = (select c from aaa); ``` In 9.3 similar query works.
INSERT INTO ... RETURNING multiple columns (PostgreSQL)
[ "", "sql", "postgresql", "" ]
I have table `IteamMaster` and query as below, ``` Select ItemID from ItemMaster Where ItemID IN(1,2,...,100) ``` this query returns me the all the values from the table which are available now what i want is the query should return the itemID which are not present in the table that is suppose My table has data as...
You can't magic values up out of no-where. Whatever you select FROM must contain the value you want. Using the system table `master..spt_value` you can generate a long list of values, and check for numbers that are in there, but not in your table... ``` ;With Numbers as ( select ROW_NUMBER() OVER (ORDER BY number)...
What about this? ``` Select ItemID from ItemMaster Where ItemID NOT IN(1,2,...,100) ```
Get the values which is not present in table?
[ "", "sql", "sql-server", "sql-server-2008", "exists", "" ]
I am using mysql DB server .. I have the following table that consists of only one column with the following data (where 0's separate sorted integers) ``` Number ------- 0 1 2 3 0 4 5 0 6 7 8 0 9 10 0 11 ``` I want to get the first value that comes after each 0 , so e.g. output would be ``` Output ------ 1 4 6 9 11...
``` SELECT id1 FROM table WHERE id IN (SELECT t1.id+1 FROM table t1 LEFT JOIN table t2 ON t1.id1=t2.id WHERE t2.id1 IS NULL); ``` [**SQL Fiddle**](http://sqlfiddle.com/#!2/4ab8a/15) Assuming no gaps in the increment field,but since it will be created..
MySQL doesn't guarantee a return order unless you specify a `ORDER BY` clause. If you get the values back in the order you insert them then that's just coincidence. As it stands there's no way to do what you want to do reliably. You need to add something to order the data by. An ID field set to `autoincrement` will pro...
How can I return the next row of WHERE clause?
[ "", "mysql", "sql", "" ]
There is a postgresql installation on my server that worked fine so far. However now there is a single table (all other tables work fine) which I cannot open through pgadmin3 or drop. I've tried restarting the server. Didn't help. I also tried dropping the table with DROP TABLE from the command line on the server. It'...
Most probably explanation: some other open transaction is holding an exclusive lock on the table. You are using **pgAdmin**, so you can check with [**`Tools -> Server Status`**](http://www.pgadmin.org/docs/dev/status.html). The activity pane lists all current connections. For instance, there is one (or more) listings ...
You could try taking a dump of the database and see if that works? Also have a look at the <http://www.postgresql.org/docs/9.1/static/runtime-config-logging.html#GUC-CLIENT-MIN-MESSAGES> and log\_min\_messages options. Change that to debug and see what is happening when you try to drop the table.
How to delete a table in postgresql
[ "", "sql", "linux", "postgresql", "ubuntu", "" ]
This's my database sample: *orderdetails* table with the ProID relate to *products* tabale ``` | ProID | OrderID | OrderQuantity | OrderPrice | | 93 | 17 | 1 | 150 | | 16 | 18 | 1 | 100 | | 93 | 19 | 3 | 450 | | 93 | 17 | 1 ...
You can use a SQL join between the tables on ProID, e.g. ``` from products as p inner join orderdetails as od on p.ProID = od.ProID ``` You can use *group by* syntax to ensure you get distinct rows, e.g. ``` group by p.ProID ``` Use aggregation function such as sum, count and avg to find out the totals in a sele...
You can try the following query - ``` select * from products where ProID = (select ProID from (select ProID , sum(OrderQuantity) as total_order, max(sum(OrderQuantity)) over() as maxSm from orderdetails group by ProID ) where total_order = maxSm) ```
How can I query this sql to get the best-selling product
[ "", "mysql", "sql", "" ]
I'm trying to get a list of all citizens of a country and list them in a table with 3 rows. The last row shows 'YES' or 'NO' depending on whether or not the person was born in a certain city. What I did was create two queries: The first query gets all the citizens who were born in the city, and the second query gets a...
You shouldn't need a `UNION` for this (and generally, when you have two queries that can't possibly intersect, you should use `UNION ALL` which avoids a unique sort (or similar operation)). Also, `DISTINCT` cannot apply to a single column, as your current query seems to imply. I find it unlikely that there are duplicat...
Try this: ``` SELECT DISTINCT(CountryCitizenID), Country, case when fte.CitizenID is not null then 'YES' else 'NO' As Resident FROM DT_Country_CitizenS dtu LEFT JOIN (select * from FT_City where cityID = 5) fte ON (dtu.CountryCitizenID = fte.CitizenID)...
creating an efficient query with a UNION
[ "", "sql", "sql-server", "t-sql", "" ]
In MS Access, I have a table like below: ``` FY Percent 2015 5% 2016 5% 2017 5% 2018 5% 2019 5% 2020 5% ``` Now I want to add a calculated row and that row should be calculated as shown below: ``` FY Calculated 2015 P * 1 (Multiply the value by 1 for first year) 2016 P * ...
There's no way to do this in plain Access' SQL dialect. So, VBA is the choice. You will need to create a table to hold the values. Let's say your output table is something like this: **Table: `tbl_output`** ``` FY Integer Calculated Double ``` The VBA code: ``` public sub fillCalculatedValues() D...
I am by no means sure what you mean, perhaps ``` SELECT t.FY, t.Calculated, Nz((SELECT Max(CPercent) FROM tFY WHERE FY< t.FY),1) * Percent AS [Last Value] FROM tFY AS t ``` Then, re comment ``` SELECT t.FY, (SELECT Sum(Percent) FROM tFY WHERE FY<= t.FY) AS [Calc Value] FROM tFY ...
How to take a cumulative previous year record?
[ "", "sql", "ms-access", "" ]
I am attempting to select the number of players in a softball database using GROUP BY and HAVING but am not getting the results I expect. Can someone help me understand what is wrong with this query? I expect it is a simple mistake that I am overlooking. ``` SELECT player_id AS 'players', SUM(sb_stats_HR) FROM `softb...
This should work. ``` SELECT player_id AS 'players', SUM(sb_stats_HR) AS 'homers' FROM softball_stats GROUP BY player_id HAVING SUM(sb_stats_HR) > 3; ```
Use backticks,you are playing with strings. ``` SELECT player_id AS `players`, SUM(sb_stats_HR) FROM `softball_stats` AS `homers` GROUP BY `player_id ` HAVING `softball_stats` > 3; ``` If this doesnt work,edit your post with some sample data.
MySQL query related to GROUP BY and HAVING
[ "", "mysql", "sql", "" ]
Query 1: ``` create or replace procedure toUp(code in number) is sname staff_master.staff_name%type; recnotfound exception; begin select staff_name into sname from staff_master where staff_code=code; if sname is NULL then raise recnotfound; else update staff_master set staff_name=upper(staff_name) where staff_code=cod...
If a query returns no rows then an "ORA-01403: no data found" error is raised. Your expectation, I think, is that execution will continue but no value will have been assigned to the variable -- that's not the case. If what you want to do is check for the existence of a record then use: ``` select count(*) into row_...
Actually, exceptions happens even before your IF statement. If SELECT INTO statement doesn't return a row, ORA-01403 is thrown. You might expect that in this situation NULL value is assigned to variable, but it is not so and exception is thrown instead. You must add exception handling in your stored procedure to get o...
ORACLE PL/SQL check whether string is NULL
[ "", "sql", "oracle", "plsql", "" ]
My tables are structured like this (there are more values in the tables but I only wrote the ones relevant to this): ``` Department(dep_id, dep_name) Employee(dep_id) ``` I need to display dep\_name and the number of employees in every department, except once specific department (let's call it DepX) and only the de...
The first example does now work because you're including dep\_name in your results without an aggregation but not grouping on it. You can either use the department name in your grouping instead of the ID: ``` SELECT department.dep_name, COUNT(employee.dep_id) AS NumberOfEmployees FROM employee INNER JOIN department O...
``` SELECT department.dep_name, COUNT(employee.dep_id) AS NumberOfEmployees FROM employee INNER JOIN department ON employee.dep_id=department.dep_id WHERE department.dep_name not in('DepX') GROUP BY department.dep_name HAVING COUNT(employee.dep_id) > 1; ``` **update your table alias per your need**
SELECT specific information
[ "", "sql", "database", "oracle", "" ]
I am trying to filter a SELECT statament. The behavior I want is that if the parameter @productId = % then I want the WHERE clause to do the following: ``` WHERE (DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId) ``` If @productId does not = % I want the following WHERE clause: ``` WHERE (PDT.PK_Product = @produ...
``` WHERE (@productId = '%' AND (DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId)) OR (NOT @productId = '%' AND (PDT.PK_Product = @productId)) ```
``` --assumes -1 and 0 are invalid TaskIds WHERE PDT.PK_Product LIKE @productId OR coalesce(DTH.TaskId, -1) = case when @productId = '%' THEN -1 ELSE coalesce(DTH.TaskID,0) END ```
WHERE statement based on variable value
[ "", "sql", "sql-server", "" ]
Using MySQL, I'm trying to make a timestamp column from a date column and a time column. If the date or time column contains a NULL value, MySQL automatically sets the corresponding value in the `TIMESTAMP` column to the [`CURRENT_TIMESTAMP`](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function...
Use this query to add your column ``` ALTER TABLE `customers` ADD COLUMN `s_timestamp` TIMESTAMP NULL DEFAULT NULL; ``` And, if you want to get current timestamp on update only : ``` ALTER TABLE `customers` ADD COLUMN `s_timestamp` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP; ```
To add to accepted answer in case someone is looking to modify an existing column that was created defaulting to current\_timestamp: ``` alter table `customers` modify `s_timestamp` timestamp null ``` The column will now not default to current\_timestamp anymore.
MySQL TIMESTAMP to default NULL, not CURRENT_TIMESTAMP
[ "", "mysql", "sql", "timestamp", "" ]
I have a data set with several heirachical variables: Region State County City District There is a series of variables which will be counted, summed, etc. for each combination of the above variables. This is simple enough with a basic proc sql, EXCEPT that the output file needs to include a row for the totals at each ...
You can use PROC TABULATE to generate easily reports with various nested variables and subtotals: ``` PROC TABULATE data=yourdata; CLASS Region State County City District; VAR Sales; TABLE Region*(State*(County*(City*(District ALL) ALL) ALL) ALL) ALL, Sales*sum; RUN; ```
Try PROC SUMMARY. ``` proc summary data=foo; class region state county city; var bar; output out=outData sum=sum; run; ```
SAS: Summing to different levels
[ "", "sql", "sas", "" ]
I have a query which looks something like this: ``` select tb1.col1, tb1.col2, tb2.col4, tb2.col7 from server_1.database_a.dbo.table_1 tbl1 inner join server_2.database_c.dbo.table_2 tbl2 on tbl1.col_id = tbl2.col_id ``` This query runs fine (I had to create an link on the sql server to link the 2 servers for the que...
Try it: ``` use database_a; select tb1.col1, tb1.col2, tb2.col4, tb2.col7 from dbo.table_1 tbl1 inner join server_2.database_c.dbo.table_2 tbl2 on tbl1.col_id = tbl2.col_id ```
server\_1.database\_1.dbo.table\_1 this is not the same with you write first. Its: server\_1.database\_a.dbo.table\_1 may be the reason is this.
Can't run SQL query via SQL job
[ "", "sql", "sql-server-2008", "sql-job", "" ]
After many trails and tribulations I was able to write the following query. ``` SELECT repName.repID, repName.Rep_Name, Positions.Position, repName.Roster, DataSheet.ENTERED FROM DataSheet INNER JOIN repName ON DataSheet.EE_ID = repName.repID INNER JOIN ...
To return TOP N Rows just use the following ``` SELECT TOP (1) /* rest of your query*/ ``` You can also use PERCENT with your TOP Clause something like this ``` SELECT TOP (10) PERCENT /* rest of your query*/ ``` If you have Same values in TOP N and you want all the rows TOP same values you can use something lik...
**IF SQL CE used this TOP(N). You must enclose the Number with parenthesis.** using Top N or Limit N in your query will return the oldest row because you order them using ``` ORDER BY DataSheet.ENTERED ``` If you wished to retrieved the latest row make your Sorting as ``` ORDER BY DataSheet.ENTERED desc ```
Return top record (or row 1) only from query
[ "", "sql", "sql-server", "" ]
I have one table which has 20 columns default These 20 columns named as D1 D2 D3...D20 , now with select query i want to add the other columns dynamically.. for ex D21 D22...D31, so how can i write a query to add this columns dynamically with incremented value..max limit is 31,please help default table columns D1 D...
try below code ``` declare @a int =21 Declare @sql varchar(max)='select *,' while @a <32 begin set @sql = @sql + cast(@a as varchar) + ' as D' + cast(@a as varchar) + ' ,' set @a = @a+1 end set @sql = substring(@sql,0,len(@sql)-1) + ' from tbl1' exec( @sql) ```
Using dynamic SQL, you can do something like this: ``` DECLARE @SQL AS NVARCHAR(MAX) = 'select *'; WITH Numbers (N) AS ( SELECT ROW_NUMBER() OVER (ORDER BY object_id) N FROM sys.all_objects ) SELECT @SQL = @SQL + ', '' '' as D' + CAST(N AS NVARCHAR) FROM Numbers WHERE N BETWEEN 21 AND 31; SET @SQL = @SQL + ' ...
add column dynamically with select query
[ "", "sql", "sql-server", "sql-server-2008", "dynamic-queries", "" ]
I am doing the following query, ``` SELECT 'Payment Token,Transaction ID,Create Date' FROM dual UNION ALL SELECT DISTINCT pt.mw_payment_token ||','|| t.mw_transaction_id ||','|| t.create_date FROM t_mw_payment_token pt, t_mw_transaction t where pt.mw_payment_token = t.mw_payme...
Here is the solution: ``` SELECT 'Payment Token,Transaction ID,Create Date' FROM dual UNION ALL SELECT mw_payment_token ||','|| mw_transaction_id ||','|| create_date FROM (SELECT DISTINCT pt.mw_payment_token, ...
Your problem is the `ORDER BY`-clause because it's global over the whole query and doesn't recognize `t.mw_transaction_id` in the whole statement. Same problem as in: ``` select 'a' from dual union all select dummy from dual order by dummy; ``` You can fix that by giving the columns in both queries the same alias:...
Error in where clause PL/SQL query selecting from dual
[ "", "sql", "oracle", "" ]