Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have this SQL commands, which I would like to run in one command. But if I remove the semicolon from between them, then it doesn't works anymore; ``` UPDATE runners SET money=20000 WHERE rrank >= 3; UPDATE runners SET money=25000 WHERE nev = 'Master'; ```
Partial (however generalized) solution (if `runners` is not *that big table*) ``` update runners set money = case when rrank >= 3 then 20000 when nev = 'Master' then 25000 -- any number of when here -- if no w...
Combine the logic into a single update: ``` UPDATE runners SET money = (case when nev = 'Master' then 25000 else 20000 end) WHERE rrank >= 3 or nev = 'Master'; ```
How to run more SQL updates in one SQL command?
[ "", "mysql", "sql", "" ]
I have a table named 'country' with a column named 'name' and the names in this column appears with translation followed by special character '/'. ``` IRELAND/IRLANDE GREECE/GRÈCE DENMARK/DANEMARK ``` Now i want only the countrynames before this special character'/' so the out put should look like this.. ``` IRELAND...
``` create table #t(name nvarchar(40)) insert into #t values('IRELAND/IRLANDE') ,('GREECE/GRÈCE') ,('DENMARK/DANEMARK') select substring(name,0,CHARINDEX('/',name)) from #t ```
Why LEN(names)-CHARINDEX('/',names)? try using CHARINDEX('/',names)+1 instead. As far as I remember, SUBSTRING's third variables should be the length of the desired output string.
How to remove text followed by a special characted in MSQL
[ "", "sql", "substring", "special-characters", "trim", "charindex", "" ]
I need to implement custom ordering for my table. For example I have a table called "TestTest" with values: `a, d01, d04, d02, b` . I need to select data and order them so that values with "d" will be first and rest will be sorted alphanumerical. So the result would be `d01,d02,d03,a,b` Script to create and insert dat...
``` Select * From TestTest Order By CASE WHEN LEFT(Name,1)='d' THEN 1 ELSE 2 END,Name ``` [**SQL Fiddle Demo**](http://www.sqlfiddle.com/#!3/ef9e7/1)
Quick soution: ``` Select * from TestTest order by case when Name like 'd%' then 'aaaaa'+Name else Name end ```
Custom ordering in TSQL
[ "", "sql", "t-sql", "" ]
I am in the process of converting some Access queries into tsql and this error pops up when I try to execute the query. I am guessing that SQL Server does not allow adding of 'bit' types, so I found the cultprit lines where that occurs and they are: ``` SELECT DISTINCT [modules].[b]+[modules].[w]+[modules].[e]+[mo...
you can't add bit fields in sql server But you can cast them to int so ``` CAST(yourBitField as int) + CAST (yourSecondBitField as int) ``` By the way (would say it's due to [type preference order](http://technet.microsoft.com/en-us/library/aa258264%28v=sql.80%29.aspx)), it will be ok if you cast only one of them ...
You cannot add bits in SQL Server, as they can only be 0 or 1. You can however convert them to integer values first and then add them. To convert a bit to an int, use the CAST function: ``` CAST([modules].[b] AS INT) + CAST([modules].[w] AS INT) + CAST([modules].[e] AS INT) ... etc ``` See more on SQL Server type con...
TSQL error: Operand data type bit is invalid for add operator
[ "", "sql", "sql-server", "t-sql", "" ]
I have an array of IDs: ``` [1, 2, 3, 4, 5, 6] ``` To check what records exist in the table I execute this query: ``` SELECT id FROM table WHERE id in (1, 2, 3, 4, 5, 6); ``` The query returns an `id` of every existing record but what if I want to know what records don't exist? For instance if a record with `id: 1`...
``` select idlist.id from ( select 1 as id union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 ) as idlist left join the_table on idlist.id = the_table.id where the_table.id is null; ``` SQLFiddle example: <http://sqlfiddle.com/#!2/b3a5b/1>
``` select id from table where id not in(1,2,3,4,5,6) ```
Return id of a non-existing record
[ "", "mysql", "sql", "" ]
Have a question about a query I am attempting to write, using SQL Server 2012. I have a table with 2 columns (Agent and UN) I am focusing on. I would like to find the number off occurrences that Agent and UN occur. For example, in the table below: ``` +----+-------+----+ | ID | Agent | UN | +----+-------+----+ | 1 | ...
Group by both agent and UN, and take out the condition from the where clause, to get the count for all groups. ``` select count(*), agent, un from tbl group by agent, un order by 1 desc ```
You should `GROUP BY` `UN` and `Agent` and then `COUNT` duplicates. To retrieve data for all possible values in `Agent` column you should remove your `WHERE` clause : ``` SELECT COUNT(*) as Count , Agent , UN FROM table GROUP BY UN , Agent ORDER BY COUNT(*) DESC ```
Get count of multiple column occurrences in SQL
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am trying to update the data in a particular column according to the data in another column. Some thing like below. ``` Name ImageName ---------- ----------- aaa no_image.jpg bbb no_image.jpg ccc no_image.jpg ddd no_image.jpg ``` I like to update ...
You could simply do this in an `UPDATE` query itself. Try this: ``` UPDATE table1 SET ImageName=Name+'.jpg' ```
``` Update table1 set imagename= name+'.jpg'; ```
Updating a column in sql
[ "", "sql", "" ]
I have a table with Names and university courses, with each course registered being a different entry in the table ``` NAME COURSE StudA Bio StudA Maths StudB Maths StudC Bio StudC Maths ``` How can I select all students registered for both Bio and Maths? I Tried ``` SELECT * FROM Tabl...
It depends on what you mean, are you looking for students registered for both math and bio, or for student registered in either of them? -- Student registered on both math and bio ``` select NAME from T where Course IN('Bio', 'Maths') group by NAME having count( distinct COURSE ) = 2 ```
Use `OR` instead of `AND`: ``` SELECT * FROM Table WHERE Course = 'Bio' OR Course = 'Maths' GROUP BY Name; ``` `AND` returns records with Course='Bio' **and** 'Maths' (which won't happen at the same time). Example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/e34bd/5). If you are looking for students who appe...
SQL Selecting with 2 entries in 1 table
[ "", "mysql", "sql", "" ]
Let's I have a inner join which results in a table as follows ``` WORKFLOWID Value 1 One 1 Two 2 Three 2 Four ``` But what I want for this is one record to come back ``` ID Value1 Value2 1 One Two 2 Three Four ``` What options do I have in SQL to change an inn...
``` select t1.workflowid as id, min(t1.value) as value1, max(t2.value) as value2 from the_table t1 join the_table t2 on t1.workflowid = t2.workflowid and t1.value <> t2.value group by t1.workflowid ``` This assumes that there are always exactly two rows present in the table. If this is not the ...
Try this: ``` WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY WORKFLOWID ORDER BY WORKFLOWID) FROM TableName) SELECT WORKFLOWID,MAX(Value1) as Value1,MAX(Value2) as Value2 FROM (SELECT WORKFLOWID, CASE WHEN RN=1 THEN Value END as Value1, CASE WHEN RN=2 THEN Value END as Value2 FROM CTE) T GROU...
Get Results from INNER JOIN on same row
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am trying to order by year ascending/descending however I want when the year is 0 to be treated as the newest. For example: ``` 2013 2014 0 ORDER BY YEAR DESC should be 0 2014 2013 ``` After some reading I thought this should work but it doesn't: ``` ORDER BY CASE WHEN YEAR = 0 THEN 9999, YEAR ASC ```
Please try: ``` select * from TableName order by case YEAR when 0 then 9999 else YEAR end desc ``` [SQL Fiddle Demo](http://www.sqlfiddle.com/#!4/7f977e/1)
Try this: ``` SELECT * FROM TableName ORDER BY CASE WHEN YEAR = 0 THEN 0 ELSE 1 END, YEAR ASC ``` Result: ``` YEAR 0 2013 2014 ``` An example in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/3018c/1).
SQL case in order by
[ "", "sql", "sql-order-by", "case", "" ]
I have a simple table - ``` id | date | type | value ------------------------- 1 1/1/14 A 1 2 1/1/14 A 10 3 2/1/14 A 10 4 2/1/14 A 15 5 2/1/14 B 15 6 2/1/14 B 20 ``` I would like to create a new column which calculates the minimum value per day per type. So giving...
First create a field named `min_day` in your table. Then you can use `JOIN` in an `UPDATE` query. Try this: ``` UPDATE TableName T1 JOIN (SELECT date,type,MIN(value) as MinValue FROM TableName GROUP BY type,date) T2 ON T1.type=T2.type AND T1.date=T2.date SET T1.min_day = T2.MinValue ``` An example in [**SQ...
Assuming that your table's name is mytable, try this: ``` SELECT mt.id, mt.date, mt.type, mt.value, mt.min_day, md.min_value FROM mytable mt LEFT JOIN (SELECT date, MIN(value) min_value FROM mytable GROUP BY DATE ) md ON mt.date=md.date; ```
Column calculated by column with grouping
[ "", "mysql", "sql", "" ]
So I have this specific table structure ``` State_Code | ColA | ColB | Year | Month ---------- ------ ---- ------ ----- AK 5 3 2013 4 AK 6 1 2014 8 AK 3 4 2012 9 . . . . . ``` I do not have access to change the table structure. The required query i...
*Community Wiki because it is borrowing heavily from other answers.* The [answer](https://stackoverflow.com/a/23627359/15168) by [Farhad Jabiyev](https://stackoverflow.com/users/1576032/farhad-jabiyev) (now deleted — see [Is it OK to unaccept an accepted answer after weeks](https://meta.stackoverflow.com/questions/256...
``` SELECT STATE_CODE, SUM(COLA) SUM_COLA, SUM(COLB) SUM_COLB FROM TABLE_NAME WHERE to_date(ExtractDay(sysdate) || MONTH || YEAR, 'ddMMyyyy') BETWEEN add_months(sysdate,-12) AND add_months(sysdate,-24) GROUP BY STATE_CODE; ```
Filter records by year and month where year and month are columns in the table
[ "", "sql", "oracle", "" ]
I am trying to populate an autocomplete select field which needs to show all users but add a flag next to those that exist in the club table for the current club. ``` Users user_id | first_name | last_name -------------------------------- 1 | Bob | Smith 2 | Lisa | Someone 3 | Bill ...
You can do this with a `left outer join`: ``` select u.user_id, u.first_name, u.last_name, (c.club_id = 2) as flag from users u left join club c on u.user_id = c.user_id; ``` Note that the `flag` gets a value of `0` (false) or `1` (true). If you want some other values for the flag, then you will need...
Just to be clear about your problem statement, I created the tables and inserted the data - ``` create table users (user_id bigint not null, first_name varchar(100), last_name varchar(100)); create table club (club_id bigint not null, user_id bigint not null); insert into users values (1, 'Bob','Smith'); insert into ...
MySQL output all records from table but add flag if value present in another
[ "", "mysql", "sql", "" ]
I've been given a large list (~50,000) of User IDs in a CSV file, and I have to query our MSSql 2008R2 database to find details of all those users (email address, etc). How can I do this, given that the source of the IDs is not in a table in order to do a join? I have tried pasting the entire list into the query edito...
If you have access to copy the file directly to the SQL server, use bulk copy. Borrowing some excellent explanations from <http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/> ``` BULK INSERT CSVTest FROM 'c:\csvtest.txt' WITH...
This is too long for a comment. Use the Import Wizard and insert them into a "temporary" table. I'm putting "temporary" in quotes, because it doesn't have be in `tempdb`. 50,000 rows is a bit long to insert them one at a time. For small sets of data, I would open the CSV file in Excel and create a separate `insert` s...
How to use IDs from another source (CSV file) in a query?
[ "", "sql", "sql-server", "" ]
I have a table in SQL Server 2012 which has columns for two countries, let's call them CountryA and CountryB. ``` CREATE TABLE dbo.AgreementParticipants ( AgreementParticipantsID INT NOT NULL PRIMARY KEY IDENTITY, CountryA CHAR(3) NOT NULL FOREIGN KEY REFERENCES dbo.Country (CountryCode), CountryB CHAR(3) ...
You can do this with two conditions. The first is a unique index (or constraint): ``` create unique index AgreementParticipants_CountryA_CountryB on AgreementParticipants(CountryA, CountryB) ``` The second is a condition that `CountryA` is less than `CountryB`: ``` check (CountryA < CountryB) ``` If the countries c...
Constraints like: `CHECK ( CountryA < CountryB )` `UNIQUE ( CountryA, CountryB )` is one way to do it Another way is to add computed columns like: `CREATE TABLE t2 (CountryA ..., CountryB ... ,least_country as LEAST( CountryA, CountryB ) ,greatest_country as GREATEST( CountryA, CountryB ) )` and then put a unique ...
Efficient way to CHECK UNIQUE on two columns?
[ "", "sql", "sql-server", "" ]
i have been trying to use this particular query to find the top three most used musical keys in songs and show all the songs made using those musical keys so far the problem is that i'm using in operator with a subquery and it doesn't work!! i have read that instead of in using join is preferable but since i haven't us...
I may be wrong, but it seems all those joins are not necessary. You want to count song records per musical key. So join musical\_keys with musicalkey\_record and count. To get the song names you would have to join with record, too, and use wm\_concat to get the song names in one string. ``` SELECT * FROM ( SELECT mk...
This is a simplification of Barmar's approach, reducing the number of joins: ``` SELECT mk.Key_Name, Song_Title FROM musicalkey_record mr JOIN musical_keys mk ON mk.Key_ID = mr.Key_ID JOIN record r ON r.Record_ID = mr.Record_ID JOIN (SELECT Key_ID FROM musicalkey_record mr GROUP BY...
using in operator with subquery
[ "", "mysql", "sql", "" ]
I am attempting to use a sub query to query our order database and return 3 columns for example: ``` Date Orders Replacements 09-MAY-14 100 5 ... ... ... ``` Each order that is created can be given a reason, which basically means that it is a replacement product...
You could could sum a `case` expression instead of having a another subquery with another `where` clause: ``` SELECT Orders.EntryDate AS "Date", SUM (CASE WHEN Orders.Reason IS NULL THEN 1 ELSE 0 END) AS "Orders", SUM (CASE WHEN Orders.Reason IS NOT NULL THEN 1 ELSE 0 END) AS "Replacements" FROM ...
Why the sub query use a case! ``` SELECT Orders.EntryDate AS "Date", COUNT(Orders.OrderNo) AS "Orders", sum(CASE WHEN Orders.reason is null then 1 else 0 end) as "Replacements" FROM Orders WHERE Orders.Reason IS NULL AND Orders.EntryDate = '09-MAY-2014' AND Orders.CustomerNo = 'A001' GROUP BY Orders.EntryDate ``` The...
How to use a SQL sub query?
[ "", "sql", "" ]
I've been doing quite a bit of MySql lately for uni, and i cant seem to figure out how to get a field from a table twice in the same statement. My database is this: ``` drop database if exists AIRLINE; create database AIRLINE; use AIRLINE; CREATE TABLE AIRCRAFT ( AircraftNo INT(20) NOT NULL, AircraftType VA...
You just need to `JOIN` the table twice with different aliases. Something like: ``` SELECT p1.lastname, p2.lastname, /* other fields */ FROM CHARTER c JOIN PILOT p1 ON p1.PilotCode = c.PilotCode JOIN PILOT p2 on p2.PilotCode = c.CoPilotCode ```
Give alias name as ``` SELECT a.columname1 AS 1, a.columname1 AS 2 FROM tablename a ```
How to select column twice from the same mysql table?
[ "", "mysql", "sql", "" ]
I need help crafting an advanced Postgres query. I am trying to find sentences with two words adjacent to each other, using Postgres directly, not some command language extension. My tables are: ``` TABLE word (spelling text, wordid serial) TABLE sentence (sentenceid serial) TABLE item (sentenceid integer, position sm...
Simpler solution, but only gives results, when there are no gaps in `item.position`s: ``` SELECT DISTINCT sentence.sentenceid FROM sentence JOIN item ON sentence.sentenceid = item.sentenceid JOIN word ON item.wordid = word.wordid JOIN item AS next_item ON sentence.sentenceid = next_item.sentenceid ...
I think this will match your requirements, sorry but i did not remember right now how to write it without using join clauses. Basicly i included a self join to the items and words table to get the next item on sentence for each item. If the query planner does not like much my nested select you can try to left join the ...
Find sentences with two words adjacent to each other in Pg
[ "", "sql", "postgresql", "full-text-search", "" ]
I'm trying to create a SQL query that will not return rows that have the same ID. I would also like to specify a primary row so that, in the event two rows have the same ID, the primary row will be returned. If no primary row is specified I would like to return the first row. Here is an example of the database I would...
Subqueries would be more appropriate than DISTINCT in your case. Try the below. Here is a demonstration of it getting your desired result: <http://sqlfiddle.com/#!2/97fdd3/1/0> By the way, when there is no "primary" for the ID, this will choose the lowest label value for that ID. This is as others have stated more re...
I can see you already got an answer, but you could also use a regular `LEFT JOIN`; ``` SELECT * FROM mytable a LEFT JOIN mytable b ON a.id = b.id AND ( a.label>b.label AND a.primary IS NULL AND b.primary IS NULL OR a.primary IS NULL AND b.primary='Y') WHERE b.id IS NULL ...
Removing duplicates from SQL query
[ "", "mysql", "sql", "" ]
I am trying to figure out this without any success i have tried going through several posts but cannot come to a solution. Situation is like this : ( There are no foreign key constraints )`Table A ID | VAL Table B ID|VAL|TEMP RESULT REQUIRED 1 | A 1| A | 2 A 1 | B 1| A | 2 C 1 | C 1| B | 1 D 1 | D 1| C | 2 E 1 | E 1|...
I think this is what you are looking for: ``` select distinct a.val from a left outer join b on (a.val = b.val) where (b.temp > 1 or b.val is null) ``` You want to do the test on B.TEMP after doing the outer join. In the where clause, you are testing for two things. Firstly, you a checking that the value of TEMP i...
If you want to exclude results from the second table, then don't use a `left outer join`. Just use an `inner join`: ``` SELECT DISTINCT A.VAL, B.TEMP FROM A INNER JOIN B ON A.VAL = B.VAL AND B.TEMP > 1; ``` Or, in your case, you might want `B.TEMP < 2`.
Sql : left join exclude values based on another table
[ "", "sql", "sql-server", "" ]
I have a table named `tuition` I want to retrieve all the students who study `111` and who does not study `333` This is what I can think of: <http://www.sqlfiddle.com/#!2/f6411/3> ``` stud_id | subject_id -------------------- 1 111 1 222 2 222 2 333 3 111 3 ...
Three alternatives: 1. Using `HAVING` clause and `WHERE` clause: ``` SELECT * FROM tution WHERE subject_id = 111 OR subject_id=333 GROUP BY stud_id HAVING COUNT(DISTINCT subject_id)=1 AND subject_id<>333 ``` Result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/df178/1). 2. Using `HAVING` ...
``` select stud_id from tution where stud_id not in (select stud_id from tution t where t.subject_id = 333) and subject_id = 111 ``` [Fiddle](http://www.sqlfiddle.com/#!2/f6411/34)
Retrieve records satisfying a condition and not satisfying another condition
[ "", "mysql", "sql", "" ]
I have the following query: ``` SELECT DISTINCT e.id, folder, subject, in_reply_to, message_id, "references", e.updated_at, ( select count(*) from emails where ( select "references"[1] from emails where me...
Expanding on Paul Guyot's answer you could move the subquery into a derived table, which should perform faster because it fetches the message counts in one scan (plus a join) as opposed to 1 scan per row. ``` SELECT DISTINCT e.id, e.folder, e.subject, in_reply_to, e.message_id, e."referen...
From what I understand of the semantics of your query, you can simplify: ``` select count(*) from emails where ( select "references"[1] from emails where message_id = e.message_id ) = ANY ("references") or message_id = ( select "references"[1] from emails where message_id = e.message...
alternative to SQL count subquery
[ "", "sql", "postgresql", "" ]
I tried this query but I can't get it to work: It says that there's a syntax error near EXISTS. ``` SELECT * FROM Customers WHERE CustomerID EXIST IN (SELECT *, CustomerID FROM Orders); ``` Thanks in advance.
the error is right. You even wrote `Exists` in your question but in the example code you wrote `exist` with no `s` on the end. See [here](http://www.techonthenet.com/sql/exists.php) for the proper syntax You need to correlate the outer query with the sub query in the `exists`. It doesn't matter what columns you select...
Try something like this: ``` SELECT * FROM Customers WHERE CustomerID IN (SELECT CustomerID FROM Orders); ```
EXISTS query don't work. Error in Syntax
[ "", "sql", "exists", "" ]
I have what seems like a very silly question to me. I have a query that looks something like: ``` SELECT id FROM myTable WHERE valueCol BETWEEN :x and :y; ``` This works great when `:x <= :y` BUT, when `:x > :y` it doesn't return the rows I want! For this case I have to manually reverse the variables to get it to wor...
Yes that's easy: ``` SELECT id FROM myTable WHERE valueCol BETWEEN LEAST(:x,:y) and GREATEST(:x,:y); ```
You could do the check yourself and swap the values, or, you could do something like this and let Oracle figure it out: ``` BETWEEN LEAST(:x,:y) AND GREATEST(:x,:y) ```
Between clause - do I have to reorder the parameters?
[ "", "sql", "oracle", "between", "" ]
How can I find maximum value on multiple columns. This is what I have so far. ``` With Temp AS ( SELECT P.ID AS 'Product_ID', P.ProductCode AS 'Product_Code', P.Name AS 'Product_Name', P.SellPrice AS 'SellPrice', P.SellPrice+(P.SellPrice*TVA/100) AS 'PricePerUnit', ...
Are you simply looking for GREATEST? ``` SELECT t.*, GREATEST(T.Discount_Product, T.Discount_Code, T.Discount_Newsletter) as 'maxval' FROM Temp T; ``` However GREATEST Returns NULL when a value is NULL, so you might want to care about this, too. For instance: ``` SELECT t.*, GREATEST ( coalesce(T.D...
You probably want to have each `Select` statement to have a From clause.
Finding max value of multiple columns in Sql
[ "", "sql", "sql-server", "max", "" ]
We have application which collect huge data daily. So write operation is more, Hence my server slow down. So what we have planned use MongoDB to collect data, By using scheduler will import data to SQL. So my problem is how can I import that much heavy data from MongoDB to SQL Any suggestion Please. Like any tool etc...
I don't know any tools, but I'm sure they exist if you google them. If it was me, without prior knowledge, I may export data to a flat file (.csv) and create either a stored procedure or an SSIS package to import the data into SQL. Python may be my choice to automate the exports in chunks overnight where SQL can hand...
We created [MongoSluice](http://mongosluice.com) for this specific reason. Our application interrogates a MongoDB collection and creates a full, deep schema. It then streams data and meta data to any RDBMS system (Oracle, MySQL, Postgres, HP Vertica...). What you end up with is a representation of your NoSQL as SQL. ...
How can import Large data from MongoDB to SQL Server Like Schedulers
[ "", "sql", "sql-server", "mongodb", "" ]
I have two tables like this. ``` A B 1 12 2 13 3 12 4 13 5 15 B C 12 APPLE 13 ORANGE 14 MANGO 15 BANANA ``` I need output as below... ``` count(A) B C 2 12 APPLE 2 13 ORANGE 0 14 MANGO 1 15 BANANA ``` I have written the query using join...
Use a `left join` to get the values of `table2` even if there are no records for them in `table1` ``` select T2.B, T2.C, count(T1.A) from table2 T2 left join table1 T1 on T1.B = T2.B group by T2.B, T2.C ```
Try this: ``` SELECT COUNT(T1.A) as Cnt,T2.B,T2.C FROM Table2 T2 LEFT JOIN Table1 T1 ON T1.B=T2.B GROUP BY T2.B,T2.C ``` Result: ``` CNT B C 2 12 APPLE 1 15 BANANA 0 14 MANGO 2 13 ORANGE ``` See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/b1846/8).
Query to count the entries
[ "", "sql", "sql-server", "join", "" ]
I want to write a SQL to count the sales of my last six months, just like the code below. ``` SELECT MONTH (pc.createTime) AS MONTH, SUM (partsModelSum) AS totalSum FROM partscontractlinkmodel AS pl RIGHT JOIN partscontract pc ON pl.partsContractID = pc.partsContractID AND pc.companyID = 8 AND pc.createTim...
If you have some data every month, you can use conditional aggregation: ``` SELECT MONTH (pc.createTime) AS MONTH, SUM(CASE WHEN pl.partsModelID = 21028 THEN partsModelSum END) AS totalSum FROM partscontract pc LEFT JOIN partscontractlinkmodel pl ON pl.partsContractID = pc.partsContractID AND ...
Get a list of month from a table or sub query. Left join the months table/query and partscontract via month(createTime) and month from table/sub-query. Left join partscontract and partscontractlinkmodel like what you did. See below for sample: ;WITH CTE\_Month as ( SELECT 1 as MonthN UNION SELECT 2 as MonthN...
SqlServer:Select and group by Month
[ "", "sql", "" ]
Is there a way to change same column name with same column type in multiple tables in one query? something like this: ``` ALTER TABLE (SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'data_by_%_month_%' AND TABLE_SCHEMA='db_name') MODIFY column1 INT(20) NOT NULL; ```
No, not with `ALTER TABLE` alone. It is expected for the `ALTER TABLE` statement to receive one table. See [the docs](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html). It doesn't expect an expression there. You can of course write a program that creates multiple `ALTER TABLE` statements based on your `SELECT`...
You can do this using a stored procedure. **Example**: ***Test table structures***: ``` drop table if exists so.tbl_so_q23631366_1; drop table if exists so.tbl_so_q23631366_2; create table so.tbl_so_q23631366_1( column1 varchar(10) ); create table so.tbl_so_q23631366_2( column1 text ); ``` ***Stored Procedure***: ...
ALTER columns from multiple tables in same query
[ "", "mysql", "sql", "" ]
I have a table with sample data as below: ``` Name | Code Ken Ken_A Ken Ken_B Tim Tim_1 Tim Tim_3 Sam Sam_Tens Sam Sam_Tenson ``` I want to do an update query that replaces the second instance of the Code ordered by Name with the first instance, so I would end up with the below: ``` N...
Assuming that you have a column that specifies the ordering, you can use an updatable CTE with a join: ``` with toupdate as ( select t.*, row_number() over (partition by name order by id) as seqnum from t ) update toupdate set code = tu2.code from toupdate join toupdate tu2 o...
One option: ``` update mytable set code = (select min(code) from mytable min_name where min_name.name = mytable.name); ```
Update row with Top 1 value per group
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I am trying to create an audit trail for actions that are performed within a web application, SQL server agent jobs and manually run queries to the database. I am trying to use triggers to catch updates, inserts and deletes on certain tables. In the whole this process is working. Example, user performs update in web a...
**WORKING CODE IS IN FIRST EDIT** - (*anothershrubery*) Use the `app_name()` function <http://msdn.microsoft.com/en-us/library/ms189770.aspx> in your audit trigger to get the name of the app running the query. For SQL Agent jobs, app\_name includes the job step id in the app name (if a **T-SQL** step). We do this in ...
You could try using CONTEXT\_INFO Try adding a T-SQL step with `SET CONTEXT_INFO 'A Job'` in to your job Then try reading that in your trigger using `sys.dm_exec_sessions` I'm curious to see if it works - please post your findings. [http://msdn.microsoft.com/en-us/library/ms187768(v=sql.105).aspx](http://msdn.micro...
Get job that ran SQL query on UPDATE trigger
[ "", "sql", "sql-server", "triggers", "ssis", "sql-server-job", "" ]
I think the best way to describe what I am looking for is to show a table of data and what I want returned from my Query. This is a simple data table in SQL Server: ``` JobNumber TimeOfWeigh 100 01/01/2014 08:00 100 01/01/2014 09:00 100 01/01/2014 10:00 200 01/01/2014 12:00 200 01/01...
Here's my attempt at this, using row\_number() with a partition. I've broken it into steps to hopefully make it easy to follow. If your table already has a column with integer identifiers in it, then you can omit the first CTE. Even after that, you might be able to simplify this further, but it does appear to work. (E...
you have to use self joins to create pseudo tables that contain the first, and last row in each set. ``` Select F.JobNumber, f.TimeOfWeigh FirstWeigh, l.TimeOfWeigh LastWeigh From table f -- for first record join table l -- for last record on l.JobNumber = f.JobNumber And Not exists ...
Sql query to return a result set for a Timeline
[ "", "sql", "sql-server", "group-by", "" ]
Another Question for Today :) Wrote a query that works perfectly - except I want it to show NULL/0 values as 0 - and - that isn't happening. I tried approaching this two ways: First I used `isnull()` ``` Select isnull(Count(*),0) as Total , z.zname From STable s , SLTable sl , ZTable z , ...
Well, it's unclear what you're actually trying to find. However, a big part of your problem is that you're using old-school, pre-ISO/ANSI `join` syntax. If you refactor your join to use modern `join` syntax, you'll get a query that looks somethinn (a lot, actually) like this: ``` select zName = z.zname , Tota...
Actually just to semi answer my own question - just realized that where - see.segID-3 - so it'll only turn out results with segID = 3 - so it cannot NOT have 3 - right? But Im specifically looking for segIDs as 3 - just, if there is nothing there then display 0
Null/0 Answers Not Appearing
[ "", "sql", "sql-server", "" ]
I have a table it's called solr. using this below Scripti'm updating this into solr table.but here my doubt is instead of this i need to use If...Else condition. I'm not getting any idea about this one. Kindly help me with on this. ``` UPDATE solr SET Stock= CASE WHEN SUD.D_price='ABC' OR SUD.D_price ='CDE...
You don't explain exactly what you want, but I surmise that you need an `else` clause. If you want to set the value to `'N'`, then use: ``` UPDATE solr SET Stock = (case when SUD.D_price = 'ABC' OR SUD.D_price = 'CDE' AND WIS.StockID > 0 THEN 'Y' WHEN SUD.Display_price=...
I don't really understand your question, but I do know this... whenever you mix AND with OR in a condition, you should use parenthesis to control the order of operations. ``` CASE WHEN (SUD.D_price='ABC' OR SUD.D_price ='CDE') AND WIS.StockID >0 THEN 'Y' WHEN (SUD.Display_price='XYZ' OR SUD.Di...
Instead of Case when I need IF..Else
[ "", "sql", "sql-server-2008", "" ]
These are my tables ``` create table employees (emp_no integer not null, emp_name char(25), age integer, department_id integer not null, salary integer, CONSTRAINT employees_pk PRIMARY KEY(emp_no), CONSTRAINT fk_Department FOREIGN KEY(department_id) REFERENCES Department...
First, to get the workers' name and their department, you should be linking table `employees` and `department` using `department_id`, not name.. ``` select emp_name,Department.dep_name from employees inner JOIN Department on employees.department_id = Department.Department_id ``` and for the employees whose working ho...
To union two `SELECT` results they have to have * same selected column count * same type of What you actually want to use is `INNER JOIN` : ``` SELECT emp_name,sum(salary) FROM employees INNER JOIN works ON employees.emp_no = works.emp_no WHERE works.hurs >= 20 ```
How can I select two columns from two tables?
[ "", "sql", "" ]
I am learning SQL currently and I have a question. I have two tables called "vehicul" and proprietate. The first table (vehicul) looks like this: ``` id nr_vehicul marca id_marca tip culoare capacitate_cilindrica 1 DJ-01-AAA Mercedes 1 CLK 350 negru 3500 2 DJ-01-BBB Me...
You need to join two tables and GROUP them based on `marca` field and sum `pret` ``` select marca, sum(pret) from table1 as t1, table2 as t2 where t1.id=t2.id group by marca ``` Here I'm assuming that `id` field is joining two tables, (but as I can see from your sampel data it isn't relating to each-other actually) ...
use this requeste ``` select marca, sum(pret) from vehicul as Ve, proprietate as Pr where Ve.nr_vehicul=PR.nr_vehicul group by marca ``` or ``` select marca, sum(pret) from vehicul as Ve where Ve.id in(select nr_vehicul from proprietate) group by marca ```
MySQL, two tables displaying information from both tables
[ "", "mysql", "sql", "" ]
My mind has gone blank...I am missing something obvious trying to write a small script: I have one table with various ID's: ``` TBL_USETHISID nextid int ``` I have another table with references: ``` TBL_REFS ref varchar(6) thisdate datetime nextid int ``` I want to take the ID from TBL\_USETHISID and then update T...
I would strongly advise you to use SEQUENCEs. That is idiomatic Ingres approach (actually, sequences are SQL:2003 standard, if I remember well, so every good RDBMS which supports SQL should support them). Unfortunately Actian moved the documentation to a new system which makes it very difficult to create a direct link...
The most simplest way is through `LOOPS` although not the most efficient way. Also not sure about the syntax in `ingres` as I have never worked on it. It is also possible through a CTE (again not sure if CTEs work in ingres). Will try and give a solution for that as well. Till then Check the below code ``` --simulat...
SQL Update, incrementing value by 1
[ "", "sql", "ingres", "" ]
I have a table in database and it has a column named 'Modified date'. Whenever i edit some data from the form in asp.net web form i should be able to fill the database table column 'Modified date' with the current date automatically. Is there any way out for it.I am stuck with it.
set > getdate() something like this: ``` ALTER TABLE [TableName] ADD DEFAULT (getdate()) FOR [ColumnName] Go ``` as default in your table will give you current insert date and time for Sql server There are two possible ways : > 1. From your code behind > 2. From Select Query from Database example to select only...
You can do it either as Krunal says or hardcode in your insert query in `C#` (or `VB)`: ``` Insert into..... values ( ...., SELECT convert(varchar, getdate(), 106),...,) ``` this inserts into format: `dd/mmm/yy`
How to get current date in sql
[ "", "asp.net", "sql", "" ]
I used to know how to do this, but I can’t seem to remember or find the answer. I want to return data from a table and then just add an extra column with a set value (which does not need to be saved). So, it is not an `UPDATE` issue. Just a `SELECT` with that extra column. Original table: ``` | id | col1 | c...
It's as simple as: ``` SELECT id, col1, col2, '12:48' AS tempCol ```
use this ``` select id,col1,col2, '12.48' as tempcol ```
MySQL SELECT with an extra column containing a string
[ "", "mysql", "sql", "string", "select", "" ]
I have a column of USD and EUR currencies and would like to multiply the values to the corresponding exchange in chilean pesos. So far I know how to extract the contracts that are in USDand the ones that are in EUR but I don't kow how to multiply each value by its own exchange rate. I think it could be something like: ...
You can filter your `contracts.value` by `contracts.currency` using `CASE` statement : ``` SELECT contracts.currency , CASE WHEN contracts.currency = 'USD' THEN contracts.value*500 WHEN contracts.currency = 'EUR' THEN contracts.value*750 ELSE contracts.value END FROM contrac...
You can do that in the select clause: ``` SELECT IF(contracts.currency='USD', contracts.value*500, contracts.value*750) as amount FROM contracts ``` Documentation: <http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html>
Multiplying column if statement is true
[ "", "mysql", "sql", "if-statement", "" ]
When I do a SELECT statement with an AS definement and i want to filter on that it give the folowing error: #1054 - Unknown column 'TimeInSeconds' in 'where clause' Code: ``` Select Id, time/10000000 as TimeInSeconds FROM Results WHERE TimeInSeconds > 5 AND TimeInSeconds < 36000 ``` I understand the error that TimeI...
You can also use `HAVING` clause to filter out the results of custom aliases ``` Select Id, `time`/10000000 as TimeInSeconds FROM Results HAVING TimeInSeconds > 5 AND TimeInSeconds < 36000 ``` Or repeat the expression using `WHERE` clause ``` Select Id, `time`/10000000 as TimeInSeconds FROM Results WHERE (`time`...
One option is to put the results in a `subquery`: ``` Select Id, timeinseconds From (Select Id, time/10000000 as TimeInSeconds FROM Results) t Where TimeInSeconds > 5 AND TimeInSeconds < 36000 ```
MYSQL: Doing a where on a own defined parameter in SELECT
[ "", "mysql", "sql", "select", "parameter-passing", "where-clause", "" ]
I have a large (3 million rows) table of transactional data, which can be simplified thus: ``` ID File DOB -------------------------- 1 File1 01/01/1900 2 File1 03/10/1978 3 File1 03/10/1978 4 File2 15/07/1997 5 File2 01/01/1900 6 File2 15/07/1997 ``` In some ca...
Supposing your table is called "Files", then this will work: ``` UPDATE f1 SET f1.DOB=f2.MaxDOB FROM files f1 JOIN (SELECT File, MAX(DOB) AS MaxDOB FROM files GROUP BY File) f2 ON f2.File=f1.File; ``` As far as performance is concerned, it probably won't get much more efficient than this, but you do need to i...
I dont know about most efficient way, but i can think of one solution...create a temp table with following query. Though i am not sure about exact keywords of sqlserver 2008, but this might work or you may need to change key word like to\_date and its format. create table new\_table as ( select file,min(DOB) as defaul...
Updating one column with the value from another, based on another common column
[ "", "sql", "sql-server-2008", "" ]
I have record of students, every day they undertakes a driving test =, I would like to calculate total number of students who have passed and failed their driving test for today's date e.g ``` StudentName Status date pass fail test1 something 2014-05-14 1 0 test2 something...
You should use `SUM` instead of `COUNT`, and add a `GROUP BY` in the end. ``` SELECT StudentName, MAX(date) as date, SUM(pass) As TotalPassed, SUM(fail) As Totalfailed, SUM(pass) + SUM(fail) as TotalTriesVersion1, COUNT(*) as TotalTriesVersion2 FROM Table1 GROUP BY StudentName ``` And [here](http://sqlfiddle.com/#!...
You need to use the GROUP BY Clause like this: ``` SELECT COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS TotalPassed, COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS Totalfailed FROM DatabaseName WHERE date>='2014-05-14' GROUP BY StudentName ```
Count total number of records
[ "", "sql", "" ]
I am executing the below query in sql-server-2008-R2 which gives me output as I wanted(i.e, number of rows) but, I want to store the result in form of a multi-columned row(s) in a variable. ``` declare @rCount int declare @kuri nvarchar(max) declare @IDs nvarchar(max) select @rCount=10 set @kuri='select top '+cast(@...
``` DECLARE @T1 TABLE ( FLD9 bigint , FLD295 nVARCHAR(max) ) insert into @T1(,FLD295,FLD9) select top(@rCount) FLD295,FLD9 from tableName (nolock) ORDER BY NEWID() select * from @T1 select @IDs=CAST(isnull(@IDs ,'')as varchar)+CAST(COALESCE(fld9,',')as varchar) from @T1 ```
I think you're missing the face that you can do ``` declare @i int=3 select top(@i) .... – ``` 2008 does support dynamic top I hope you know that result should be single. , otherwise , it can't be possible (unless you're doing `insert into...` if you're asking about how to concatenate ( cte is jsut table , ignore ...
need to assign values from sql query in single instance
[ "", "sql", "sql-server", "" ]
Hello so I have two tables and I want to copy one column from table1 to table2. ``` SET @m=0; SELECT column INTO @m FROM table1; UPDATE table2 SET column = @m; ``` Basically I tried to insert into the column in table2 the values from column in table1. What am I doing wrong? LE: I tried the INSERT INTO and it worked ...
Syntax is Correct but when you are copying you should take care about types ... **types** should be compatible to each other ``` INSERT INTO table (column) SELECT a_column FROM a_table --- optional (multiple) JOINs --- and WHERE --- and GROUP...
Try this syntax: `INSERT INTO table2 (column) SELECT column FROM table1` Don't need VALUES and parenthesis.
MySQL copying a column from another table
[ "", "mysql", "sql", "" ]
I want to create a group of users only if the same group does not exist already in the database. I have a GroupUser table with three columns: a primary key, a GroupId, and a UserId. A group of users is described as several lines in this table sharing a same GroupId. Given a list of UserId, I would like to find a match...
Let say your UserId list is stored in a table called 'MyUserIDList', the following query will efficiently return the list of GroupId containing exactly your user list. (SQL Server Syntax) ``` Select GroupId From ( Select GroupId , count(*) as GroupMemberCount , Sum(case when MyUserIDList.UserID is nul...
There are couple of ways of doing this. This answer is for sql server only (as you have not mentioned it in your tags) 1. Pass the list of userids in comma seperated to a stored procedure and in the SP create a dynamic query with this and use the `EXEC` command to execute the query. [This](http://www.mssqltips.com/sql...
Check if a list of items already exists in a SQL database
[ "", "sql", "many-to-many", "" ]
So i'm just wondering how I would go about getting the a merged list of two tables, one with all the required rows, and the second with extra data to be associated with the first. ![enter image description here](https://i.stack.imgur.com/CalAJ.png) So with table 1 and 2 I want to get 3, would this be able to be done a...
So if the "empty" value in column coming from table2 can just be NULL, you can do a LEFT JOIN ``` select t1.col1, --this is A, B, C t1.col2, t1.col3, t2.col4 -- this is the fourth column from Table1 t1 left join Table2 t2 on t1.Col1 = t2.Col1 ``` see [SqlFiddle](http://sqlfiddle.com/#!6/98ebf/1) If you wanna be s...
Use Exists ``` SELECT T1.Column1, T1.Column2, T2.Column3 FROM T1, T2 WHERE T1.Column1 IN (SELECT Column1 FROM T1); ```
Query to merge results with same values + extra column
[ "", "sql", "sql-server", "" ]
I am trying to add two columns to the query below: * 1st column would be the % of free space = `freespace/capacity` * 2nd column would be the amount of used space = `capacity-freespace` This is my query ``` SELECT SystemName, Caption, Label, Capacity, FreeSpace FROM CCS_Win32_Volume ORDER BY SystemName, ...
Calculated fields will not add much overhead when you add them right into the query, since the data you're calculating on has already been read from disk. ``` SELECT SystemName, Caption, Label, Capacity, FreeSpace, 100*freespace/capacity [% of free space], capacity-freespace [used space] FROM CCS_Win32_V...
I think the question was the approach, not the actual T-SQL... Unless your query is used elsewhere and changing it might break something, then I would update your existing query. If it is used elsewhere and it's going to be a lot of work to update all the related processes/queries then I would create a separate query ...
When to add calculated custom columns to a query - right away or by using a join
[ "", "sql", "sql-server", "" ]
I have a database table that stores data to show on a report. Each time records are inserted into the database, another row is added except the ReportNumber row is incremented. I've been searching and can't seem to find anyone else who may have asked this. I need the stored procedure to get the latest report info (high...
Does this do it: ``` select * from Table where ReportNumber in (select max(ReportNumber) from Table) ```
Why not use `order by` like ``` select * from report_table order by ReportNumber desc ``` (OR) ``` select * from report_table where ReportNumber = (select max(ReportNumber) from report_table) ```
Filter SQL results by highest number in column
[ "", "sql", "sql-server", "" ]
``` DECLARE @DATA TABLE ( Id int, Value int ) INSERT INTO @DATA VALUES (1, 10) INSERT INTO @DATA VALUES (2, 20) INSERT INTO @DATA VALUES (3, 30) INSERT INTO @DATA VALUES (4, 40) DECLARE @TO_FILL TABLE ( Id int, Value int ) INSERT INTO @TO_FILL VALUES (1, 100) INSERT INTO @TO_FILL VALUES (3, 300) DECLA...
From the relevant [TechNet page](http://technet.microsoft.com/en-us/library/ms177523.aspx): > If the object being updated is the same as the object in the FROM clause and there is only one reference to the object in the FROM clause, an object alias may or may not be specified. If the object being updated appears more ...
Both queries are essentially doing the same thing, difference is in the syntax. *1st Query* Its is using old join syntax where join condition is mentioned in where clause something like this... ``` SELECT * FROM table1 , Table2 WHERE Table1.ID = Table2.ID ``` *2nd Query* your second block uses newer ansi join synt...
What is the difference between UPDATE FROM WHERE and UPDATE FROM INNER JOIN?
[ "", "sql", "sql-server", "" ]
I need to insert into a mysql table. However, It should insert only if a conditions is satisfied. So I want something like this to happen ``` INSERT INTO table_name(name,qty,code) VALUES(SELECT i.name,i.qty,i.code FROM table2 i); ``` For a condition like this ``` IF i.code == 'abcd' && i.name == 'def' THEN perform...
@strawberry answered this question in the comments. It's a simple answer but somehow really nice. Here is the answer ``` INSERT INTO table_name(name,qty,code) VALUES ( SELECT i.name,i.qty,i.code FROM table2 i WHERE (i.code = 'abcd' AND i.name = 'def') OR i.code != 'abcd' ) ```
first insert all the rows from table2 for code = 'abcd' and name = 'def' ``` INSERT INTO table_name SELECT i.name,i.qty,i.code FROM table2 i where i.code = 'abcd' and i.name = 'def' ``` Now insert conditionally other rows
Selectively inserting into a mysql table
[ "", "mysql", "sql", "" ]
I want to limit the count to 5 using `COUNT(*)` and `group by` but it returns all the rows.Consider I have a table names tbhits ``` tbhits id | uname ------------------------ 101 | john 101 | james 101 | henry 101 | paul 101 | jacob ...
`LIMIT` is intended to limit the number of rows you'll get from your query. I suggest you use the `COUNT` function as follows : ``` SELECT id, CASE WHEN COUNT(*) < 6 then COUNT(*) ELSE '5+' END as 'hits' FROM tbhits GROUP BY id ``` More details about selecting the minimum of two numbers [here](https://stackoverflow...
LIMIT on GROUP BY clause won't actually limit the counts, it will limit the rows being outputed. Try using `if` statement to compare count result, ``` SELECT id,if(COUNT(*)>5,'5+',COUNT(*)) as 'hits' FROM tbhits GROUP BY id ``` O/p: ``` id | hits -------------------- 101 | 5+ 102 | 1...
Limit the count using GROUP BY
[ "", "mysql", "sql", "" ]
I am tryng to compare race codes in two different tables joining on a number id in each table, one table is in fixed positional format. I am getting an error on the '.' between T2.DSNumber on line 5 ``` select T1.SNumber, T1.Racecode1, T1.Race1 , SUBSTRING(rec,1,6) as T2.DSNumber, SUBSTRING(rec...
If i am not wrong, you are using SQL Server. In your query the below part is wrong ``` SUBSTRING(rec,1,6) as T2.DSNumber, ``` should be ``` SUBSTRING(rec,1,6) as DSNumber, SUBSTRING(rec,175,2) as DSRaceCode1, SUBSTRING(rec,251,12) as DSRaceText1 ```
Others apparently are close with different answers, but your issue is that your second table (T2) does not actually have columns for "DSNumber" and "DSRaceCode1" as you are pulling those from the substring components. Therefore, those substring references need to be applied to your join (or WHERE). I have formatted to ...
inner join aliases not working
[ "", "sql", "t-sql", "" ]
I have written a procedure which takes several input parameters. I need to validate the input. If they are valid values they have to be present in the database table - attribute\_values. The problem is attribute\_values table contains million records. I am now supposed to improve the performance of select query. For va...
Rather than doing a `SELECT COUNT(*)...` followed by a `SELECT ID...`, both against the same table, I suggest you rework this logic as follows: ``` BEGIN SELECT ATTRIBUTE_VALUE_ID INTO MYVAR1 FROM ATTRIBUTE_VALUES A WHERE A.ATTRIBUTE_VALUE = INPUT_PARAMETER1 AND ROWNUM = 1; COUNT_VAR := 1;...
For these queries, I would suggest an index: ``` create index attribute_values_attribute_value on attribute_values(attribute_value); ``` This should suffice for your purposes.
how to improve performance of select
[ "", "sql", "oracle", "stored-procedures", "plsql", "" ]
I found this character while reading some blog of pl sql `<< some text >>` . I found this character from following blog <http://www.oracle-base.com/articles/8i/collections-8i.php>
It's often used to label loops, cursors, etc. You can use that label in [`goto`](http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/goto_statement.htm) statements. Else, it is just 'comment'. Sample from Oracle: ``` DECLARE p VARCHAR2(30); n PLS_INTEGER := 37; -- test any integer > 2 for prime B...
As others have said, `<<some_text>>` is a label named "some\_text". Labels aren't often used in PL/SQL but can be helpful in a variety of contexts. As an example, let's say you have several nested loops, execution has reached the very inner-most level, and the code needs to exit from all the nested loops and continue ...
What is << some text >> in oracle
[ "", "sql", "oracle", "plsql", "" ]
I'm trying to get the quotient of two columns inside the select statement. Here's what I have tried. ``` Select ( select sum(x.amount) amount from this_table x where x.acct_no = '52' ) / ( select sum(x.amount) amount from this_table x where x.acct_no = '53' ) a...
This should do as you want: ``` select sum(case when acct_no = '52' then amount else 0 end) / sum(case when acct_no = '53' then amount else 0 end) as amount from this_table where acct_no in ('52','53') ``` To make the amount column show zero if the divisor is zero (rather than return an error), you can us...
FWIW I just had a play in SQLFiddle <http://sqlfiddle.com/#!1/d41d8/1606> , and if you're only after a single row single column result, PostgreSQL seems to allow : ``` WITH Amounts52 as (select 23 as sum52), Amounts53 as (select 4356 as sum53) SELECT Amounts52.sum52::float / Amounts53.sum53 AS Result FROM...
How do you divide in the select statement?
[ "", "sql", "postgresql", "" ]
I have three tables towns , patientsHome,patientsRecords **towns** > Id > 1 > 2 > 3 **patientsHome** > Id | serial\_number > 1 | 11 > 2 | 12 > 2 | 13 **patientsRecords** > status | serial\_number > stable | 11 > expire | 12 > expire | 13 I want to count stable and expire patients from patien...
Try like this : ``` select t.id,case when tt.StableRecords is null then 0 else tt.StableRecords end as StableRecords,case when tt.expiredRecords is null then 0 else tt.expiredRecords end as expiredRecords from towns t left join (select ph.id, count(case when pr.status='stable' then 1 end) as StableRecords, count(Case ...
Assuming `patientsHome.ID` is in fact a foreign key to `towns.ID`, you can join the 3 tables, filter as appropriate, group by Town, and count the rows: ``` SELECT t.Id, COUNT(*) as patientCount FROM towns t INNER JOIN patientsHome ph on t.Id = ph.Id INNER JOIN patientsRecords pr on ph.serialNumber = pr.ser...
Linking three tables SQL
[ "", "sql", "postgresql", "" ]
We're accessing our database with our server (another computer). Before, I'm able to connect with it but it suddenly stop and now I cant connect and I encounter this error which is error 26 Locating Server. Others can connect with our server. I don't know what I've done or what I've change with my machine that causes ...
Try **flushing your DNS**. Open a DOS window to do this. 1. Click Start Button 2. Type CMD and press enter 3. Type this into the black window that appears: **ipconfig /flushdns** and press enter you should see: Windows IP Configuration Successfully flushed the DNS Resolver Cache. See if this does not correct...
I tried using the (IP address of the server)\SQLEXPRESS and it do work. Yet I still dont know why It cant access the instance name of the server.
How to resolve Error 26 in SQL Server?
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
Currently have sql returning a result set as below ``` WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXCEPTIONREASON 1001 UNIQUE ADDRESS1 (null) 1001 UNIQUE ADDRESS2 Some Value ``` What I am looking for is a result like this ``` WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXC...
Try this: ``` ;WITH CTE AS ( SELECT ws.id as WorkflowStepId, ws.workflow_id as WorkflowId, sg.unmatchValue as UnmatchedValue, geo_address as MatchedAddress, ws.exception_Value as ExceptionReason, ROW_NUMBER() OVER(PARTITION BY ws.workflow_id ORDER BY w...
Try this: ``` SELECT ws.workflow_id as WorkflowId, sg.unmatchValue as UnmatchedValue, MAX(CASE WHEN ws.id = 1 THEN geo_address END) as MatchedAddress1, MAX(CASE WHEN ws.id = 2 THEN geo_address END) as MatchedAddress2, MAX(CASE WHEN ws.id = 1 THEN ws.exception_Value END) as ExceptionReason1, MAX(CASE WH...
Getting Results from inner join differences on same row
[ "", "sql", "sql-server-2012", "" ]
It is acceptable in Oracle databases the command ``` "SELECT UNIQUE * FROM table"? ``` Or do I have to select the column name for that command to work?
Yes, this syntax is acceptable. See this [SQLFiddle example](http://sqlfiddle.com/#!4/ce01b/2).
you can use the following query ``` select distinct * from table ```
Oracle SELECT UNIQUE * FROM TABLE
[ "", "sql", "oracle", "" ]
I have two tables as below: logs ``` id | user | log_id --------------------- 1 | user1 | abc 2 | user2 | def 3 | user1 | xyz ... ``` users ``` id | user | code --------------- 1 | user1 | 1234 2 | user2 | 9876 3 | user1 | 5678 ... ``` I want to add log\_id to `users` and update it with log\_id'...
I figured out the solution. I added 2 columns `rank` and `prev_user` in both tables, and incremented the value for `rank` from 1 for the first record for user\_x to n for the nth record for user\_x, as below: ``` ALTER TABLE users ADD COLUMN rank tinyInt(1); ALTER TABLE users ADD COLUMN prevuser varchar(50); SET @prev...
If the id fields are always matched then the reply by Ronak Shah would be my choice. If the ids do not match then possibly something like this:- Firstly:- ``` ALTER TABLE table1 ADD COLUMN code VARCHAR(25); ``` Then an update like this:- ``` UPDATE table2 INNER JOIN ( SELECT id, user, code, @rank2:=IF(@prev_us...
MySQL - updating table based on chronological order
[ "", "mysql", "sql", "join", "" ]
i am trying to create new column from existing column(table) in a new table. this is my old table ``` projectnum allw budjet 648PE2075 152.00 230.00 648PE2075A 33.33 00.00 333AD0221B 125.11 1256.00 123CF0023 125.22 215.33 ``` I need to create a new table that have a ...
I suggest using `select ... into ... from ...` to create a new table from existing data in one step. For your string operations `substring()` seems appropriate. Please try the following query: ``` select projectnum, allw, budjet, substring(projectnum, 1, 3) + '-' + substring(projectnum,...
``` SELECT projectnum, CASE LEN(projectnum) WHEN 9 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3) WHEN 10 THEN LEFT(projectnum,3) + '-' + SUBSTRING(projectnum,6,3) + '-' + RIGHT(projectnum,1) END AS Project_code, allw, budjet INTO MyNewTable FROM MyOldTable ``` Just obvi...
creating new column from existing column using t-sql
[ "", "sql", "sql-server", "t-sql", "" ]
I need some help with a SQL view please.. I am creating a view to be used for reporting via Crysyal.. One of the fields that I need is a string field that contains three values separated by a character '~' I basically need this splitting out within my Select query within view to three separate fields.. An example is ...
you mean split the string at the delimiter ? ``` declare @a as varchar(100) set @a='Trading~Concession~Telemetry - OCPD / Low Sales' select substring(@a,0,patindex('%~%',@a)) as trading_status,reverse(substring(reverse(@a),0,PATINDEX('%~%',(reverse(@a))))) as problem1, substring(@a,patindex('%~%',@a)+1,10) as problem...
Try this: ``` select cast(c1 as nvarchar) + '~' + cast(c2 as nvarchar) + '~' + cast(c3 as nvarchar) from table ```
SQL breaking a string between characters in a view
[ "", "sql", "select", "" ]
I have a simple table. ``` Date | Revenue 5/1 12 5/2 25 5/3 93 . . 11/15 47 ``` I am trying to write a query that returns two columns. The first column is Date, day-by-day, like the original table. The second column is 30-Day-Revenue, which is the sum of the "Revenue" column in the original table for...
I have an alternative solution (assumes your table is called `revenue_table`): ``` SELECT a.Date, SUM(b.Revenue) FROM revenue_table a, revenue_table b WHERE b.Date <= a.Date AND b.Date > a.Date - 30 GROUP BY a.Date; ```
``` SELECT table1.Date, table1.Revenue, Past30DayRevenue = SUM(table2.Revenue) FROM insert_your_table_name_here table1 JOIN insert_your_table_name_here table2 ON DATEDIFF(day, table2.Date, table1.Date) BETWEEN 0 AND 29 GROUP BY table1.Date, table1.Revenue ORDER BY table1.Date; ```
Sum of revenue everyday, for last 30 days on each day
[ "", "sql", "" ]
I need to filter based on a timestamp and would like to get everything within a certain day. The timestamps are like this: `02/06/2014 7:45:59 AM` or translated `2014-02-06 07:45:59` ``` select * from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM where service_type_id = 134469888 and valid_from_tsp not like '2014-02-06 %' ``` ...
You should be able to just cast to a date and compare to your desired date, something like; ``` SELECT * FROM P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM WHERE service_type_id = 134469888 AND CAST(valid_from_tsp AS DATE) = '2014-02-06' ``` EDIT: If you have a large table, this query will not use indexes well. If that is i...
The following is a better way to express the date condition: ``` select * from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM where service_type_id = 134469888 and valid_from_tsp >= DATE '2014-02-06' and valid_from_tsp < DATE '2014-02-07'; ``` or: ``` select * from P_FAR_SBXD.T_CLAIM_SERVICE_TYP_DIM where servic...
sql NOT LIKE syntax
[ "", "sql", "teradata", "" ]
I have a `Emptbl` in which I have `EmpType` Column. In EmpType I have following data for example : ``` E0123 M0123 E1245 E4578 M1245 E0478 M4789 E4762 ``` Now I want to get only those emp data which have same `EmpType` for example below data: ``` E0123 M0123 E1245 M1245 ``` And want to show this data as group by ...
``` Select A.* From EmpTbl A Inner Join EmpTbl B On SubString(A.EmpType, 2, 4) = SubString(B.EmpType, 2, 4) And SubString(A.EmpType, 1, 1) <> SubString(B.EmpType , 1, 1) ```
Try this: ``` select substring(emptype, 2, len(emptype)) from emptbl group by substring(emptype, 2, len(emptype)) having count(*) > 1 ``` The hard-coded 2 is based on your sample data. If instead you had an arbitrary number of letters before the numeric part, e.g. 'ABCDEFG0123', you could use `patindex` to get the st...
Get data from table using group by
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I've got a table `PERSON_PROPERTIES` that resembles the following : ``` | ID | KEY | VALUE | PERSON_ID | | 1 | fname | robert | 1 | | 2 | lname | redford | 1 | | 3 | fname | robert | 2 | | 4 | lname | de niro ...
``` SELECT PERSON_ID FROM PERSON_PROPERTIES group by PERSON_ID having sum(case when key = 'fname' and value = 'robert' then 1 else 0 end) > 0 and sum(case when key = 'lname' and value = 'redford' then 1 else 0 end) > 0 ``` Groupy by the person and select only those having both values.
Another approach would be with subselect (caution, it's MS SQL 2012) ``` SELECT PERSON_ID FROM PERSON_PROPERTIES WHERE [Key] = 'fname' AND value = 'robert' AND PERSON_ID in (SELECT PERSON_ID FROM PERSON_PROPERTIES WHERE [Key] = 'lname' AND value = 'redford') ``` [Fiddle Demo](http://sqlfiddle.com/#!6/74e0d/5)
SQL SELECT multiple keys/values
[ "", "sql", "jpql", "psql", "" ]
I have a simple table that has two columns `uid` and `isEnded`. A `uid` can occur multiple times in this table and can have the value `0` or `1`. The value `0` can only occur one time for each unique `uid`. For example: --- ``` | uid | isEnded | ------------------ | 1 | 1 | | 1 | 1 | | 1 | 0 ...
Well, if all of the values should be `1` for the `uid`s you want to select, that also means that the minimum value will also be `1`: ``` SELECT uid FROM table GROUP BY uid HAVING MIN(isEnded) = 1 ```
Try the below query: ``` SELECT DISTINCT uid FROM #Tab WHERE UID NOT IN (SELECT uid FROM #tab WHERE isended = 0) ```
Get all records that are ended
[ "", "sql", "sql-server", "" ]
I have two tables: ``` tickets ticket_updates ``` and i am trying to run a query where it shows data from the tickets table and `order by` the latest `datetime` in the `ticket_updates` table ``` SELECT * from tickets where status = 'Completed' order by ??? DESC LIMIT 0,50 ``` `ticketnumber` in the `tickets` table m...
``` SELECT t.* FROM tickets AS t JOIN ticket_updates AS tu ON t.ticketnumber = tu.ticketnumber WHERE status = 'Completed' ORDER BY tu.datetime DESC LIMIT 50 ``` Try this.
One approach is to summarize the `ticket_updates` table to get what you want: ``` select t.* from tickets t join (select ticketid, max(datetime) as max_datetime from ticket_updates group by ticketid ) tu on t.ticketid = tu.max_datetime order by tu.max_datetime desc limit 0, 50; ```
SQL Query selecting from two separate tables using a order clause
[ "", "mysql", "sql", "" ]
I'm trying to do an update on my SQL DB (2008 R2), but for some reason it's updating more than I expected. I think there's an issue with my where, join, and update commands but I'm having trouble finding info on scope and order of operations. Fortunately, I'm practicing on DB backups that are restored before I make the...
I thought I'd update this since we got it working. My co-worker used a different approach (worked) and I'm not exactly sure why it didn't work (directly) with the parameters given for the problem, and the other values had to be used, but this is what fixed it. So the tables involved look like this: ``` PQdata table n...
As stated in the comment above, the update is currently being run seperately. Change the query to be an update instead of a select. Change your query to be - ``` UPDATE TestUnits SET TestUnits.unitNo = '05088' FROM DashboardData INNER JOIN TestUnitCounts ON DashboardData....
SQL Update command getting more than expected
[ "", "sql", "sql-update", "" ]
I'm looking for help with a formula. I'm looking for how to do two separate SELECT queries, but without merging them so. ``` SELECT basetype from table1 where name="test"; **SELECT itemid from table2 where itemid="5";** ``` I want the query to display basetype as a column and itemid as another column. Short version i...
I suspect you want this: ``` select rn, max(basetype) as basetype, max(itemid) as itemid from ((SELECT @rn := @rn + 1 as rn, basetype, NULL as itemid from table1 cross join (select @rn := 0) var where name = 'test' ) union all (SELECT @rn2 := @rn2 + 1, NULL, itemid from tab...
Try with union : ``` SELECT basetype from table1 where name="test" union SELECT itemid as basetype from table1 where itemid="5"; ```
mysql select two different queries
[ "", "mysql", "sql", "select", "scripting", "" ]
I have a table metrics which has the following columns : ``` stage name --------------------- new member new member old member new visitor old visitor ``` Now I can find out how many new or old members are there by running a query like this : ``` select stage, count(*) from metrics where name = 'memb...
You can do something like this: ``` with t as (select stage from metrics where name = 'member') select (select count(*) from t) as total, stage, count(*) from t group by stage ``` Check it: <http://sqlfiddle.com/#!15/b97a4/9> This is compact variant and includes the `'member'` constant only once.
The [window-function](http://www.postgresql.org/docs/9.3/static/tutorial-window.html) using variant: ``` with member as ( select stage, count(*) from metrics where name = 'member' group by stage ) select sum(count) over () as total, member.* from member ``` <http://sqlfiddle.com/#!15/b97a4/18>
Multi-level aggregation from a table
[ "", "sql", "postgresql", "" ]
I am having duplicate rows with the same storeactivityid show up in my results... This is the primary key, so this should not happen. Is there something wrong with my joins that could cause this? I could use distinct, but that will not solve the issue here. Any tips or advice? There are 3 duplicates showing for each re...
If it is a primary key, you can be certain that in the actual table you do not have duplicate rows with the same `storeactivityid`. Your query returns rows with the same `storeactivityid` because at least one of the joined tables has the matches the condition specified in the join. My best guess it is due to the foll...
i do not know what is in each of the tables, but the easiest way i found to debug something like his is ``` select [storeactivityid],count([storeactivityid]) as [count] from [<table>] <Start adding joins in one at a time> where [count] > 1 group by [storeactivityid] ```
Duplicate rows in SQL Server
[ "", "sql", "sql-server", "duplicates", "rows", "" ]
An event has many participants. A participant has a field of "status". ``` class Event < ActiveRecord::Base has_many :participants end class Participant < ActiveRecord::Base belongs_to :event end ``` I need to find all events except the following ones: events where every one of its participants has a status of '...
If I get it right your problem can be classified as relational division. There are basically two ways to approach it: 1a) Forall x : p(x) which in SQL has to be translated to: 1b) NOT Exists x : NOT p(x) For your problem that would be something like: ``` SELECT e.* FROM events e WHERE NOT EXISTS ( SELECT 1 ...
I really like [Lennarts examples](https://stackoverflow.com/a/23707565/3453463) I made a simple modification to the first example which will only return EVENT parent records which have Participation Child records, and is much faster at processing than finding the counts for each. ``` SELECT e.* FROM events e INNER J...
find all parent records where all child records have a given value (but not just some child records)
[ "", "sql", "ruby-on-rails", "ruby-on-rails-4", "has-many", "belongs-to", "" ]
Hey so I have a question. I have two tables. table1 and table2. table1: ``` id | car_numbers | type | model | type_id 1 3 bmw <model1> 1 2 5 bmw <model2> 1 3 2 mercedes <model1> 2 4 4 mercedes <model2> 2 ...
``` SELECT type, car_numbers, AVG(price) AS average_price FROM (SELECT type_id, type, SUM(car_numbers) AS car_numbers FROM table1 GROUP BY type_id) AS t1 JOIN table2 AS t2 ON t1.type_id = t2.type_id GROUP BY type ``` [DEMO](http://www.sqlfiddle.com/#!2/cbb37/3)
I think it might be this you are looking for ``` SELECT t.name, sum(Distinct o.car_number) car , avg(w.price) price FROM TYPE t INNER JOIN tone AS o ON o.type_id = t.id INNER JOIN ttwo AS w ON w.type_id = t.id GROUP BY t.name ``` <http://sqlfiddle.com/#!2/1937a/51>
MySQL relation between tables
[ "", "mysql", "sql", "database", "" ]
I have a table that has approximately 4 million records. I would like to make it have 240 million like so: 1. Add an additional column of type BIGINT, 2. Import 59 times the data I already have, 3. And for each 4 million group of records, have the additional column to have a different value The value of the additiona...
Sounds like you'd like to take the `cartesian product` of 2 tables and create a new table since you say `The value of the additional column would come from another table`? If so, something like this should work: ``` create table yourtable (id int, value int); create table yournewtable (id int, value int, data int); cr...
First, I would recommend that you create a new table. You can do this using a `cross join`: ``` create table WayBigTable as select t.*, n from table t cross join (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all . . . select 60 ...
Duplicate records of a MySQL table
[ "", "mysql", "sql", "" ]
I keep looking at this and do not understand why I am not getting a result set back here are my my queries ``` SELECT UserID FROM @SelectedID SELECT UserID FROM @SelectedIdValue SELECT UserID FROM @SelectedID WHERE NOT EXISTS (SELECT UserID FROM @SelectedIdValue ``` And here is the result set returned ![enter image...
You need a correlated subquery: ``` SELECT UserID FROM @SelectedID si WHERE NOT EXISTS (SELECT 1 FROM @SelectedIdValue siv WHERE si.UserId = siv.UserId ); ``` Your version of the query simply returned false for all rows. The subquery returns a value, so something e...
The exists subquery only checks whether user ids exist, not what their value is. If you replace "not exists" with "UserID not in" your query will return the expected result. Note though that "in" doesn't work as expected when there are null values in the column, verify if that's possible before using "in".
Something is Wrong with my SQL Query NOT EXISTS
[ "", "sql", "sql-server", "" ]
Using SQL Server Management Studio 2012, I'm trying to create a copy of a local database. I found a few variants of solution. One of them - backup and restore database as new one - [HERE](http://msdn.microsoft.com/en-us/library/ms190447%28v=SQL.100%29.aspx). Currently create database backup with name `Rewards2_bak`. T...
When you restore a database from a backup it will use the same file names as the original database. You need to change these file names during the restore. On the restore window go to the `Files` tab. On this window you have a column called `Restore As`. Change the file names at the end of the path in the column Resto...
I think you are trying to overwrite the logical filenames from the database you are trying to copy...guessing a bit but try this - try it in SSMS if you don't need to script it right now: 1. Backup the database you want to copy (Rewards2\_bak.bak is fine) 2. Create a new database (Rewards2\_copy) 3. Restore into Rewar...
How to create copy of database using backup and restore
[ "", "sql", "sql-server", "database", "copy", "ms-query", "" ]
I am unsure if my terminology is correct. I have this query: ``` select (select count(*) from table1 where column1 = 'x' and column2 = 'y' and column3 = 'z' ) as new_column1, (select count(*) from table 1 where column1 = 'x' and column2 = 'y' and column3 = 'z' ) as...
This will give you the delta between sum1 and sum2, expressed as a percentage relative to sum2: ``` select sum1 = s.sum1 , sum2 = s.sum2 , delta = sum1 - sum2 , delta_pct = 100.0 * ( sum1 - sum2 ) / sum2 from ( select sum1 = sum(case when t.c1='a' and t.c2='b' and t.c3='c' ...
Here's one way you could do it: ``` select new_column1, new_, new_column1 / new_ * 100 as PercentDiff from ( select (select count(*) from table1 where column1 = 'x' and column2 = 'y' and column3 = 'z' ) as new_column1, (select count(*) from table1 ...
SQL Percent difference between 2 aggregate columns
[ "", "sql", "sql-server-2008", "" ]
I have a table `messages` and a table `deleted_messages` every time the delete action on a message is fired instead delete the record I create a new record on the `deleted_messages` table. Then i would like retrieve the messages without the deleted messages on the `deleted_messages`. **ps**: I don't use soft delete he...
You can do so ``` select * from messages m left join deleted_messages d on d.message_id = m.id where d.message_id IS NULL AND m.user_id = 1 ``` This will give all the messages from user 1 which are not deleted ## [Demo](http://sqlfiddle.com/#!2/1c2e3/14) Other way to use `NOT EXISTS` ``` select * from messages m...
add the were condition in the left join clause ``` select * from messages left join deleted_messages on deleted_messages.message_id = messages.id and deleted_messages.user_id = 1 where deleted_messages.message_id is null ``` [sqlFiddle](http://sqlfiddle.com/#!2/1c2e3/17)
select rows mysql where the value of the left join is different
[ "", "mysql", "sql", "" ]
How can I get list of tables which have rows in my database. ``` Select A.Name From Sys.Tables A -- Inner Join with ? -- Or What conditions ? ``` Is it possible? please guide me! Thank you.
This query will help. ``` SELECT obj.name TableName, st.row_count FROM sys.dm_db_partition_stats(nolock) st inner join sys.objects(nolock) obj on st.object_id = obj.object_id WHERE index_id < 2 and st.row_count > 1 and obj.type = 'u' ``` Edited to show user tables only.
Well you could get the list of tables from INFORMATION\_SCHEMA.TABLES and then cursor through each table and exec some dynamic sql to get the COUNT(\*) for each table. So yes, it is possible, but I don't know if there is a more simpler solution.
How to get list of tables which have rows?
[ "", "sql", "sql-server", "" ]
I want to perform a select using an index (number) of a column. I tried: ``` select 1 from "user" select '1' from "user" ``` but they don't do what I expect.
You cannot do this in postgres. Selecting a literal (such as `1` or `'1'`) would just return its value. The only place such indices are allowed is in the `order by` clause, and even there, they don't relate to the order of columns in the table, but in the select list: ``` SELECT col1, col2, col3 FROM my_table OR...
When i need the FIRST column (and i don't know the column name) , i do something like this: ``` SELECT uno FROM _your_table_ as t(uno); ``` Just use an alias for table and columns!.. if you REALLY NEED the NUMBER 1 you could write something like this: ``` SELECT "1" FROM _your_table_ as t("1"); ``` double quotes.....
Refer to a column by its number (index)
[ "", "sql", "postgresql", "select", "postgresql-9.2", "" ]
I have a table T1, which contains which contains columns (A , B, C ,D) in which A is PK. And I have some more tables. And I want to get some data from these tables. I get the data as per my sql query from these tables. Sql query (query1) is as follows ``` select t3.col1 as A, t3.col4 as F, t4.col as H from t3, t4 whe...
I'd suggest using explicit join as in: ``` select t1.B, t1.C, ..., t3.col1 as A, t3.col4 as F, t4.col as H from t3 join t4 on t3.col1 = t4.col2 join t1 on t1.A = t3.col1; ```
try this ``` SELECT t1.B as B, t1.C as B, t1.D as D, t3.col4 as F, t4.col as H FROM t1, t3, t4 WHERE t1.A=t3.col1 AND t3.col1=t4.col2 ```
SQL Query, Get data from multiple tables and query result
[ "", "mysql", "sql", "" ]
I am just starting with mySQL, and have been through many of the tutorials, but there are a couple of things I cannot find. **1:** Do you just include the following in your HTML, or would it go into a different file (if so, what would the extension be)? ``` CREATE DATABASE user_db; CREATE TABLE Users ( ...
You can't use mySQL with only HTML. You need to use a server-side scripting language (such as PHP) to do your database work. As for the second question, a database runs on a server where it can be accessed by any page (that is given permission to access it). And the data would persist (never get deleted until you delet...
If you wish to use a database in your web application, then you need to set up and configure the database, in this case. MySQL would be running and you would use commands like that to create the tables within the database. From there, pending on the language(s) your using, you have a plethora of options available for a...
Proper way to Include SQL
[ "", "mysql", "sql", "" ]
I need to Find out the course with the most passes from my table tblResults. ``` tblResults: StuID Course Symbol 1001 CSC101 P 1001 RNG101 F 1002 CSC101 P 1002 RNF101 F 1003 HAP101 P 1004 HAP101 P ``` i.e should gi...
Something like this should work: ``` create view yourview as select course, count(*) passcnt from tblResults where symbol = 'P' group by course select * from yourview where passcnt = (select max(passcnt) from yourview) ``` * [SQL Fiddle Demo](http://sqlfiddle.com/#!2/d377d4/1) Note, you don't need the view, I just ...
``` SELECT Course, count(StuID) count FROM tblResults GROUP BY Course HAVING count = (SELECT max(c) FROM (SELECT count(StuID) c, Course FROM tblResults GROUP BY Course WHERE Symbol = 'p' ...
SQL Comparing 2 values that must be determined
[ "", "mysql", "sql", "" ]
Im currently amending the opencart search feature, this is a simplified version of the code without the PHP, Im looking to order my results by the most matched words. I have looked at other questions but cant seem to grasp how to use `CASE` in SQL to simply prioritise my matches. Is it possible someone could show me th...
***First solution :*** `CASE` ``` SELECT id FROM oc_products WHERE product_description LIKE '%my search keywords%' OR product_description LIKE '%my%' OR product_description LIKE '%search%' OR product_description LIKE '%keywords%' ORDER BY CASE WHEN product_description LIKE '%my search keywords%' THEN 0 ...
``` SELECT id FROM oc_products WHERE product_description LIKE '%my search keywords%' OR product_description LIKE '%my%' OR product_description LIKE '%search%' OR product_description LIKE '%keywords%' ORDER BY product_description LIKE '%my search keywords%' desc , product_description LIKE '%my search%' d...
Syntax for SQL on how to order by best match with most words using CASE
[ "", "mysql", "sql", "search", "" ]
I'm trying to get only the rows that are in USD and EUR from a table with more currencies. I thought the code should be something like: ``` SELECT IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD',1,0) OR IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR',1,0 FROM CONTRACTS_IN_DIFFERENT_CURRENCIES ``` But I know ...
The preceding answers are good in my opinion, but let's say you would have alot of currencies, you could do ``` SELECT * FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE CURRENCY IN ("USD","EUR") ```
It looks as though you're trying to use Excel's `IF(condition, true_response, false_response)` syntax. The equivalent in T-SQL is the `CASE WHEN THEN ELSE END` syntax: ``` SELECT CASE WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY ='USD' THEN 1 WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='E...
Simple If Else statement in sql
[ "", "mysql", "sql", "if-statement", "" ]
I have two tables with following data: `Test_parent`: ``` parent_id title ------------------ 1 Parent1 2 Parent2 3 Parent3 4 Parent4 ``` `Test_child`: ``` child_id parent_id property ------------------------------------ 1 1 A 2 2 A 3 2 B 4 3 A 5 3 C 6 4 A ``` I want to select...
I'm not sure about "more correct", but a simple JOIN with GROUP BY/HAVING will do it without a subquery; ``` SELECT test_parent.parent_id, test_parent.title FROM test_parent JOIN test_child ON test_child.parent_id=test_parent.parent_id AND test_child.property IN ('A','B') GROUP BY test_parent.parent_id, test_parent....
The query in the question ``` select * from test_parent p where 2 = (select COUNT(property) from test_child c where p.parent_id = c.parent_id and c.property in ('A', 'B')) ``` has a little problem: if there are two child, both with 'A' or both with 'B' the parent will show...
SQL - child must contain all specified values
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table that looks like this: ``` location | object | date-time-string | id -------------------------------------------- Login | label | 5/17/14 4:29:20 | 1 Login | main | 5/17/14 4:29:20 | 2 Login | button | 5/17/14 4:29:20 | 3 Login | name | 5/17/14 4:29:20 | 4 Login | passwd | 5/17/14...
1. Use a datetime field for dates. Really. No excuses. 2. Use [ISO-8601](http://xkcd.com/1179/) to represent date-time as string. No excuses. If you are wrong on either of the above (as you are, inexcusable), then cast the string to a date time and sort by the casted value. In your case is `mm/dd/yy` which is [style 1...
I'm not 100% sure , but try this: ``` SELECT object FROM table a INNER JOIN (SELECT TOP 1 date-time-string FROM table ORDER BY date-time-string DESC) b ON a.date-time-string=b.date-time-string ```
How do you return items using a SQL command that are the most recent based on a date time string?
[ "", "sql", "sql-server-2012", "" ]
I have a syntax that can copy all records from tables that have the same fields: ``` INSERT INTO table2 SELECT * FROM table1 WHERE id = '7' ``` So I would like to know how do I keep copying all values ​​except the 'id' field (because him is primary key and auto increment).
You list the columns: ``` insert into table2(col1, . . . coln) select col1, . . ., coln from table1 where id = '7'; ``` Under most circumstances, you should list the columns explicitly. You can run into problems even when tables have the same columns but in a different order. (The one exception in code t...
You have to list all the columns specifically: ``` INSERT INTO table2 (col1, col2, col3, ...) SELECT col1, col2, col3, ... FROM table1 WHERE id = '7' ```
Copy all records between tables with the exception of a line
[ "", "mysql", "sql", "" ]
Follow my code ``` begin declare @Iorder int set @Iorder=0 declare @no int set @no=(select MAX(IOrder) from Team) if @no=NULL set @Iorder=1 else begin set @Iorder=(select MAX(IOrder) from Team) set @Iorder=@Iorder+1 end end ``` if in Team tabl...
Test using `is null` instead. ``` begin declare @Iorder int set @Iorder=0 declare @no int set @no=(select MAX(IOrder) from Team) if @no is null set @Iorder=1 else begin set @Iorder=(select MAX(IOrder) from Team) set @Iorder=@Iorder+1 end end ``...
You can simply do this all in a short form. Try this: ``` begin declare @Iorder int SELECT @Iorder = ISNULL(MAX(IOrder),0)+1 FROM Team end ``` **Explanation:** `@Iorder` will be 1 (i.e., 0+1) if `MAX(IOrder)` is NULL. Otherwise, `@Iorder` will be `MAX(IOrder)+1`.
how to assign NULL type for int type in sql server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Imagine I have a table like this one: ``` CREATE TABLE marcas ( id_marca integer, marca character varying )); ``` I would like to make a query but get the value in every field empty. I know that could solve it like this: `SELECT '' as id, '' as marca FROM marcas` The problem is that i have plenty of tables and...
Here is one method to get `NULL` in every column. It uses `left outer join` with a failing condition: ``` select t.* from (select 1 as val ) v left outer join table t on 1 = 0; ``` EDIT: If you want to do this in Access, that is a challenge. The expression `select 1 as val` doesn't work. The following...
if you just want the column list and no rows returned then ``` SELECT TOP 0 * FROM marcas ```
SQL Empty query results
[ "", "sql", "database", "select", "" ]
``` select a.name from student a, student b where a.id = b.id and a.id = 1; ``` vs ``` select a.name from student a inner join student b on a.id = b.id and a.id = 1; ``` Are they actually the same?
They are the same as far as the query engine is concerned. The first type, commonly called a comma join, is an implicit inner join in most (all?) RDBMSs. The syntax is from ANSI SQL 89 and earlier. The syntax of the second join, called an explicit inner join, was introduced in ANSI SQL 92. It is considered improved s...
Obviously they are not the same syntactically, but they are semantically (they return the same). However, I'd write the second one as: ``` select a.name from student a inner join student b on a.id = b.id where a.id = 1; ```
What is the difference between these two SQL?
[ "", "sql", "join", "" ]
**For Example:** I have a table called Trans. There are three columns: `Date`, `Customer`, `Sales`: ``` Date Customer Sales 01/05/14 1 1000 02/05/14 2 5000 03/05/14 3 2500 10/05/14 4 10000 01/12/13 1 25000 02/12/13 2 500...
For `SQL Server` something like the below will work, the approach should work for any `TSQL`, may just need to alter the `CASE WHEN` for different `RDMS`. Note that you will need to change your field name `Date` to something else or you will inevitably run into problems. ``` SELECT Customer, sum(CASE WHEN datepart(...
Assuming you are using Sql Server, you can use following query ``` select a.id, (select sum(sales) from salesData where datepart(year,Date)=2013 and id=a.id) as sales_2013, (select sum(sales) from salesData where datepart(year,Date)=2014 and id=a.id) as sales_2014 from salesData as a group by a.id ``` Sql fiddle <htt...
How to select same column of values with different date criterias and display as column1 and column2 in the same query
[ "", "sql", "sql-server-2008", "" ]
I have a table (see the image below --red box). It describes the content of my table (A, B, C, and D) are the columns. The data structure will always be like this, if col A is Type\_1, only col B has a content while if Col A is Type\_2, Col C and D has contents while col B is NULL. Now, the table which re enclosed wit...
Something like this: ``` SELECT Table2Id, MAX(B) B, MAX(C) C, MAX(D) D FROM tbl WHERE A != 'Type_3' GROUP BY Table2Id ```
Assuming that there is only one row of data for type1 and one row of data for type 2, you can use the following: ``` SELECT Id, MAX(B) AS B, MAX(C) AS C, MAX(D) AS D FROM Table2 WHERE A IN ('Type_1','Type_2') GROUP BY Id ``` Example in this [SQL Fiddle](http://sqlfiddle.com/#!6/e3551/1/0)
SQL Query combine two rows into one row of data
[ "", "sql", "sql-server", "" ]
Edit 1: I am trying to fetch using this below query but problem is that the end div is not taken the occurrence after the start Point i.e ``` select ID, post_title, substr(post_content,instr(post_content,'<div style="position:absolute') + 0, instr(post_content,'</div>')) as temp from wp_posts where post_content LIKE '...
Your query is close, but you need to use LOCATE as well as INSTR to find the end of the embedded string: ``` select ID, post_title, substr(post_content, instr(post_content,'<div style="position:absolute'), LOCATE('</div>',post_content,instr(post_content,'<div style="position:absolute')+30)-instr(post_c...
the answer is variation of the following: ``` update wp_posts set post_content = CONCAT(LEFT(post_content, LOCATE('div style=', post_content)-1), SUBSTRING(post_content, LOCATE('</div>', post_content)+7)) where LOCATE('div style=', post_content) > 0 ``` Changing the "div style" to whatever beginn...
MYSQL Replace string between two known strings
[ "", "mysql", "sql", "phpmyadmin", "" ]
I want to load some datas from DB, and i have a problem i don't understand. My function : ``` public List<News> getNews(){ db = this.getReadableDatabase(); List<News> tmp_list = new LinkedList<News>(); txtRequest = "SELECT * FROM myTable "; Cursor c = db.rawQuery(txtRequest, null); tmp_list = l...
You are closing the cursor after the first pass in your while loop. Plus you are always moving to the first element of your SQL result thus potentially only reading the 1st one and creating an infinite loop. Luckily you have a close to stop your loop ;) You could make the following small changes to improve it a littl...
Close cursor after using, not in while loop execution (on loadListNews). ``` public List<News> loadListNews(Cursor c) { List<News> tmp_list = new LinkedList<News>(); while(c.moveToNext()) { tmp_list.add(loadOneNews(c)); } c.close(); return tmp_list; } ```
Android Error to reopen an alreay closed object
[ "", "android", "sql", "" ]
Maybe the title of the question is not completly right. I will try explain better my issue. I have two tables with following structure: TABLE01: ``` ID | GENUS | SPECIES | INDIVIDUUM 1 | A | a | alfa 2 | B | b | beta 3 | C | c | gama 4 | D | d | delta 5 | E | e |...
try to see if this helps: ``` SELECT table01.id, table01.individuum, table01.species, table01.genus, -- ----------------- table02.id as id2, -- ----------------- t01.individuum as individuum2 t01.species as species2, t01.genus as genus2, -- ----------------- table02.index from table01 inner ...
Try this way. Just rename (with aliases) the fields. ``` select t2.id, spec1.individuum, spec1.species, spec1.genus, t2.id2, spec2.individuum, spec2.species, spec2.genus t2.INDEX from table2 t2 table1 spec1, table2 spec2 where t2.id1 = spec1.id and t2.id2 = spec2.id ``` Then you can add whatev...
How to present a mixed result of two tables using subqueries in MySQL?
[ "", "mysql", "sql", "" ]
Table Position: ``` CREATE TABLE Position( p# NUMBER(8) NOT NULL, /* Position number */ ptitle VARCHAR(30) NOT NULL, /* Position title */ employer VARCHAR(100) NOT NULL, /* Institution name */ salary NUMBER(9,2) NOT NULL, /* Salary */ ...
Your subquery: ``` SELECT ptitle FROM Position WHERE salary < (SELECT MAX(salary) FROM Position) ``` always finds the same four rows, so at least one result is always returned, so `exists` would always be true, so `not exists` is always false. You have no correlation between the row you're examining and the subquery....
An easier way to get the result you're looking for is to use an analytic function to `rank` all positions by salaries, and then just take the top one: ``` SELECT ptitle FROM (SELECT ptitle, RANK() OVER (ORDER BY salary DESC) AS rk FROM position) WHERE rk = 1 ```
Queries as SELECT statements with NOT EXISTS clauses
[ "", "sql", "database", "oracle11g", "sqlplus", "" ]