Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following table in my database. ``` # select * FROM matches; name | prop | rank ------+------+------- carl | 1 | 4 carl | 2 | 3 carl | 3 | 9 alex | 1 | 8 alex | 2 | 5 alex | 3 | 6 alex | 3 | 8 alex | 2 | 11 anna | 3 | 8 anna | 3 | ...
``` select x.name, max(x.rank) from matches x join ( select name from matches where prop = 1 AND rank > 5 intersect select name from matches where prop = 3 AND rank >= 8 ) y on x.name = y.name group by x.name order by max(rank); ```
Filtering the data to match your criteria here is quite simple (as shown by both Amir and sternze): ``` SELECT * FROM matches WHERE prop=1 AND rank>5) OR (prop=3 AND rank>=8 ``` The problem is how to aggregate this data so as to have just one row per candidate. I suggest you do something like this: ``` SELECT m.nam...
Matching algorithm in SQL
[ "", "sql", "postgresql", "relational-division", "" ]
My table is defined like this: Name is a string and property too. ``` ID | Name | Property ``` An example for data in this table is this: ``` ID | Name | Property 1 Peter Newsletter 2 Paul Register 3 Peter Register 4 Shaun Newsletter 5 Steve Register ``` Now I like to query all people that hav...
Here is one method: ``` select t.* from table t where exists (select 1 from table t2 where t2.name = t.name and t2.property = 'NewsLetter' ) and exists (select 1 from table t2 where t2.name = t.name and t2.property = 'Register' ); ...
An alternative, pretty much on the same lines as Gordon's solution, but without using `EXISTS`: ``` select * from tablename where name in (select name from tablename where property = 'Newsletter') and name in (select name from tablename where property = 'Register') ```
How to write a SQL-Query for the following table?
[ "", "sql", "" ]
I'm not good at sql but I can create,understand common SQL queries. While scouring the net it seems its hard to find a befitting way on this query. I have a query which is ``` SELECT COUNT(`BetID`), FORMAT(SUM(`BetAmount`),0), FORMAT(SUM(`Payout`),0), ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2),...
If you want the numbers rounded *before* subtracting them (which seems to be the case when you want to subtract the formatted numbers), you'll need to round them first to the same precision as the formatting, subtract and lastly format the result; ``` SELECT COUNT(`BetID`), FORMAT(SUM(`BetAmount`),0), FO...
Use `FORMAT((SUM(BetAmount) - SUM(Payout)),0)` Try this: ``` SELECT COUNT(`BetID`), FORMAT(SUM(`BetAmount`),0), FORMAT(SUM(`Payout`),0), FORMAT((SUM(`BetAmount`) - SUM(`Payout`)),0), ROUND((SUM(`BetAmount`) / COUNT(`BetID`)),2), ROUND((((SUM(`BetAmount`) + SUM(`Payout`)) / SUM(`Pay...
mysql get difference from the result of 2 fields queried
[ "", "mysql", "sql", "select", "sum", "difference", "" ]
Probably a simple one but I'm having trouble getting this to work in SQL. ( easy with VBA ). Given xxx\_123\_abcd I need to extract the 123 part. whatever code searchs for the \_ should always work from the left because sometimes and string might be xxx\_123\_abcd\_xxx. Thanks in advance for any advice :)
Use CHARINDEX to search for the underscores, to be able to extract the part of the string you need with SUBSTRING. Something like this should work: ``` SELECT SUBSTRING(MyColumn, CHARINDEX('_', MyColumn)+1, CHARINDEX('_', MyColumn, CHARINDEX('_', MyColumn)+1)-CHARINDEX('_', MyColumn)-1) FROM MyTable ``...
you can also go with this ``` SELECT LEFT(Col1,PATINDEX('%[^0-9]%', Col1+'a')-1) from( SELECT SUBSTRING(Col1, PATINDEX('%[0-9]%', Col1), LEN(Col1)) As Result From table )x ```
Find a string between two string values
[ "", "sql", "sql-server", "" ]
i am using this query to get some result ``` select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit from transactions t inner join accounts a on a.code = t.accode where a.TypeCode = 5 and t.date between '2014-05-01' and '2014-05-15' group by t.accode,t.acname ``` i am getting this result with this...
You can insert a subquery in the `SELECT` statement like this: ``` select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit , (SELECT sum(t2.debit) - sum(t2.credit) FROM transactions AS t2 INNER JOIN accounts AS a2 ON t2.accode = a2.code WHERE a2.code = t.accode AND t2.date < '2014-05-01') as prev...
You can just add the columns to your existing field as below: ``` select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit, ( sum(t.debit) - sum(t.credit) ) as previousbalance from transactions t inner join accounts a on a.code = t.accode where a.TypeCode = 5 and t.date between '2014-05-01' and '201...
want to add one more column in my Sql server query
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Sorry for the vague title (I just don't know how to describe this conundrum) Give the following schedule table for a classroom: | Classroom | CourseName | Lesson | StartTime | EndTime | | --- | --- | --- | --- | --- | | 1001 | Course 1 | Lesson 1 | 0800 | 0900 | | 1001 | Course 1 | Lesson 2 | 0900 | 1000 | | 1001 | C...
The query determines each rows `EndTime` by using `NOT EXISTS` to make sure no other class or course of a different type is scheduled between a course range's `StartTime` and `EndTime` and then uses `MIN` and `GROUP BY` to find the `StartTime`. The `NOT EXISTS` part ensures that there aren't "breaks" between the `Star...
If you're using SQLServer 2012 or better you can use `LAG` to get the previous value of a column, then `SUM() OVER (ORDER BY ...)` to create a rolling sum, in this case one that count the change of the CourseName, that can be used as the `GROUP BY` anchor ``` With A AS ( SELECT ClassRoom , CourseName ,...
Group consecutive rows of same value using time spans
[ "", "sql", "sql-server", "t-sql", "" ]
I have a sales order table that goes: ``` SALESORDERCODE ITEMCODE WAREHOUSECODE SO-605338 ITEM-003200 MAIN SO-605338 ITEM-016328 PFC ``` I also have an inventory table that goes: ``` WAREHOUSECODE ITEMCODE UNITSINSTOCK MAIN ITEM-003200 1 MAIN ITEM-016328 2 P...
If it's limited to just those two, you can use a case statement: [SQL Fiddle](http://sqlfiddle.com/#!3/4a92c/1) ``` select SO.SalesOrderCode ,I.ITEMCODE ,sum(case when I.WAREHOUSECODE = 'MAIN' then I.UNITSINSTOCK else 0 end) as MAIN ,sum(case when I.WAREHOUSECODE = 'PFC' then I.UNITSINSTOCK else 0 end) from SalesOrd...
You can get the result using 2 JOINs on your `INVENTORY` table - one join for each `WarehouseCode` that you want in a column: ``` select so.SALESORDERCODE, so.ITEMCODE, i_main.UNITSINSTOCK UnitsInMain, i_pfc.UNITSINSTOCK UnitsInPFC from SalesOrder so left join Inventory i_main on so.ItemCode = i_main.ItemCo...
Multiple Where Clauses as Separate Columns
[ "", "sql", "" ]
I'm still new to SQL so this question I am asking may be easy for you. So I am creating a report that for every week generates the prior 14 days (Or 2 weeks) of the funded contracts. I know this has to be Hardcoded to a specific company. The ID for that specific company is '55' So can someone help me with this function...
In order to check if a.funded\_date is between today's date and two weeks ago, you are going to need several sql server functions. The first one is [GetDate()](http://msdn.microsoft.com/en-us/library/ms188383.aspx). This returns the current date and time as a datetime value. Now, you want to check only for the date pa...
if a.funded\_date is a DATETIME then ``` a.funded_date between dateadd(day,-14,getdate()) and getdate() ``` if a.funded\_date is a DATE then ``` a.funded_date between cast(dateadd(day,-14,getdate()) as date) and cast(getdate() as date) ```
Calculating 2 weeks for every week SQL
[ "", "sql", "sql-server", "hardcode", "" ]
I have the table below.Using salary as condition I want to get multiple rows. Below is current table call it employee. ``` empid name salary ----------------------------------- 1 A1 alex 20000 2 B2 ben 4500 3 C1 carl 14000 ``` compare the salary to cert...
Your question is unclear, because your logic implies that you should only have 3 output rows for 3 input rows. Your output however implies that you want to compare the salary to certain fixed values, and every time the salary is larger than the fixed value, show a record in output. If the former is the case, Minh's qu...
This returns 3 rows and enough for your need: ``` SELECT empid, name, salary, case When salary<6000 then 101 When salary Between 6000 And 18000 Then 102 Else 103 End as incometype FROM employee; ```
Select statement with multiple rows from condition on values in single column
[ "", "sql", "select", "conditional-statements", "" ]
I have a simple table like ``` user_id | meta_key | meta_value =============================== 1 | color | green 2 | color | red 1 | size | L 2 | size | L 3 | color | blue ... ``` Now I like a single query where I get all colors and sizes of a certain user ``` SELECT a...
The predicate on `b.meta_key` in the **`WHERE`** is negating the "outerness" of the LEFT JOIN operation. One option is to relocate that predicate to the **`ON`** clause, for example: ``` SELECT a.user_id AS ID, a.meta_value AS color, b.meta_value AS size FROM table AS a LEFT JOIN table AS b ON a.user_id = b.use...
The where clause is killing you. Let's take `b.meta_key = 'size'`. If there are no rows in your B table, meta\_key will come back null. The filter on that column removes them from the result. Try adding the `b.meta_key = 'size'` to the on clause.
Joining same table with NULL values in MySQL
[ "", "mysql", "sql", "" ]
I have the following procedure for inserting into a user table: ``` -- ================================================ -- Template generated from Template Explorer using: -- Create Procedure (New Menu).SQL -- -- Use the Specify Values for Template Parameters -- command (Ctrl-Shift-M) to fill in the parameter -- val...
`RETURN` can only be used with an `int`. You can simply use a `SELECT` query to retrieve the value of variable `@GUID`. Reference: [http://technet.microsoft.com/en-us/library/ms174998(v=sql.110).aspx](http://technet.microsoft.com/en-us/library/ms174998%28v=sql.110%29.aspx)
get rid of `RETURN @GUID` and you should be good to go.
unqiueidenfitier is not compatible with type int SQL Server Procedure
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2012-express", "" ]
``` COUNTRY NUM_GUNS MAX_BOR MAX_DISP Gt.Britain 40000 45000 32000 Germany 40000 45000 42000 USA 60000 48000 46000 Japan 45000 54000 65000 ``` This is my table and i need column name with highest value in the row.Example for Gt.Britain the max value is 45000 i want to di...
Just try do it *explicitly*, like that: ``` select case when NUM_GUNS = Greatest(NUM_GUNS, MAX_BOR, MAX_DISP) then 'NUM_GUNS' when MAX_BOR = Greatest(NUM_GUNS, MAX_BOR, MAX_DISP) then 'MAX_BOR' else 'MAX_DISP' end as MaxColumnName, Greatest...
You can use `CASE` Statement ``` SELECT COUNTRY, CASE WHEN NUM_GUNS > MAX_BOR AND NUM_GUNS > MAX_DISP THEN 'NUM_GUNS' ELSE NUM_GUNS END NUM_GUNS, CASE WHEN MAX_BOR > NUM_GUNS AND MAX_BOR > MAX_DISP THEN 'MAX_BOR' ELSE MAX_BOR END MAX_BOR , CASE WHEN MAX_DISP > MAX_BOR AND MAX_DISP > NUM_GUNS THEN ...
I have to display the column name with highest value in a row in oracle
[ "", "sql", "oracle", "" ]
Basically I just need to get a 5 digits number that is separated by a space. The 5 digits number can be anywhere in the varchar. Example: I have a varchar column with this various data in SQL 2008 table ``` travel visa 34322 LLL001 Coffee 34332 Jakarta FDR001 34312 Taxi cost cash taxi cash 34321 34556 eating dinner ...
How about something like this? ``` select substring(tr_comment, patindex('%[0-9][0-9][0-9][0-9][0-9] %', tr_comment), 5) as zip5 ``` If you want to consider that it might be at the end of the string: ``` select substring(tr_comment, patindex('%[0-9][0-9][0-9][0-9][0-9] %', tr_comment + ' '), 5 ) a...
use this, this may help you ``` select SUBSTRING(tr_comment, PATINDEX('%[0-9]%', tr_comment), 5) as zip ```
How to find 5 digit number in a varchar?
[ "", "sql", "sql-server", "" ]
For some reason i need to explode a query in multisteps (very large rows and many join) , **I know its possible to perform the query like SELECT IN (subquery) but its not what i need to achieve.** How to construct my query into step where query 2 can use the result of query 1 (without using temporary table) with an IN...
Use a `Temporary Table` instead and have the query1 value inserted in that table. then in your query2 you can directly fetch the data from temporary table; like below (A code sample) ``` CREATE PROCEDURE `exemple`() BEGIN create temporary table temptest(col varchar(20)); insert into temptest SELECT `foo` FROM `tabl...
I add an answer here To follow the @Rahul correct answer in final edit , for thoses who need to achieve this particular case (when subquery cannot perform as well you'd like) , here is the final form of the procedure using the mysql GROUP\_CONCAT and CONCAT function : **temp is the declared local variable for storin...
mysql stored procedure construct with GROUP_CONCAT and IN clause
[ "", "mysql", "sql", "stored-procedures", "" ]
I have this query : ``` SELECT SUM(IF(b.correct = 1,1,0)) correct_answers, SUM(IF(b.correct != 1,1,0)) incorrect_answers, SUM(IF(a.answer IS NULL) 1,0)) as no_answers, a.ID FROM `a` join b on a.answer = b.id where a.created_at between '2014-06-10' and '2014-06-17' group by a.ID ord...
Try this: ``` SELECT SUM(b.correct = 1) correct_answers, SUM(b.correct != 1) incorrect_answers, SUM(a.answer IS NULL) AS no_answers, a.ID FROM a LEFT JOIN b ON a.answer = b.id WHERE a.created_at BETWEEN '2014-06-10' AND '2014-06-17' GROUP BY a.ID ORDER BY SUM(b.correct = 1) DESC; ```
You missed a ',' int the 3rd Line Change : ``` SUM(IF(a.answer IS NULL) 1,0)) as no_answers, ``` To: ``` SUM(IF(a.answer IS NULL, 1,0)) as no_answers, ```
Count of NULLS in IF condition
[ "", "mysql", "sql", "count", "group-by", "sum", "" ]
Seems like a simple question... but I am stumped. ``` declare @Total_User int set @Total_User = 8 declare @Total int set @Total = 12 declare @Number int set @Number = (@Total_User / @Total) * 100 select @Number as 'Standard' ``` I am expecting 66, but my select comes out zero ?? What am...
The result of `(@Total_User / @Total)` is zero, as it is doing integer division. You can multiply by 100 first, which gives the result that you expected: ``` set @Number = 100 * @Total_User / @Total ``` To get a rounded value rather than truncated, you would use floating point values and the `round` function: ``` s...
Try: set @Number = (@Total\_User\*100 / @Total)
How do I get an int
[ "", "sql", "math", "" ]
I try to make a sql query to get all my followers except me. I have the following tables: users ``` | id_user | username | | 1 | xaxa | | 2 | toto | | 3 | bubu | | 4 | yiyi | | 5 | pepe | | 6 | sisi | | 7 | fifi | | 8 | mama | | 9 ...
The solution is a union of two simple joins: ``` SELECT u.id_user, u.username name FROM friends f JOIN users u ON u.id_user = f.id_user_to WHERE f.id_user = 10 UNION SELECT u.id_user, u.username FROM friends f JOIN users u ON u.id_user = f.id_user WHERE f.id_user_to = 10 ``` Note that the keyword `UNION` removes dup...
This should do: ``` SELECT u.id_user, u.username name FROM `friends` f JOIN `users` u ON u.id_user = f.id_user_to and f.id_user = 10 or u.id_user = f.id_user and f.id_user_to = 10 ORDER BY u.id_user ``` SqlFiddle: <http://sqlfiddle.com/#!9/7cbb3/1>
SQL query to get my followers except me
[ "", "mysql", "sql", "" ]
I have 1 id column and 3 int columns. Data is inserted in this way ``` insert into table (col1, col2) values (1,1) insert into table (col2, col3) values (1,1) insert into table (col1, col3) values (1,1) insert into table (col1) values (1) ``` then, row 1, col 3 is null row 2, col 1 is null, row 3, col 2 is null. ...
If you want to update the table so the `NULL`s become `0`, use `coalesce()`: ``` update table t set col1 = coalesce(col1, 0), col2 = coalesce(col2, 0), col3 = coalesce(col3, 0) where col1 is null or col2 is null or col3 is null; ``` `coalesce()` is the ANSI-standard function for replacing a `N...
If you want to insert `0` to columns by default, you can alter the table and set `DEFAULT CONSTRAINT` to needed column ``` ALTER TABLE myTable ADD DEFAULT(0) FOR Col1 ``` *No **UPDATE** statement required* Anyhow you need to update existing records using UPDATE statement.
select multiple columns which are null for a row
[ "", "sql", "sql-server", "" ]
I have a basic order detail table that contains: `docDate`, `customerCode`, `itemCode`, `Price`, and `Quantity`. Looked through a number of similar questions, but they didn't seem to take into account everything I need, and I failed to re-purpose the other solutions. The end goal: Only the most recent record of each i...
I think you want to something like this: ``` select * -- or whatever columns you actually want from RDR1 inner join (SELECT itemCode, MAX(docDate) AS docDate FROM RDR1 WHERE customerCode= 'TEST001' GROUP BY ItemCode) MD on MD.docDate = RDR1.docDate and md.ItemCode = RDR1.ItemCo...
``` SELECT distinct (ItemCode), docDate, Price, Quantity FROM RDR1 WHERE customerCode= 'TEST001' ORDER BY docDate DESC ```
Need to select most recent record, group by customer and item code
[ "", "sql", "sql-server", "" ]
In XLS I have two columns A and B. ``` A,B 1,1 2,3 2,5 1,6 5,11 2,13 ``` A column have value, and B column is calculated with formula, (A + (previous row B value)) How can i do this calculation on MYSQL? I'm trying to join same table twice and i can get previous rows A column next to B. I can sum them, but how ca...
``` SELECT A, @b := A+@b AS B FROM (SELECT A FROM YourTable ORDER BY id) AS t CROSS JOIN (SELECT @b := 0) AS var ``` The user variable `@b` holds the value of `B` from the previous row, allowing you to add the current row's `A` to it. [DEMO](http://www.sqlfiddle.com/#!2/f66f8a/1)
<http://sqlfiddle.com/#!2/74488/2/1> shows how to select the data. ``` SET @runtot:=0; Select a,b, @runtot:=@runtot+a from b ``` However there's an underlying problem I can't figure out. Since you don't have a defined order, the SQL could do this ordering in any way, so you may not get the desired results.. without a...
Mysql how to sum column with previous column sum
[ "", "mysql", "sql", "math", "xls", "" ]
I have the following tables. One haves the `TimeRegister` for each Employee (each row equals a IN and a OUT in `asc` sequence): ``` Employee TimeRegister 15 2014-04-01 11:51:43.000 15 2014-04-01 14:03:52.000 15 2014-04-01 14:17:01.000 15 2014-04-01 16:01:12.000 15 ...
I've used a recursive cte to generate all dates for a range, but if as you say you have another table with all dates (or all relevant / working dates), use that instead of the `cteDateGen`. Similarly, I've scraped the unique employees from the same table as `TimeRegister` - again you may have another table of Employee....
This isn't perfect (it gives the null in the employee rather than the date, and the comparison of just the year/month/day is crude!)) ``` select Employee, coalesce(TimeRegister, Date) from Date left outer join EmpDate on left(cast(Date as nvarchar), 10) = left(cast(TimeRegister as nvarchar), 10) ``` i.e. gives: `...
SQL - Create row for filling in NULL into missing dates but repeating ID Column Value
[ "", "sql", "sql-server", "date", "row", "fill", "" ]
I have an array of ids, I have to select from table for each value of array , i can get it by one by one in `for loop`, ``` SELECT point, privacy FROM `tableName` WHERE id='1403176452487620892'and status=1 ``` but the problem is that array size is 100, i need a single query not 100.
Why can't you use: ``` SELECT point, privacy FROM `tableName` WHERE status=1 and id in(?,?,?...) ``` Yes, it's ridiculously long, but if one query is what you need...
You can use like this : ``` $ids = join(',',$ids); $sql = "SELECT * FROM tableName WHERE id IN ($ids)"; ```
Select Query by array values
[ "", "mysql", "sql", "arrays", "" ]
I've been having trouble understanding this example, I have the answer but I'm having trouble wrapping my head around how this works. How are the joins working exactly? Examine the structures of the PLAYER and TEAM tables: ``` PLAYER ------------- PLAYER_ID NUMBER(9) PK LAST_NAME VARCHAR2(25) FIRS...
So the first `LEFT OUTER JOIN` takes the player table, then adds on the info for each players manager. Each player has an `ID` for its manager, who is also a player with an `ID`. If Mr. A, with `player_id 9`, is a manager for Ted, with `player_id 5`, then Ted's manager\_id will be `9`. The first join takes Ted's `manag...
In your example the players that are also managers, have a null value in the manager\_id column. Take the first part of the SQL statement, which is: ``` SELECT p.last_name, p.first_name, m.last_name, m.first_name, t.team_name FROM player p LEFT OUTER JOIN player m ON (p.manager_id = m.player_id) ``` Since you are per...
SQL JOIN and LEFT OUTER JOIN
[ "", "sql", "oracle", "join", "outer-join", "" ]
In SQL Server 2012 I have a table called `Deal_Country`. This table contains a field called `deal_id`, which is not a primary key. The same `deal_id` value can be in the table multiple times. What I would like to know is the number that the most common `deal_id` is in the table. Please see example below. ``` deal_...
Use `order by` and `top`: ``` select top 1 deal_id, count(*) as numtimes from DEAL_COUNTRY group by deal_id order by count(*) desc ``` In MySQL, you would use `limit` instead of `top 1`.
**MySQL Solution**: `count` first, sort them from max to min and pick the top 1 record. ``` select deal_id, count(deal_id) deal_count from deal_country order by 2 desc limit 1 ```
counting times the most frequent record appears in a table
[ "", "sql", "sql-server", "" ]
I have following 3 tables(Organization, OrganizationAddress, Address).Each organizations has more than one address and one of them is primary.if an organization has primary address,I need to select the primary address else that column can be null or blank. How can i write a sql sub query in mysql?. Please help me, Th...
You just need a `LEFT JOIN` ``` select a.orgid, b.orgaddressid, c.address from organization a left join organization_address b on a.orgid = b.orgid and b.isprimaryaddress = 'YES' left join address c on b.orgaddressid = c.addressid where a.orgid = 1; ```
Maybe something like this. I think you need to use `LEFT JOIN` for both tables: ``` select organization.orgid, organization_address.orgaddressid, address.address from organization LEFT JOIN organization_address ON organization_address.orgid = organization.orgid AND organization_address.isprim...
Write Sql sub Query
[ "", "mysql", "sql", "sql-server", "subquery", "" ]
I have a select statement that gives me the results I need for my update but I have no idea how to incorporate it into the update. Below is the select statement and the results. ``` select top 20 percent fpartno ,(fytdiss * fmatlcost) as 'total' from inmast where fpartno not like 'CRV%' and fcstscode = 'A' group by fp...
Updating `top 20 percent` is tricky... because you can't put an `order by` in an update. I would do something like this: ``` select * -- update t set fabccode='a' from inmast t where fpartno in ( select top 20 percent fpartno from inmast t where fpartno not like 'CRV%' and fcstscode = 'A' group by...
``` update inmast set fabccode = 'A' where fpartno in ( select top 20 percent fpartno from inmast where fpartno not like 'CRV%' and fcstscode = 'A' group by fpartno, fytdiss,fmatlcost,fabccode order by (fytdiss * fmatlcost) desc) ```
Update based on a select statement SQL Server 2005
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have 2 tables like ``` Company( #id_company, ... ) addresses( address, *id_company*, *id_city* ) cities( #id_city, name_city, *id_county* ) countries( #id_country, name_country ) ``` What i want is : It is a good design ? ( a company can have many addresses ) And the important thing is that you my notice that ...
First of all we should distinguish natural keys and technical keys. As to natural keys: 1. A country is uniquely identified by its name. 2. A city can be uniquely identified by its country and a unique name. For instance there are two Frankfurt in Germany. To make sure what we are talking about we either use the disti...
This design is fine. A (relational) table *always* has a (candidate) key. (One of which you can choose as the primary key, but candidate keys, aka keys, are what matter.) Because if no subset of columns smaller than set of all columns is unique then the key is the set of all columns. Since every table has one, in SQL...
PK for table that have not unique data
[ "", "sql", "database", "database-design", "database-performance", "" ]
I read most relevant Q/A on <https://stackoverflow.com/questions/tagged/greatest-n-per-group> tag but doesn't found solution for my task as details differ. I have a table with *amount*/*currency*/*date* and have a task to convert *amount* to *amount in national equivalent* on that *date*. One problem that currency ex...
latest currencies by "max" with "group py": ``` select cr.COUNTRY, cr.CURRENCY, cr.RATE from CURRENCY_RATE cr where cr.dt = (select max(subcr.DT) from CURRENCY_RATE subcr where subcr.COUNTRY = cr.COUNTRY and subcr.CURRENCY = cr.CURRENCY group by subcr.CURRENCY, subcr.COUNTRY); -- too long select count (*) from ( ...
You might try a query like this: ``` SELECT A.AMOUNT * A.RATE FROM ( SELECT P.AMOUNT, CR.RATE, ROW_NUMBER() OVER (PARTITION BY P.ROWID ORDER BY CR.DATE DESC) AS RN FROM PAYMENT P INNER JOIN CURRENCY_RATE CR ON P.CURRENC...
greatest-n-per-group with condition and joining to large table (or query for getting amount in national currency when holes in currency rates table)
[ "", "sql", "performance", "oracle", "query-optimization", "greatest-n-per-group", "" ]
I am trying to import a CSV into MSSQL 2008 by using the flat file import method but I am getting an Overflow error. Any ideas on how to go around it? I used the tool before for files containing up to 10K-15K records but this file has 75K records in it.... These are the error messages ``` Messages Error 0xc020209c: ...
This could be a format problem of the csv file e.g. the delimiter. Check if the delimiters are consistent within the file. It could also be a problem of blank lines. I had a similar problem a while ago. I've solved it by removing all blank lines in the csv file. Worth a try anyway.
You may have one or more bad data elements. Try loading a small subset of your data to determine if it's a small number of bad records or a large one. This will also tell you if your loading scheme is working and your datatypes match. Sometimes you can quickly spot data issues if you open the csv file in excel.
Import Flat File to MS SQL
[ "", "sql", "sql-server", "" ]
Here I have a sample table: ``` id | datetime | views -------------------------------- 1 | 2014-02-27 21:00:00 | 200 65 | 2014-02-08 05:00:00 | 1 65 | 2014-02-08 10:00:00 | 3 65 | 2014-02-08 17:00:00 | 1 65 | 2014-02-08 20:00:00 | 1 65 | 2014-02-08 21:00:00 | 1 65 | 2014-02-09 04:00:00 | 2 65 | 2...
You can use the [DATE function](http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date) to get the date part of your datetime value: ``` SELECT id, DATE(datetime) AS mydate, SUM(views) AS total FROM yourtable GROUP BY id, DATE(datetime); ```
``` SELECT `id` , DATE(`datetime`) , SUM(`views`) FROM `table` GROUP BY `id` , DATE(`datetime`) ```
Is it possible to sum the result of a column based on the date being group by day?
[ "", "mysql", "sql", "datetime", "" ]
I have a block of vbscript which takes in a variable, builds a sql string with it, executes the sql string, then passes the results of the sql query along with the original variable into another sub. It works pretty much all the time, except in one instance. Here's the code (I added line numbers for reference... Also, ...
I was able to resolve this after looking at the hints provided by Pavel and doing more research on the error code. The issue was that user\_id is assigned (prior to this sub being called) to a value in another recordset which was also stored in the rs variable (which I redefine inside of this sub). Apparently in classi...
I'm pretty sure that your issue is connected with defining variables. Let me explain why do I think so. I created a test page (test.asp) ``` <!--#include virtual="/includes/gm_functions.asp"--> <% UpdateContact1 "who cares", 34838 'UpdateContact1DefineNewVar "who cares", 34838 response.write("Finished") %...
Unable to access vbscript variable after using it in sql string - Variable is not null, but errors when used
[ "", "sql", "sql-server", "vbscript", "asp-classic", "" ]
I have a table (Table1) that has an ID that is shared from multiple-inserts: > ``` > ID | RefID | Field_Name | Field_Value | Type > 1 | 1 | NumbAmt | 1111 | INT > 2 | 1 | LocAdd | 123 Street | String > 3 | 1 | LocDesc | Something | String > 4 | 1 | LocHidden | Useless ...
You have several options: * Join the table to itself * Use PIVOT * Subquery all fields in the SELECT list * Use OUTER APPLY for each field * Use CTE * **Consider to rethink your scheme!** **JOINS** ``` SELECT T1_RefID.RefID, T1_NumbAmt.FieldValue AS NumbAmt, T1_LocAdd.FieldValue AS LocAdd FROM (SELECT DIST...
You could create a view for this and use it ``` SELECT T.RefID, TAmt.Field_Value as Amt, TAddress.Field_Value as Address, TType.Field_Value as Type FROM ( SELECT DISTINCT RefID FROM Table1 WHERE Type IN ('INT', 'String') ) T LEFT JOIN Table1 AS TAmt ON T.RefID = TAmt.RefID ...
SQL: Selecting NOT NULL data with a column that is shared and changes?
[ "", "sql", "sql-server", "" ]
I have a sample table which looks like following: ``` WITH T(ID, SLOW, MEDIUM, FAST, SUPER_FAST) AS (SELECT 1, 'Y', 'Y', 'N', 'Y' FROM DUAL UNION ALL SELECT 2, 'N','Y','N', 'Y' FROM DUAL ) SELECT 'Identified in ' ||CASE WHEN L_TEXT_A IS NOT NULL THEN L_TEXT_A END ||' , ' ||CASE WHEN L_TEXT_B IS NOT...
If you are using Oracle 11g2, a combination of unpivot and listagg can help, try this query ``` WITH T(ID, SLOW, MEDIUM, FAST, SUPER_FAST) AS (SELECT 1, 'Y', 'Y', 'N', 'Y' FROM DUAL UNION ALL SELECT 2, 'N','Y','N', 'Y' FROM DUAL union all SELECT 3, 'N','N','N', 'Y' FROM DUAL union all ...
Here is some code that uses simple instr, substr and replace functions built in functions which seems to work for all combinations. Note, if you have the option of doing this via a PL/SQL function you could probably simplify the code a bit: ``` with t(id, slow, medium, fast, super_fast) as ( select 1, 'n', 'n', 'n'...
oracle user defined delimiter in sql
[ "", "sql", "oracle", "oracle11g", "" ]
I´m trying to create a procedure that has a parameter called m\_reaplicacao. This parameter receives the values 'S' for Yes, 'N' for No and 'T' for all records. When the parameter is Yes, I should return the records with value equals to 9. When the parameter is No, I should return the records different of 9. And finall...
Don't use a `CASE` statement in a `WHERE` clause when you really want a simple combination of boolean evaluations. ``` WHERE ta.estado = 'RJ' AND ( m_reaplicacao = 'T' OR (m_reaplicacao = 'S' AND ta.id_1a_cbr = 9) OR (m_reaplicacao = 'N' AND ta.id_1a_cbr <> 9) ) ``` If for some reason you rea...
You cannot return expressions in `CASE` statements, easiest to add additional `WHERE` criteria sets: ``` select * from proposta ta where ta.estado = 'RJ' and ( (m_reaplicacao = 'S' AND ta.id_1a_cbr = 9) OR (m_reaplicacao = 'N' AND ta.id_1a_cbr <> 9) ) ``` Not sure what you want to happen in t...
Using case inside where clause
[ "", "sql", "oracle", "plsql", "" ]
Basically I have an application that processes transactions. Each transaction has a transaction number. In the application view on the front the total for each transaction is calculated but it is not stored in the database (and this cannot be changed) Now in SSRS they want to see the value come through on the report. ...
[Window functions](http://msdn.microsoft.com/en-us/library/ms189461.aspx) are just so much more fun though: ``` SELECT TransactionId , Value , SUM(Value) OVER(PARTITION BY TransactionId) AS Total FROM SomeTable ``` [SQL Fiddle](http://sqlfiddle.com/#!3/667dca/1)
This should do the trick ``` select transactionID , value , TransactionSum from MyTable t join (select transactionID , sum (value) as TransactionSum from MyTable group by transactionID ) x on t.transactionID = x.transactionID ```
SSRS/T-SQL sum if another condition is met
[ "", "sql", "sql-server", "t-sql", "reporting-services", "" ]
I have a largish( 10's of millions of rows) SQL table, that lists attribute types, and attributes. I want to investigate the relationship between subsets (three or four at a time) of these attributes, for a given object. The objects may have some, all, or none, of the attributes that I'm interested in. If it has none o...
Try something like this... ``` select distinct base.id, Att1.AttributeValue as Attribute1, Att2.AttributeValue as Attribute2, Att3.AttributeValue as Attribute3, Att4.AttributeValue as Attribute4 from Attributes base left join Attributes Att1 on base.id = Att1.id and Att1.AttributeType = 1 left jo...
You may want to use SQL-Server's "Pivot" functionality ([http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx](http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx)) I think the syntax for your example would be: ``` SELECT Id, [01], [02], [04], [15], [06] from (SELECT Id, AttributeTy...
Select Null From A Table When Records May Not Exist
[ "", "sql", "sql-server", "join", "" ]
Looking to find all rows where a certain json column contains an empty object, `{}`. This is possible with JSON arrays, or if I am looking for a specific key in the object. But I just want to know if the object is empty. Can't seem to find an operator that will do this. ``` dev=# \d test Table "public.test" Co...
There is **no equality (or inequality) operator** for the data type **`json`** as a whole, because equality is hard to establish. Consider [**`jsonb`**](https://www.postgresql.org/docs/current/datatype-json.html) in Postgres 9.4 or later, where this is possible. More details in this related answer on dba.SE (last chapt...
Empty JSON array `[]` could also be relevant. Then this could work for both `[]` and `{}`: ``` select * from test where length(foo::text) > 2 ; ```
How to query a json column for empty objects?
[ "", "sql", "json", "postgresql", "types", "jsonb", "" ]
I am using below mentioned code when I tried to connect with SQL server. I am geeting Login failed for user 'domain\username'. I have checked that the user having sysadmin permission in SQL Server & I am using SQL server Express edition. connection string I used for this "Initial Catalog=Employee;Server=serverName" `...
Typically, when you add a Login to Sql Server, there are 2 modes. Sql Server Authentication (which is the "old school" user-name and pwd scenario) and "Windows Authentication". which is where you find a user (domain\username) on your network and add the login. THIS SCENARIO DOES NOT REQUIRE A PASSWORD TO BE SET/SENT...
While you may have created the user did you add that particular user to your actual database? This tripped me up for a while after I inherited a demo that already had the user created. When I backed it up and restored it the user was not included and needed to be added back in. Here you can see the folder **Security*...
Error : Login failed for user 'domain\username' using SqlCredential object
[ "", "sql", "sql-server", "sqlconnection", "" ]
I need help with how to write an `SQL` statement. This what I am trying to say, this clearly is not `SQL` format but for purpose of understanding the request: ``` SELECT * FROM $A$ WHERE marketprovider_1 OR marketprovider_2 OR marketprovider_3 OR marketprovider4 OR marketprovider_5 CONTAIN ‘data’ AND...
Here's an example of valid SQL `WHERE` clause syntax that implements the predicates you described. ``` WHERE ( ( marketprovider_1 LIKE '%data%' AND marketprovider_1 LIKE '%tv%' ) OR ( marketprovider_2 LIKE '%data%' AND marketprovider_2 LIKE '%tv%' ) OR ( marketprovider_3 LIKE '%data%' AND marketprovider_3...
Try using : ``` marketprovider_1 like ('%data%') ``` Where the % is a wildcard. You can use NOT LIKE for the opposite. The IN clause you are using is for searching for lists of things. An example is: ``` marketprovider_1 in ('data','this','that') ```
SQL Query, Need help using "contains" and "does not contain"
[ "", "mysql", "sql", "" ]
I am trying to get all the values which exist in one table and not the other. The condition to join them is varchar in one table and bigInt in the other (swmItems is bigInt, OBJ\_TAB is varchar). I tried the following: ``` SELECT si.upc as upc from swmItems si left outer join dbo.OBJ_TAB obj on cast(obj.F01 as BIG...
``` SELECT swmItems.upc FROM swmItems LEFT JOIN OBJ_TAB ON CASE WHEN ISNUMERIC(OBJ_TAB.F01 + '.e0') = 1 -- ensure no decimals THEN CASE WHEN CONVERT(float, OBJ_TAB.F01) BETWEEN -9223372036854775808 AND 9223372036854775807 ...
You cannot convert any non-numeric value into integer datatype. but you can convert numeric value into varchar datatype. So, you can try like this. ``` SELECT si.upc as upc from swmItems si left outer join dbo.OBJ_TAB obj on obj.F01 = Cast(si.upc As Varchar) WHERE obj.F01 IS NULL ```
Convert varchar to bigInt including null values
[ "", "sql", "sql-server", "" ]
My SQL is very rusty. I'm trying to transform this table: ``` +----+-----+--------------+-------+ | ID | SIN | CONTACT | TYPE | +----+-----+--------------+-------+ | 1 | 737 | b@bacon.com | email | | 2 | 760 | 250-555-0100 | phone | | 3 | 737 | 250-555-0101 | phone | | 4 | 800 | 250-555-0102 | phone | | 5 ...
One way to approach this is conditional aggregation: ``` select min(ID), SIN, max(case when type = 'phone' then contact end) as phone, max(case when type = 'email' then contact end) as email from people t group by sin; ```
Seems a [pivot](http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html) (oracle.com) would work easily here. ``` SELECT ID, SIN, PHONE, EMAIL FROM PEOPLE PIVOT ( MAX(CONTACT) FOR TYPE IN ('EMAIL', 'PHONE') ) ```
Split column into two columns based on type code in third column
[ "", "sql", "oracle11g", "" ]
I am using a function to get total of a column field is : ``` ALTER FUNCTION [dbo].[GetTwoWeeklyWorkTime](@EmployeeID as int,@PayPeriodID as varchar(10)) RETURNS int AS BEGIN DECLARE @StartDate DATETIME DECLARE @EndDate DATETIME Select @StartDate=[PeriodStartDate],@EndDate=[PeriodEndDate] from PayPerio...
Well, you can *calculate* it as a `float` using ``` Sum(Cast([WorkingTime] as float))/60 ``` but you also need to change your function return value to `float`: ``` RETURNS float ```
`INT / INT` would result in an `INT`, even though result could be a fraction. Use this: ``` Sum([WorkingTime]) / 60.0 ```
Error converting Sum[Field] as numeric or float
[ "", "sql", "sql-server-2008", "sql-convert", "" ]
I have a table that has the names of the department, but if a department is not part of the count in the other table then I don't get the department name. How can I get the names of the departments who are not part of the CSEReduxResponses to display in the output with a 'branchtotalstarsgiven' of 0? Here are some te...
To get the expected result there are few changes to implement: * change the `JOIN` from `INNER` to `LEFT/RIGHT` * change the `WHERE` condition so that it will not remove the department not in `CSEReduxResponses` * change the `COUNT` so that it'll return 0 when the department is not in `CSEReduxResponses` the resultin...
AS I understood you need names of departements that don't figure in the second table : ``` SELECT csedept_id, csedept_name FROM CSEReduxDepts WHERE csedept_id NOT IN (SELECT distinct submitterdept FROM CSEReduxResponses) ```
How to get all names of a table column to show if its not part of another table?
[ "", "sql", "" ]
``` create table tab3(a integer,d1 datetime default getdate()) insert into tab3(a) values(1) insert into tab3 (a) select a from tab3 GO 20 insert into tab3 (a) select a from tab3 select d1,count(*) from tab3(NOLOCK) group by d1 ``` The final insert definitely takes a non trivial amount of time(3 seconds on my machine...
> When is a default value initialized? This depends on whether or not the expression is a "[runtime constant](http://blogs.msdn.com/b/conor_cunningham_msft/archive/2010/04/23/conor-vs-runtime-constant-functions.aspx)". To get your desired behaviour you can wrap the call in a scalar UDF. ``` CREATE FUNCTION dbo.F() R...
SQL is set-based, not row-by-row. The insert statement logically happens all-at-once so it is correct to assign the same value for all rows inserted by the statement. You might even get the same getdate value for different statements on a faster machine since getdate only has a precision of a millisecond with an accura...
When is a default value initialized?
[ "", "sql-server", "sql", "" ]
I'm new to Sql but what is the best way to insert more than 1000 rows from an excel document into my database(Sql server 2008.) For example I'm using the below query: ``` INSERT INTO mytable(companyid, category, sub, catalogueref) VALUES ('10197', 'cat', 'sub', '123'), ('10197', 'cat2', 'sub2', '124') ```...
Microsoft provides an [import wizard](http://msdn.microsoft.com/en-us/library/ms141209.aspx) with SQL Server. I've used it to migrate data from other databases and from spreadsheets. It is pretty robust and easy to use.
Just edit the data in Excel or another program to create N amount of insert statements with a single insert for each statement, you'll have an unlimited number of inserts. For example... ``` INSERT INTO table1 VALUES (6696480,'McMurdo Station',-77.846,166.676,'Antarctica','McMurdo') INSERT INTO table1 VALUES (3833...
Inserting more than 1000 rows from Excel into SQLServer
[ "", "sql", "sql-server", "sql-server-2008", "insert", "" ]
Here is some data: ``` record ------------------------------------------------- | id | name | ------------------------------------------------- | 1 | Round Cookie | | 2 | Square Cookie | | 3 | Oval Cookie ...
``` SELECT r.id, r.name FROM record r JOIN record_type_field rf ON rf.data_type = 'Color' LEFT JOIN record_type_data rd ON rd.record_id = r.id AND rd.type_id = rf.id ORDER BY rd.data ```
Have you tried using the SQL 'IN' clause. ``` select record.id as id, recordfield.data, recordtype.field_name from record left join record_field_data recordfield ON record.id = recordfield.record_id WHERE id IN (SELECT id FROM record_type_field where data_type='Color'); ``` The IN clause allows you to specify a list ...
Filtering data in left join
[ "", "mysql", "sql", "join", "" ]
**Background** Coming from a `mysql` background, I find getting started with Oracle quite a different experience. **Question** Where do I find this command tool for Oracle? I have checked [wikipedia](http://en.wikipedia.org/wiki/SQL%2aPlus) and it only says: > An Oracle programmer in the appropriately configured s...
You can locate the `sqlplus` executable in Windows by running in a CMD shell ``` dir /s /b c:\sqlplus.exe ``` Suppose you find the file at ``` c:\oracle\product\11.2.0\client_1\bin\sqlplus.exe ``` Then you have determined that your ORACLE\_HOME is: ``` c:\oracle\product\11.2.0\client_1 ``` Assuming the above ORAC...
Usually in $ORACLE\_HOME/bin and usually they suggest to run ``` . oraenv ``` to prepare your environment.
Where is Oracle sqlplus located?
[ "", "mysql", "sql", "oracle", "command-line", "sqlplus", "" ]
This may just be a Friday thing but I cant work out how to display these records as one line, my data looks like this ``` PTaskID Part Requisition Service Requisition 394512 Yes No 394512 No Yes ``` What I want is 1 row with the `PTaskID` but with the f...
Given that 'Yes' comes after 'No' (\*in most collations), you could `GROUP` and then do a `Max`, viz ``` SELECT PTaskID, MAX([Part Requisition]) as [MaxPartRequisition], MAX([Service Requisition]) as [MaxServiceRequisition] FROM [Load] GROUP BY PTaskID; ``` [SqlFiddle here](http://sqlfiddle.com/#!3/...
Try this ``` Select Ptaskid, case when sum(case when [Part Requisition] = 'Yes' then 1 else 0 end)> 0 then 'Yes' else 'No' end 'Part Requisition', case when sum(case when [Part Requisition] = 'Yes' then 1 else 0 end)> 0 then 'Yes' else 'No' end 'Service Requisition' from [Load] group by ptaskid ```
Grouping 2 lines in to 1
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to insert values into a table named EMPLOYEE\_PROGRAM\_LEVEL. Here are the column names I need to specify: ``` EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS ``` Before doing the insertion, I know only the employee name and the program name. LEVEL and MANAGE\_ACCESS are known constants that I need to hardco...
This should work for you: ``` INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS) SELECT ID, ID_PROGRAM,'9000', 'O' FROM EMPLOYEE T1 INNER JOIN PROGRAM T2 ON T2.NOM='programName' WHERE T1.USERNAME='userName' ```
You're almost there, just need to add the constants to the SELECT: ``` INSERT INTO EMPLOYEE_PROGRAM_LEVEL(EMPLOYEE_ID, PROGRAM_ID, LEVEL, MANAGE_ACCESS) SELECT ID, ID_PROGRAM, '9000', 'O' FROM EMPLOYEE T1 INNER JOIN PROGRAM T2 ON T2.NOM='programName' WHERE T1.USERNAME='userName' ```
MS SQL: INSERT values from another table and values from constant data
[ "", "sql", "sql-server", "" ]
I'm trying to join two tables based on the first two digits of UK Postcodes. The problem I have is that not all postcodes in my table start with two letters. For example: ``` Table 1 Birmingham B Bath BA Table 2 B5 5NR BA1 2BX ``` If I was to join using LEFT(Postcode,2) I would be excluding Birmingham. If I was...
You can try the following query, assuming that the second table contains a number after the postcode to which we need to cut off to extract the postcode. ``` SELECT Name,A.Code,B.Code,B.Val FROM table1 A JOIN table2 B ON A.Code =LEFT(B.Code,PATINDEX('%[0-9]%',B.Code)-1) ```
This will eliminate the last character of a string in SQL Server: ``` LEFT(Postcode,LEN(Postcode)-1) ```
SQL Joining on Different cell values
[ "", "sql", "" ]
Of all the SQL transpose questions using PIVOT and UNPIVOT I am yet to see one where you transpose a single row into columns. This is my query: ``` SELECT '' as Status, '' as "Count", sum(Created) as "Created", sum(Forwarded) as "Forwarded", sum(Replied) as "Replied" FROM ( SELECT CASE WHEN a.TO_WG_I...
## Test Data ``` DECLARE @TABLE TABLE ( [Status] VARCHAR(10) ,[Count] VARCHAR(10) ,Created INT ,Forwarded INT ,Replied INT ) INSERT INTO @TABLE VALUES ('', '', 1693 , 209 ,1499) ``` ## Query ``` ;WITH CTE AS ( SELECT * FROM ( SELECT Created, Forwarded, Replied FROM @TABLE --<-- Your...
You could just union them. ``` Select 'Created' as Status, Sum... as Count from... union all select 'Forwarded', Som... union all select 'Replied, sum... ```
SQL Transpose sum of field into columns
[ "", "sql", "sql-server", "transpose", "" ]
I have a quiz table ``` id | user_id | quiz_id -------------------------- 1 | 34567 | 12334 2 | 34567 | 12334 3 | 34567 | 23455 ``` id 1 and 2 depicts a quiz that can be assigned to the same user twice and a quiz transaction table ``` id | date | status ------------------------ 1 | 2014 | assigned 2...
How about simply using the `MAX()` function with `GROUP BY` ([**SQL Fiddle**](http://sqlfiddle.com/#!6/39ac3/1/0)): ``` SELECT q.id, q.user_id, q.course_id, qt.date, MAX(qt.status) AS Status FROM quiz q LEFT JOIN quiz_transaction qt ON q.id = qt.id GROUP BY q.id, q.user_id, q.course_id, qt.date ``` **EDIT:** If yo...
Depending on your release SQLnServer supports Standard SQL's "Windowed Aggregate Functions". ROW\_NUMBER will give you a single row: ``` SELECT q.id ,q.user_id ,q.quiz_id ,qt.date ,qt.status FROM quiz q JOIN ( SELECT id ,date ,status ,ROW_NUMBER() OVER (PARTITION BY id ...
Select one row from non unique rows based on row value
[ "", "sql", "sql-server", "subquery", "case", "conditional-statements", "" ]
I have a few large tables in a oracle DB (lots of columns and data types) that I need to move to another oracle database (say from my DEV region to UAT region). Is there anyway I can get sql developer or sql plus to output a create table statement that is exactly the structure of the existing table? thanks
If you are making use of the SQL Developer you can right click the table that you want to generate a script for. From there select Quick DDL and then click on Save To File. This will then generate the create table script to an external sql file. You can do this for multiple tables as well by selecting more than one ta...
If you want to get it through SQL statement then you can try the below query ``` SELECT dbms_metadata.get_ddl('TABLE', 'Your_Table_Name') FROM dual; ``` See [DBMS\_METADATA](http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_metada.htm) for more information. You can generate the script using Toad software as we...
generate create table from existing table
[ "", "sql", "oracle", "" ]
I have been working on this query for some time now, and reading `right join` question after `right join` question here on SO, but I cannot figure this one out. I have the following Query: ``` DECLARE @ExpectedDateSample VARCHAR(10) DECLARE @Date datetime DECLARE @DaysInMonth INT DECLARE @i INT --GIVE VALUES SET @Ex...
Change your `where` clause to part of the join, and display the day value from `#tempdays`, not the data table ``` SELECT #TempDays.days ExpectedDate, SUM(a.budg_do1_total) ExpectedAmount FROM CRM.dbo.budget a RIGHT JOIN #TempDays on DATEPART(DD, CONVERT(DATE, a.budg_tempDODate1, 103)) = #TempDays.days ...
The problem is your Where Clause - > WHERE DATEPART(MONTH, a.budg\_tempDODate1) = DATEPART(MONTH, GetDate()) AND DATEPART(YEAR, a.budg\_tempDODate1) = DATEPART(YEAR, GetDate())
SQL not delivering expected result with RIGHT JOIN
[ "", "sql", "sql-server", "right-join", "" ]
These numeric values needs to be converted into date time. It is date of birth so the values can not be in the future. Can I somehow implement a rule that not accept date-of-birth where the value would equal to over 100 years old?? 201246-1324 040210-6387 111257-0647 040210-6387 Result: **2046-12-20 00:00:00.000 - W...
Temporarily change your cutoff, since you're working with DOBs which are always in the past.. ``` sp_configure 'two digit year cutoff', 2015 reconfigure ``` Then use a standard datediff on years < 100.
You can use the datediff function in an if statement for this circumstance i believe Essentially, if the time between the two dates being compared is greater than 100 years then do not insert the record <http://www.w3schools.com/sql/func_datediff.asp>
Wrong (future) convert to datetime
[ "", "sql", "date", "datetime", "type-conversion", "" ]
I have a stored procedure and I cant work out how the string is meant to be built up. The SQL statement works fine when I do not have a variable in there so it is definitely the way I am writing it in. I am just a beginner so unsure about the syntax. Here is the code: ``` CREATE PROCEDURE [dbo].[SP_SLINVOICE] @varCU...
Your SQL is ending up like this: ``` WHERE dbo.InvMaster.InvCurrency = '@varCURRENCY' ``` So you are not looking for the value of the parameter, you are looking for `@Currency`, I am not sure why you are using Dynamic SQL, the following should work fine: ``` CREATE PROCEDURE [dbo].[SP_SLINVOICE] @varCURRENCY AS VA...
If you want to pass a variable to an `sp_executesql` context, you need to pass it as a parameter. ``` EXECUTE sp_executesql @sql, N'@varCurrency varchar(3)', @varcurrency= @varCurrency; ``` <http://msdn.microsoft.com/en-gb/library/ms188001.aspx> Although why you don't just use ``` sel...
SQL Stored Procedure WHERE CLAUSE Variable
[ "", "sql", "sql-server", "sql-server-2008", "variables", "stored-procedures", "" ]
I currently have some SQL that is used to create an excel report in the following format: ``` COL1 COL2 COL3 2 1 8 3 7 9 1 2 4 ``` Now what I am trying to do is sum up the total of these each value and insert it at the bottom using `UNION ALL` (unless of course the...
It looks like you want to add ``` WITH ROLLUP ``` to the end of your query eg: ``` Select sum(a) as col1, sum(b) as col2 from yourtable group by something with rollup ``` Depending on the full nature of your query, you may prefer to use `with cube`, which is similar. See [http://technet.microsoft.com/en-us/librar...
``` select col1 ,col2 ,col3 from tableA union select sum(col1) ,sum(col2) ,sum(col3) from tableA order by col1,col2,col3 ```
Create SQL summary using union
[ "", "sql", "sql-server", "union", "" ]
I'm trying to make a listing for **Ageing Transaction** where areas the list will have 0-30 days column and 31-60 days column. If transaction date is within 30 days, then its in 0-30 days column, if it's within the range of 31-60 then it's inside 31-60 days column. So to make it more clear, here's the table ``` |tra...
Here is a better approach: ``` SELECT d.customer, CASE WHEN DATEDIFF(c.trans_date, d.trans_date) <= 30 THEN d.debit ELSE 0.0 END AS `0-30`, CASE WHEN DATEDIFF(c.trans_date, d.trans_date) > 30 AND DATEDIFF(c.trans_date, d.trans_date) <= 60 THEN d.debit ELSE 0.0 END AS `31-60` FROM table AS d INNER JOIN ta...
``` SELECT t.customer, SUM(c1.credit) AS `0-30`, SUM(c2.credit) AS `31-60`, FROM table AS t LEFT JOIN table AS c1 ON c1.debit = t.credit AND DATEDIFF(t.trans_date, c1.trans_date) <= 30 LEFT JOIN table AS c2 ON c2.debit = c2.credit AND DATEDIFF(t.trans_date, c2.trans_date) > 30 DATEDIFF(t.trans_date, c2.trans_dat...
SQL - Compare Date in a same Columnn
[ "", "mysql", "sql", "" ]
I am trying to concatenate multiple columns in a query in SQL Server 11.00.3393. I tried the new function `CONCAT()` but it's not working when I use more than two columns. So I wonder if that's the best way to solve the problem: ``` SELECT CONCAT(CONCAT(CONCAT(COLUMN1,COLUMN2),COLUMN3),COLUMN4) FROM myTable ``` I c...
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical `CONCAT()` function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it. An alternative: ``` SELECT '1'+'2'+'3' ``` This approach requires non-string values to ...
``` SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME) INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’) FROM EMPLOYEES WHERE HIRE DATE = 1995 ```
SQL Server: Best way to concatenate multiple columns?
[ "", "sql", "sql-server-2012", "" ]
Having Table1 ``` id | productname | store | price ----------------------------------- 1 | name a | store 1 | 4 2 | name a | store 2 | 3 3 | name b | store 3 | 6 4 | name a | store 3 | 4 5 | name b | store 1 | 7 6 | name a | store 4 | 5 7 |...
Try this ``` select p.* from Table1 as p inner join (SELECT ProductName, MIN(Price) AS minPrice FROM Table1 GROUP BY ProductName) t on p.productname = t.ProductName and p.price = t.minPrice ```
You didn't mention your SQL dialect, but most DBMSes support Standard SQL's "Windowed Aggregate Functions": ``` select * from ( select t.*, RANK() OVER (PARTITION BY ProductName ORDER BY Price) as rnk from table1 as t ) as dt where rnk = 1 ``` If multiple stores got the same lowest price all of them w...
Select columns with and without group by
[ "", "sql", "" ]
I'm using the hortonworks's Hue (more like a GUI interface that connects hdfs, hive, pig together)and I want to load the data within the hdfs into my current created table. Suppose the table's name is "test", and the file which contains the data, the path is: /user/hdfs/test/test.txt" But I'm unable to load the data i...
As you said "**load the data within the hdfs into my current created table**". But in you command you are using : load data **local** inpath '/user/hdfs/test/test.txt' into table test Using **local** keyword it looks for the file in your local filesystem. But you file is in **HDFS**. I think you need to remove **loc...
Since you are using the hue and the output is showing not matching path. I think you have to give the complete path. for example: load data local inpath '/home/cloudera/hive/Documents/info.csv' into table tablename; same as you can give the complete path where the hdfs in which the document resides. You can use any oth...
How to load data into Hive table
[ "", "sql", "hive", "" ]
I have a `Dossiers` table with a `print_flag` column and i want set `print_flag`=1 for multiple rows. ``` UPDATE dossiers SET print_flag = 1 WHERE id=1013997,id=1020799,id=1020800,id=1020800; ``` How should the SQL look like?
You should use the IN clause as it'll allow you to use multiple values for a single column. ``` UPDATE dossiers SET print_flag = 1 WHERE id IN(1013997, 1020799, 1020800); ```
You need `IN` clause as: ``` UPDATE dossiers SET print_flag = 1 WHERE id IN (1013997,1020799,1020800,1020800); ```
SQL update multiple rows based on multiple where conditions
[ "", "sql", "sql-server", "" ]
Been scratching my head for a while on this one and despite trying many variations I cannot see the mistake. After writing the app file, which contains what looks like the correct DataMapper.setup code for using PostgreSQL (?), and upon trying to play around in IRB/PRY, i just get a 'FATAL database not created' message...
You need to do this in command line: ``` psql ``` and then ``` CREATE DATABASE development; ``` before even trying to run Data Mapper setup code.
Perhaps you are missing this line: DataMapper.auto\_upgrade!
PostgreSQL & DataMapper issues
[ "", "sql", "sqlite", "postgresql", "sinatra", "" ]
I am experiencing an interesting problem with a NULL value in the following table: ``` CREATE TABLE dbo.STAFF ( staffID int PRIMARY KEY NOT NULL, lastname varchar(50) NULL, firstname varchar(50) NULL, pay money NULL, supervisorID int NULL ) INSERT INTO STAFF (staffID, lastname, firstname, pay, supervisorID) VALUES ...
You have to use a LEFT JOIN. I think if join type isn't give INNER JOIN is default.
You can try this: ``` SELECT (a.firstname + ' ' + a.lastname) AS "Employee Name", CASE WHEN a.supervisorID IS NOT NULL THEN (b.firstname + ' ' + b.lastname) ELSE 'No supervisor' END AS "supervisor Name" FROM dbo.STAFF a LEFT JOIN dbo.STAFF b WHERE a supervisorID= b.staffID; ```
SQL Server: CASE ignoring rows with NULL values within SELF JOIN
[ "", "sql", "sql-server", "" ]
I am a new learner in Netezza. Right now, I wanna write a sql statement to feedback the recent data objects corresponding to a defined recent date. Like return the data objects after 2014-06-10. Or return the objects before a certain date. Like return the data objects before 2014-03-10. How to do that? The attribute in...
You can compare the date or timestamp field to a date created with an explicit call to the to\_date function, or you can simply compare it to a character literal of the date in a format that the compiler will recognize and implicitly cast to a date. For example: ``` TESTDB.ADMIN(ADMIN)=> select * from date_test; ...
Netezza has built-in function for this by simply using: ``` SELECT DATE(STATUS_DATE) AS DATE, COUNT(*) AS NUMBER_OF_ FROM X GROUP BY DATE(STATUS_DATE) ORDER BY DATE(STATUS_DATE) ASC ``` This will return just the date portion of the timetamp and much more useful than casting it to a string with "TO...
How to compare dates in Netezza?
[ "", "sql", "netezza", "" ]
I have two tables my database. One is a list of drivers and one is a list of violations. Each violation has a status, either yellow or red and I need to count the number of yellow violations and red violations that a particular driver has and ORDER BY either red or yellow ASC or DESC. Drivers Table: AutoID (primary ke...
Sounds like you want to group by driver and violation color: ``` SELECT d.autoID, v.status, COUNT(v.status) FROM edsp_drivers d LEFT JOIN edsp_violations v ON d.autoID = v.driverID AND (v.status = 'yellow' OR v.status='red') WHERE d.employerID = '000000028' GROUP BY d.autoID, v.status ORDER BY v.status ASC,...
Try: ``` SELECT d.autoID , SUM( CASE WHEN v.status = 'yellow' THEN 1 ELSE 0 END) as Yellow_Count , SUM( CASE WHEN v.status = 'red' THEN 1 ELSE 0 END) as Red_Count FROM edsp_drivers d, edsp_violations v WHERE d.employerID='000000028' AND d.autoID=v.driverID AND (v.status = 'yellow' OR v.status='red') GROUP ...
SQL Query to COUNT all rows with duplicate values broken down by primary key
[ "", "mysql", "sql", "count", "" ]
I have 3 models: ``` class Student < ActiveRecord::Base has_many :student_enrollments, dependent: :destroy has_many :courses, through: :student_enrollments end class Course < ActiveRecord::Base has_many :student_enrollments, dependent: :destroy has_many :students, through: :student_enrollments end cla...
You can pass a string that is the join-sql too. eg `joins("LEFT JOIN StudentEnrollment se ON c.id = se.course_id")` Though I'd use rails-standard table naming for clarity: ``` joins("LEFT JOIN student_enrollments ON courses.id = student_enrollments.course_id") ```
If anyone came here looking for a generic way to do a left outer join in Rails 5, you can use the [`#left_outer_joins`](http://guides.rubyonrails.org/active_record_querying.html#left-outer-joins) function. Multi-join example: Ruby: ``` Source. select('sources.id', 'count(metrics.id)'). left_outer_joins(:metrics). ...
LEFT OUTER JOIN in Rails 4
[ "", "sql", "ruby-on-rails", "ruby-on-rails-4", "rails-activerecord", "mysql2", "" ]
I have a table set up that tracks changes to a user's account. It has `ID`, `UserAccountNo`, `OldVal`, `NewVal`, `ChangeColumnName` columns. I have a query set up similar to this: ``` Select case when ChangeColumnName = 'Address1' then NewVal else '' end as Address1, when ChangeColumnName = 'Address2' t...
Try this ``` create table #t ( id int, userAccountNo int, oldVal varchar(255), newVal varchar(255), changeColName varchar(255) ); insert #t values (1, 1, '123 main st', '123 s. main st.', 'Address1'), (2, 1, 'Springville', 'Springfield', 'City'), (3, 1, 'Springfield', 'N. Springfield', 'City'), (4, 2, '12345', ...
I suggest that you use pivot command, use this script and let me know : ``` IF OBJECT_ID('_temp') IS NOT NULL DROP TABLE _temp SELECT * INTO _temp FROM ( Select 'PostalCode' AS ChangeColumnName, '95100' AS NewValue UNION ALL Select 'City' AS ChangeColumnName, 'Argenteuil' AS NewValue UNION ALL ...
SQL Merge Data into Single Row
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Query should output a certain list of Items, along with info like store information and manager info. Uses a Cursor to flip through list of various different levels of management, selects relevant information, then emails that person what the query returned for their district/region/store. My issue is with the SSIS le...
Recheck column assignment between source and destination and in-between component as well. Give it a try by setting data flow component's Properties, ValidateExternalMetadata to False. Please have a look of [this](https://stackoverflow.com/questions/8656287/the-external-column-y-col1-598-needs-to-be-removed-from-the-...
It seems like you were changing the OLEDB Source or other type of source recently. Thus, you must delete OLEDB Source and create a new one again. Then also delete the mapping of particular field, save, go back to mapping again and map it back. Than it should work fine.
SSIS Error: External Column for Source out of sync with Data Source columns; How do I remove External Columns?
[ "", "sql", "sql-server", "t-sql", "ssis", "" ]
i have the following query to find the rank ``` SELECT a.appName,RANK() OVER (PARTITION BY a.appName, b.depName ORDER BY a.appName) as RANK,b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a inner join tbl_users b on b.userName = a.userName where a.date_time between '01-JUN-12' and '20-JUN-14...
Try below query: ``` SELECT a.appName, RANK() OVER (PARTITION BY a.appName ORDER BY b.depName) as RANK, b.depName,Count(distinct a.userName) as visitors FROM tbl_app_webstats a inner join tbl_users b on b.userName = a.userName where a.date_time between '01-JUN-12' and '20-JUN-14' and a.appName like '%' group by a...
Maybe something like this: ``` SELECT a.appName,RANK() OVER (PARTITION BY a.appName ORDER BY b.depName) ...... ``` You could also do this: ``` SELECT a.appName,ROW_NUMBER() OVER(PARTITION BY a.appName ORDER BY b.depName) ...... ``` To address you comment. You could do something like this: ``` WITH CTE AS ( SE...
finding rank with two columns oracle
[ "", "sql", "oracle", "" ]
I've a very big query, that in the end I've to ORDER BY some criterias. The main table of the query has about 1 500 000 rows, and I've a lot of JOIN statements. When I run the query it takes more than 9 minutes, when a run the EXPLAIN SELECT, it was clear it is the "ORDER BY" Clause, that takes a lot of time. The colum...
Here is a workaround, for those that have no time to solve the problem. Just wrap the big query, and then make a ORDER BY.
The reason behind this is that your query is not using any of that table's indexes. > For a query that requires scanning a large fraction of the table, an explicit sort is likely to be faster than using an index because it requires less disk I/O due to following a sequential access pattern. Indexes are more useful whe...
Postgresql ORDER BY of indexed columns is slow
[ "", "sql", "postgresql", "" ]
I have a scenario ``` Key Name Amt 101 Nikh 100 101 Mark 150 101 Jess 75 102 Sam 200 102 Lee 150 ``` Observe that Key is same for multiple records. Also it is coming from a different table than Name and Amt. I want to returns records havig minimum Amt. Below is the eg.: ``` Key Name Amt 101 Jess 75 102 Lee ...
You should approach this using `row_number()`: ``` select [key], name, amt from (select t.*, row_number() over (partition by [key] order by amt asc) as seqnum from table t ) t where seqnum = 1; ```
Classic question and answer ``` ;WITH CTE as ( SELECT row_number() over (partition by [Key] order by Amt) rn, [Key], Name, Amt FROM <table> ) SELECT [Key], Name, Amt FROM CTE WHERE rn = 1 ``` Edit: If, in case of ties, you want to show all results with the lowest Amt, replace `row_number()` with `ra...
Return rows with column having min value
[ "", "sql", "sql-server", "reporting-services", "ssrs-2008", "" ]
I am trying to pass a complete query to source qualifier of Informatica powercenter Designer. Since the query is large I cannot parameterize it (limitations of UNIX also comes here). So, is there a way I can refer and run a query without hardcoding it inside Informatica, and get the result in Informatica. Any help!!
You can put the query in a view and reference it in the parameter.
You can create a pipeline function or table function and Use that in SQ Override. They have advantage over views where you can pass in parameters to the Function.
Pass a query to informatica
[ "", "sql", "teradata", "informatica", "informatica-powercenter", "" ]
In the code below I am inserting values into a table and getting the error "String or binary data would be truncated." My table definition: ``` CREATE TABLE urs_prem_feed_out_control ( bd_pr_cntl_rec_type char(7) NULL , pd_pr_cntl_acctg_dte char(6) NULL , bd_pr_cntl_run_dte char(10) NULL , bd_pr_cntl_start_dte...
The problem with your insert query is *THE ORDER OF INSERTION* : ``` SELECT fd_ctl_nbr = @cur_fd_ctl_nbr, ``` This column must be defined at the last in the `INSERT` as its the last column defined in the create table script. Change your query to this: ``` INSERT INTO #urs_prem_feed_out_control (fd_ctl_nbr, bd_pr...
This is why you should never write an insert statement without specifying the columns. Since you did not, it wil try to put the data in the columns in the order they are in the table which is not at all the order you have them in. Another thing that can happen when you get this sort of message (but which I don't think...
TSQL error on insert "String or binary data would be truncated"
[ "", "sql", "sql-server", "t-sql", "insert", "truncate", "" ]
I am struggling with a select query I'm trying to create to join two tables which has a 1 to many row ratio. ### Core Table ``` id | client_id | vehicle_code | risk | .... --------------------------------------------------------------------- 20 | 2 | C2E | There ...
You can do that with a subquery instead of a join ``` SELECT * FROM core_table WHERE NOT EXISTS ( SELECT LTEQR_id FROM secondary_table WHERE LTEQR_id = core_table.id AND subsequent_payments IS NULL) ``` Another way would be to `GROUP BY` and use a `CASE`: you would group the records from ...
You want to select records from a table where exists or not exists a record in another table. So use an EXISTS clause rather than joining the tables. EDIT: You can also use an IN clause.
SQL table join selection
[ "", "sql", "" ]
So, i've got a query (which i use as a Stored Procedure) in SQL Server 2008 R2. It works, but i cannot believe there isn't a more efficient way. The data is in a table 'ServiceInstance'. This is one, completely flat table containing **16** 'instances' per IPAddress, each of them having a unique TCPPort for that IPAddr...
``` WITH UnAvailableCpus AS ( SELECT IpAddress ,CpuId FROM ServiceInstance WHERE IsAvailable = 0 GROUP BY IpAddress ,CpuId ) ,AvailableInstances AS ( SELECT ServiceInstanceId ,LastRequestDate FROM ServiceInstance LEFT JOIN UnavailableCpus ON ...
It may be related with the structure of the table (if you post it we can further elaborate). Best guess is to create indexes for any column used for joins, if not already done: * CpuId * IpAddress * IsInUse Also not bad to create indexes for columns used for where conditions: * IsAvailable * IsEnabled Anyway, this...
SQL query improved performance needed (1 table)
[ "", "sql", "sql-server", "" ]
I have the following table: ``` | ID | Name | DateA | TimeToWork | TimeWorked | |:--:|:----:|:----------:|:----------:|:----------:| | 1 |Frank | 2013-01-01 | 8 | 5 | | 2 |Frank | 2013-01-02 | 8 | NULL | | 3 |Frank | 2013-01-03 | 8 | 7 | | 4 |Jules | 2013-0...
If I understand the question right, than Gordon Linoff's answer is a good beginning, but doesn't deal with "full day off". ``` select Name, sum(case when month(DateA) = 01 and TimeWorked is null then 1 else 0 end) as Jan, sum(case when month(DateA) = 02 and TimeWorked is null then 1 else 0 end) as Feb, ...
The correct syntax is conditional aggregation: ``` select name, sum(case when month(datea) = 1 then timeworked else 0 end) as Jan, sum(case when month(datea) = 2 then timeworked else 0 end) as Feb, . . . sum(case when month(datea) = 12 then timeworked else 0 end) as Dec, sum(timework...
Get Month columns from datetime column and count entries
[ "", "sql", "t-sql", "" ]
I am tring to execute the below code... ``` select a.name, a.phone, b.mobile, b.relation, case when a.phone<>'' and b.mobile<>'' then a.phone + ' ' + b.mobile when a.phone<>'' and b.mobile='' then a.phone when a.phone='' and b.mobile<>'' then b.mobile else '' end as phone from abc a join bcdb where a.id=b.id and...
Since you are using MySQL, you've got to use the [CONCAT](https://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat) function to concatenate your strings, not the `+` operator. ``` select a.name, a.phone, b.mobile, b.relation, case when a.phone<>'' and b.mobile<>'' then CONCAT(a.phone, ' ', b....
**UPDATED**: You seem to be storing phone and mobile columns as numbers. SO you'll have to convert them to strings for concatenation. Try this: ``` CONVERT(a.phone, CHAR) + ' ' + CONVERT(b.mobile, CHAR) ``` So your query effectively becomes this: ``` select a.name, a.phone, b.mobile, b.relation, case when a.phone<...
concatenation in sql not working as expected
[ "", "mysql", "sql", "concatenation", "" ]
I have two tables that I need to combine into one query (bad software), from tables with different schema. I can fake one table easily to take care of the schema differences but the kicker is that I only want a subset of rows from the second table based on (joined with) info from the first table. My last resort is maki...
``` SELECT id,name,awesomeness from Cats where color = 'blue' UNION SELECT cat_id,null,badness from BadCats where cat_id in ( SELECT id from Cats where color = 'blue') and color = 'blue ```
This doesn't need to be a UNION, this is simply an outer join. ``` SELECT id, name from Cats c LEFT OUTER JOIN BadCats bc on bc.cat_id=c.id WHERE c.color = 'blue' ``` You get all the blue cats from Cats, whether there is a matching bc.cat\_id or not. Then *if* there is a matching row in BadCats with the same id, it...
In MySQL, can I SELECT with UNION but limit the rows from the second query based on the first query?
[ "", "mysql", "sql", "union", "mysql-5.5", "" ]
I am developing an stateless API that needs to support pagination. I use an Oracle database. I use Spring with MyBatis for database access. From the documentation, I understand that I can use the RowBounds class to limit the number of rows returned by the query. However, it seems that there's no special optimization...
`Mybatis` leaves many things up to the `SQL driver` that is being used, and it appears the exact behavior surrounding`RowBounds` is one of those. See <http://mybatis.github.io/mybatis-3/java-api.html>, particularly the section that says: > Different drivers are able to achieve different levels of efficiency > in this...
I found a simple work around to this issue. I had followed the Mybatis instructions @khampson recommended and was passing a RowBounds instance to the mapper with no limits being enforced. ``` RowBounds rowbounds = new RowBounds(0, resultLimit); roster = tableMapper.selectAll(rowbounds); ``` mapper java ``` public Li...
MyBatis RowBounds doesn't limit query results
[ "", "sql", "spring", "oracle", "mybatis", "" ]
TSQL Says : Invalid Column Name 'VehicleId' ``` SELECT (SELECT dbo.Vehicles.Id FROM dbo.Vehicles JOIN dbo.Movements ON dbo.Vehicles.Id=dbo.Movements.VehicleId WHERE dbo.Movements.Id=dbo.Alarms.MovementId) As VehicleId FROM [dbo].[Alarms] WHERE VehicleId =1 ``` What is the problem ?
I think, you are looking for something like this: ``` SELECT Alarms.* FROM dbo.Vehicles JOIN dbo.Movements ON dbo.Vehicles.Id=dbo.Movements.VehicleId JOIN dbo.Alarms ON dbo.Movements.Id=dbo.Alarms.MovementId WHERE VehicleId =1 ```
The table `Alarms` does not have a column named `VehicleId` The where clause does not use the alias ``` SELECT (SELECT dbo.Vehicles.Id FROM dbo.Vehicles JOIN dbo.Movements ON dbo.Vehicles.Id=dbo.Movements.VehicleId WHERE dbo.Movements.Id=dbo.Alarms.MovementId) As VehicleId FROM [dbo].[Alarms] WHERE VehicleId = 1...
SQL Subquery, Invalid Column Name
[ "", "sql", "sql-server", "" ]
Table data looks like: ``` EventID | MPID | rundate | Horizon | otherData 1 | 1 | 23-Jun-2014 | 360 | other value 1 | 1 | 23-Jun-2014 | 365 | pther value 1 | 1 | 23-Jun-2014 | 300 | pther value 1 | 1 | 22-Jun-2014 | 700 | pther value 1 | 2 | 23-Jun-2...
Try this query ``` Select T.* From Tbl T JOIN ( Select Max(S.Horizon) MaxHorizon,Max(S.rundate) As dte,S.EventID,S.MPID From Tbl S Join ( Select T1.EventID,Max(T1.rundate) As Maxrundate,T1.MPID From Tbl T1 Group By T1.EventID,T1.MPID ) JR On S.rundate = JR.Maxrundate AND S.EventID = J...
The proper way... ``` SELECT x.* FROM dsie_result_overalls x JOIN ( SELECT a.eventid , a.mpid , a.rundate , MAX(a.horizon) max_horizon FROM dsie_result_overalls a JOIN ( SELECT eventid , mpid , MAX(rundate...
Query to find result with max rundate with max horizon
[ "", "mysql", "sql", "max", "" ]
I have a long running report written in SQL\*Plus with a couple of SELECTs. I'd like to change the transaction isolation level to get a consistent view on the data. I found two possible solutions: ``` SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; ``` and ``` SET TRANSACTION READ ONLY; ``` Which one do I use for a r...
This article from the Oracle documentation gives a lot of detailed info about the different transaction isolation levels. <http://docs.oracle.com/cd/B10501_01/server.920/a96524/c21cnsis.htm> In your example, it sounds like you are wanting `Serializable`. Oracle does not block when reading data, so using serializable i...
In Oracle, you can really choose between `SERIALIZABLE` and `READ COMMITTED`. `READ ONLY` is the same as serializable, in regard to the way it sees other sessions' changes, with the exception it does not allow table modifications. With `SERIALIZABLE` or `READ ONLY` your queries won't see the changes made to the datab...
For a long running report, do I use a read only or serializable transaction?
[ "", "sql", "oracle", "" ]
This is the result of separating a single table in two: ``` Table users: user_id (pk, ai) email password last_login Table data: user_id (fk to users.user_id) data_1 data_2 ``` To select a single record when there was only one table: ``` SELECT users.email, users.password, data.data_1, da...
Using explicit `join` syntax could help you. Rewrite your query to: ``` SELECT users.email, users.password, data.data_1, data.data_2 FROM users INNER JOIN data ON users.user_id=data.user_id WHERE users.email='$user_email' ``` and get all rows without a WHERE condition: ``` SELECT users....
have you tried this? ``` SELECT users.email, users.password, data.data1, data.data2 FROM users,data WHERE users.user_id=data.user_id ``` or this? ``` SELECT users.email, users.password, data.data1, data.data2 FROM users inner join data on users.user_id=data.user_id ```
How to get all data from 2 tables using foreign key
[ "", "mysql", "sql", "" ]
I know the importance of indexes and how order of joins can change performance. I've done a bunch of reading related to multi-column indexes and haven't found the answer to my question. I'm curious if I do a multi-column index, if the order that they are specified matters at all. My guess is that it would not, and tha...
When discussing multi-column indexes, I use an analogy to a telephone book. A telephone book is basically an index on last name, then first name. So the sort order is determined by which "column" is first. Searches fall into a few categories: 1. If you look up people whose last name is Smith, you can find them easily ...
The two indexes are different. This is true in MySQL and in other databases. MySQL does a pretty good job of explaining the different in the [documentation](http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html). Consider the two indexes: ``` create index idx_lf on name(last_name, first_name); create in...
Does Order of Fields of Multi-Column Index in MySQL Matter
[ "", "mysql", "sql", "performance", "indexing", "" ]
I have a "stock market" data table with `contract` values. I want to get the volume (number of trades executed per day), and the close price, with the close price being the last recorded contract price that trading day. ``` CREATE TABLE IF NOT EXISTS `contracts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `price` deci...
One solution is to use a sub-query to get that price ``` SELECT count(ctr.id) as volume, (SELECT cc.price FROM contracts as cc WHERE DATE(cc.created_at) = DATE(ctr.created_at) ORDER BY cc.created_at DESC LIMIT 1) as price, DATE(ctr.created_at) FROM `contracts` as ctr GROUP B...
``` SELECT id, count(id) AS volume, DATE(created_at), (SELECT price FROM `contracts` as innerContracts WHERE innerContracts.id = outerContracts.id ORDER BY created_at DESC LIMIT 1) FROM `contracts` AS outerContracts GROUP BY DATE(created_at) ```
SQL query with GROUP BY and conditions
[ "", "mysql", "sql", "group-by", "" ]
I have a table called `Users` which is currently holding data on both `Customers` and `Staff`. It has their names and emails and passwords etc. It also has a field called `TypeOfUserID` which holds a value to say what type of user they are .e.g Customer or Staff Would it be better to have two separate tables: `Custome...
# Short Answer: It depends. If your current needs are met, and you don't foresee this model needing to be changed for a long time / it would be easy to change if you had to, stick with it. # Longer answer: If staff members are just a special case of user, I don't see any reason you'd want to change anything about th...
Even they look similar, they are logically from different areas. You will never need a union between those tables. But as your application develops, you will need to add more and more specific fields for these tables and they will became more different than similar.
Does it follow best-practice DB design to mix staff and customer details in 1 table?
[ "", "sql", "sql-server", "" ]
I have a table that contains basically an error log. These errors arrive based on various factors and have various severities. I am trying to get a query put together the total of each severity per hour in a 24 hour period. I have it working, except for one small item. The results are sorted by the Hour, which always ...
Try this query. ``` select [Hour], ISNULL([Critical],0) as Critical, ISNULL([Major],0) as Major, ISNULL([Minor],0) as Minor, ISNULL([Warning],0) as Warning, ISNULL([Information],0) as Information, ISNULL([Critical],0) + ISNULL([Warning],0) + ISNULL([Major],0) + ISNULL([Minor],0) + ISNULL([Information],0) as [Tota...
``` (original query) ORDER BY CASE WHEN [Hour] >= DATEPART(HOUR, GETDATE()) THEN [Hour] ELSE [Hour] + 24 END ```
mssql calculate total by hour
[ "", "sql", "sql-server", "" ]
Given the following SQL ``` SELECT T1."PN" as "Part Number", T2."QTY" as "Quantity", T2."BRANCH" AS "Location", T3."STOCK" as "Bin" FROM "XYZ"."PARTS" T1, "XYZ"."BALANCES" T2, "XYZ"."DETAILS" T3 WHERE (T2."PART_ID" = T1."PART_ID") AND (T3."PART_ID" = T1."PART_ID") ORDER BY "Part Number" ASC, ...
For older versions, I guess **WM\_CONCAT** would work. Modifying Gordon Linoff's query: ``` SELECT T1."PN" as "Part Number", max(T2."QTY") as "Quantity", T2."BRANCH" AS "Location", WM_CONCAT(T3."STOCK") as Bins FROM "XYZ"."PARTS" T1 JOIN "XYZ"."BALANCES" T2 ON T2."PART_ID" = T1."PART_ID" JOIN "XY...
You can do this in Oracle using `listagg()`: ``` SELECT T1."PN" as "Part Number", max(T2."QTY") as "Quantity", T2."BRANCH" AS "Location", listagg(T3."STOCK") within group (order by t3.stock) as Bins FROM "XYZ"."PARTS" T1 JOIN "XYZ"."BALANCES" T2 ON T2."PART_ID" = T1."PART_ID" JOIN "XYZ"."DETAILS...
How to group multiple values into a single column in SQL
[ "", "sql", "sql-server", "oracle", "" ]
i am having problem with a sql search . i am trying to search with the help of datetime because in my project time is very important. when i use query like this ``` where registration_date = '2014-06-19 00:12:08.940' ``` it does works but as soon as i try to search using ``` where registration_date like '2014-06-19%...
You will have to cast to date to compare two dates on equality. eg ``` CAST(registration_date AS DATE) = CAST('2014-06-19' AS DATE) ``` An alternative: ``` DECLARE @DateToFilter DATE = (CAST('2014-06-19' AS DATE)) [..] WHERE registration_date >= @DateToFilter AND registration_date < DATEADD(d, 1, @DateToFilter) ...
Simply search for everything that's at least on or after that date, and earlier than the next day. ``` registration_date >= '2014-06-19' AND registration_date < '2014-06-20' ```
How to Search datetime in Sql server 2008R2
[ "", "sql", "sql-server", "datetime", "" ]
Tables are: ``` Patient(PatientID, FirstName, LastName) Disease(DiseaseID, DiseaseName) PatientDisease(PatientID, DateID, DiseaseID) ``` It's clear that *Patient* and *Disease* tables have *PatientID* and *DiseaseID* as PKs, but what about *PatientDisease* table knowing that each patient in a single day can be diagno...
I think, that it here you should use composite PK with all 3 fields: PatientId, DateId, DiseaseId. No matter one disease per day can be diagnosed or not, all 3 fields are mandatory for patient disease.
Eigher you can go with composite key or add another column patient desiese-id to work as unique row number
Identify the PK in given tables
[ "", "mysql", "sql", "database", "" ]
I want to Calculate average hours for week. e.g. My Weekly hours are 44:43 (hh:mm) and my Working days are 5 then it should return **8:57** 44:43/ 5 ==> 8:57 How i can achieve in SQL Server.
Here's the query that I have constructed as per your requirements: ``` DECLARE @TotalHours VARCHAR(5) = '44:43' SELECT CAST(CAST(AvgMinutes AS INT)/60 AS VARCHAR) + ':' + CAST(CAST(AvgMinutes AS INT)%60 AS VARCHAR) FROM ( SELECT CEILING((CAST(LEFT(@TotalHours,CHARINDEX(':',@TotalHours) - 1) AS INT ) ...
You can convert the time to seconds, then divide, and convert back to time format. Assuming that `WeeklyHours` are in a `time` format, something like this: ``` select dateadd(second, datediff(second, 0, WeeklyHours) / WorkingDays, cast(0 as time)) ``` This expression should definitely work if `WeeklyHours` is stored ...
SQl Server Average Hours per day
[ "", "sql", "sql-server-2008", "" ]
I want to join two tables (`sales_flat_order` & `sales_flat_order_address`). I want to use the `entity_id` from one table to match with the `parent_id` in the other table. Now there is one row for every `entity_id` but there are two rows for every parent\_id. But i just want to have one row after the join. I am using ...
``` select o.customer_email, a.prefix from sales_flat_order o left JOIN (Select distinct a.prefix, a.parentid from sales_flat_order_address) a on o.entity_id = a.parent_id ```
Just add a distinct? ``` select DISTINCT o.customer_email, a.prefix from sales_flat_order o left JOIN sales_flat_order_address a on o.entity_id = a.parent_id ``` Obviously this will only remove multiple rows where o.customer\_email, a.prefix are in fact the same, otherwise you would need to find some way to decide wh...
SQL joining tables (a,b) - but only rows from a
[ "", "sql", "magento", "join", "" ]
I have inherited a MySQL database, that has a table as follows: ``` mysql> describe stock_groups; +--------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------+------+-----+---------+----------------+ | id | int(11) ...
``` SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style ='N26'; ``` worked for me.
Join the tables, and select only the data you need. If you need unique rows, use the `distinct` keyword: ``` select -- If you need unique names, use "select distinct" instead of "select" sg.name from stock_groups_styles_map as sgs inner join stock_groups as sg on sgs.group = sg.group where sgs.style ...
mysql INNER_JOIN subquery
[ "", "mysql", "sql", "" ]
I have a SQL Server 2008 database with multiple tables. I am writing a stored procedure for the user to get some market values from the tables. Eg. I have a table which has columns `Currency`, `[Market Value]`, `[Hedging]` and `[Customer ID]`. Now the user can choose to see the Currency, Market Value and Hedging by s...
Since you are using SQL 2008 I would suggest a better alternative that is both strongly typed and avoids the need of creating dynamic SQL: User Defined Table Types (UDTT) You can create a generic table type that holds integer values like so: ``` CREATE TYPE IntegerList AS TABLE ( Value int NOT NULL ) GO ``` T...
``` where ([Customer ID] IN ({ids placeholder}) ``` You can build the `SELECTreplacing` the `{ids placeholder}` with "1,3,5,... n" string
SQL Server stored procedure unkown number of variables
[ "", "sql", "sql-server-2008", "stored-procedures", "" ]
I am using SQL Server 2012. I have two tables `Sales` & `Country`. `Sales` has approx. 15 columns one of which is a primary key called `s_id`, `Country` has 5 columns and contains a foreign key also called `s_id`. I want to write a query which will select only records in the Sales table where the s\_id has more than ...
Try it like this ``` SELECT COUNT(c.[s_id]) Total, s.[usd_value], s.[eur_value] FROM Sales s LEFT JOIN Country c ON c.[s_id] = s.[s_id] GROUP BY s.[s_id] HAVING Total > 1 AND (usd_value > 0 OR eur_value > 0) ```
Try this: ``` select s.* from sales s where ( s.eur_value > 0 or s.usd_value > 0 ) and s.s_id in ( select s_id from country group by s_id having count(*) > 1 ) ```
multiple select queries using primary and foreign key
[ "", "sql", "sql-server", "" ]
Right now I have: ``` year(epe_curremploymentdate) = year(DATEADD(year, -1, SYSDATETIME())) ``` But that is giving me everything from last year. All I want is the data from today's date, one year ago.
It should be: ``` epe_curremploymentdate = DATEADD(year, -1, GETDATE()) ``` Don't check for **year** in your where clause. **EDIT:** Simple: use ``` cast(epe_curremploymentdate AS DATE) = cast(DATEADD(year, -1, GETDATE()) AS DATE) ``` That is, if you are using SQL Server 2008 and above.
This should get you to where you need to go: ``` Declare @StartDate datetime, @EndDate datetime -- @StartDate is midnight on today's date, last year set @StartDate = Convert(date, (DATEADD(year, -1, getdate()))) set @EndDate = DATEADD(Day, 1, @StartDate) select * from YourTable where epe_curremploymentdate >= @St...
How do I find data from this day exactly one year ago?
[ "", "sql", "sql-server", "datetime", "" ]
I have a very simple request to do with **SQL Server 2008**, but I can't success to achive what I want. ![Schema SQL](https://i.stack.imgur.com/ExoIA.png) For a given `FAVORITE`, a user can have zero or many `COMMENTs`, however, if the user have more than one comment, all `COMMENTs` have a `DeletedDate` `NOT NULL` (e...
If I understand your requirement you need to put the condition for the right table (`co.DeletedDate IS NOT NULL`) in the `JOIN` portion of your query like: ``` SELECT * FROM FAVORITE f INNER JOIN COMMENT co ON f.IdReferenced = co.IdReferenced AND co.DeletedDate IS NULL AND co.IdUser = f.IdUser WHERE f.IdUser = 7 AND...
If I understood your problem correctly. You could use `EXISTS` to check if there is such a record [SQLFiddle](http://sqlfiddle.com/#!3/3c35a/8) ``` SELECT * FROM FAVORITE f LEFT JOIN COMMENT co ON f.IdReferenced = co.IdReferenced WHERE f.IdUser = 7 AND f.DeletedDate IS NULL AND EXISTS ( SELECT 1 FROM COMMENT WHER...
SQL - Join 2 tables using a join column AND a condition
[ "", "sql", "sql-server", "sql-server-2008", "left-join", "sqlfiddle", "" ]
would like get your advice on how to achieve the following. I have two tables. One is called the Category and other the Trxn. I trying to find how many transactions are are in each category. I understand I need to left join my Trxn table with Category table. But the issue is that, CategoryId in the Category table is 6 ...
You have part of your left outer join table in the where clause. You can't do that, it makes it become a normal join. This works: ``` SELECT Category.ID, COUNT(Trxn.Cat_ID) FROM Category LEFT JOIN Trxn ON Category.ID = (rtrim(Trxn.Cat_ID)+ltrim(Trxn.STV)) AND Trxn.Status='ok' WHERE Category.Status='A' GRO...
For some reason there was a space after cat\_id when you concatenate the values. I was able to find this by just running. I just noticed the data type is a char. ``` select cat_id + stv from trxn ``` I trimmed of the space and the query is working. ``` SELECT Category.ID, count(Trxn.Cat_ID) FROM Category LEFT JOIN T...
Counting the number of transactions by left joining a category table
[ "", "sql", "sql-server", "left-join", "" ]
I have data in a table of length 9 where data is like ``` 999999969 000000089 666666689 ``` I want to delete only those data in which any number from 1-9 is repeating more than 5 times.
This can be **much simpler** with a regular expression using a [**back reference**](http://www.postgresql.org/docs/current/interactive/functions-matching.html#POSIX-BRACKET-EXPRESSIONS). ``` DELETE FROM tbl WHERE col ~ '([1-9])\1{5}'; ``` That's all. ### Explain `([1-9])` ... a character class with digits from 1 t...
OK, so the logic here can be summed up as: * Find the longest series of the same consecutive digit in any given number; and * Return true if that longest value is > 5 digits Right? So, lets split it into series of consecutive digits: ``` regress=> SELECT regexp_matches('666666689', '(0+|1+|2+|3+|4+|5+|6+|7+|8+|9+)'...
Deleting records with number repeating more than 5
[ "", "sql", "regex", "database", "postgresql", "pattern-matching", "" ]