Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a datetime column in one of my tables (team\_opps) called start\_date. I am trying to write methods in my model that allow me to classify them as Monday, Tuesday, etc... opportunities. ``` def self.friday_team_opps where('WEEKDAY(start_date) = ?', 4) end ``` In my view I am trying to call a .each on i...
First of all, you need to define the method on the TeamOpp class by defining the method as `def self.friday_team_opps`. Moreover, you can't call methods on the column since it would require ActiveRecord to load all the data in your table and then call the Ruby method on that data. What you can do is use direct SQL fun...
You define it as an instance method ``` def friday_team_opps ``` And it should be defined as a class method ``` def self.friday_team_opps ```
Trying to define method that makes datetime entries by day of week
[ "", "sql", "ruby-on-rails", "" ]
I want to import data from MS Sql Server and apply linear regression on the data in R. But i am not sure how i can manipulate the data from sql server so that i can do a regression. My table in sql server looks like this, ``` Pack Cubes Name Sales 1001 1.2 A 10 1001 1.2 B 12 1002 0...
Try reshape or the reshape package: ``` wide <- reshape(data, v.names = "Sales", idvar = "Cubes", timevar = "Name", direction = "wide") ```
I would use `dcast` from the `reshape2` package. Note that `dcast` leads to `NA` for non-existing combinations of `Name` and `Sales`. You need to manually change this to `0`: ``` res = dcast(df, Cubes ~ Name, value.var = 'Sales') res[is.na(res)] = 0 res Cubes A B C 1 0.8 0 8 10 2 0.9 8 5 12 3 1.2 10 12 ...
Linear regression in R with data from Sql server
[ "", "sql", "sql-server", "r", "excel", "linear-regression", "" ]
Suppose I have a table called `Events` with data similar to the following: ``` ID | Name | ParentEvent ----+----------------+----------------- 0 | Happy Event | NULL 1 | Sad Event | NULL 2 |Very Happy Event| 0 3 | Very Sad Event | 1 4 | Happiest Event | ...
The following queries all return the exact result set you asked for. All of these work by calculating the full path to the root nodes, and using some technique for making that path able to be ordered by. SQL Server 2008 and up. Here, by converting to the `hierarchyid` data type, SQL Server handles the ordering properl...
This is just add to M.Ali's answer. I realize the OP said, "As long as the results satisfy the previous two conditions, the order the results appear in does not matter". However, by adding a column to the query that keeps track of the hierarchy path, it is possible to display the results the same as in the question. `...
Ordering results in SQL select query
[ "", "sql", "sql-server", "t-sql", "select", "" ]
I've come across a problem while learning transaction isolation levels in SQL server. The problem is that after I run this code (and it finishes without errors): ``` set implicit_transactions off; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRAN T1; SELECT (...) WAITFOR DELAY '00:00:5' SELECT (...) WAITFOR D...
Either the first tran is still open (close the window to make sure it is not), or some other tran is open (`exec sp_who2`). You can't suppress X-locks taken by DML because SQL Server needs those locks during rollback.
@usr offers good possibilities. A related specific possibility is that you selected only part of the first transaction to execute while tinkering - i.e. executed `BEGIN TRAN T1` and never executed `COMMIT TRAN T1`. It happens - part of Murphy's Law I think. Try executing just `COMMIT TRAN T1`, then re-trying the secon...
sql server a simple query takes forever to run due to transaction isolation level
[ "", "sql", "sql-server", "transactions", "isolation-level", "transaction-isolation", "" ]
I have an varchar input variable that contains a comma delimited list of integers that are in one of the columns in my select statement. I know how to split the list and use this in a where clause for example: ``` DECLARE @ListOfAges Varchar SET @ListOfAges = '15,20,25' select p.Name, a.Age from People p left join A...
The function call in the WHERE clause is slowing you down. This approach is not dramatically better, but should help a bit.. ``` WHERE (@ListOfAges is NULL OR CHARINDEX(','+TRIM(STR(A.AGE))+',',','+@ListOfAges+',')) > 0) ``` Again, not an ideal approach, but should perform better than the function call. I wou...
You could use a case statement within the where clause if this is Sql 2005 or above... <http://msdn.microsoft.com/en-us/library/ms181765.aspx>
SQL for including rows based on list in input variable or all rows if variable is null
[ "", "sql", "sql-server", "" ]
I've got 2 tables that have to be joined together without them joining up together. Table 1. ``` 130, 'HANSEN', 'ZIP1' 130, 'HANSEN', 'ZIP2' 130, 'HANSEN', 'ZIP3' 120, 'HANSEN', 'ZIP4' 120, 'HANSEN', 'ZIP5' ``` Table 2. ``` 130, 'HANSEN', 'ZIP1' 130, 'HANSEN', 'ZIP2' 130, 'HANS...
Perform a union between the two tables: ``` select * from test1 union select * from test2 ``` If you want to retain duplicates in the result set use U NION ALL **SQL Fiddle:** <http://sqlfiddle.com/#!2/32bd6/2>
You are looking for the UNION clause. To keep duplicates you would have to use UNION ALL. To eliminate them use UNION without ALL. ``` select id, key, value1 from test1 union all select id, key, value2 from test2; ```
Output in SQL Table : without using JOIN
[ "", "sql", "join", "" ]
I have a basic table named `animals` with two fields `name` and `type`. The field `type` is an enum field with these values: `enum('dog','cat','horse','zebra','lion')`. I am trying to run a query and count the number of each species as well as specify the name of that species. For example an expected result will show s...
Use `GROUP BY` and `COUNT` for counting animals by type. Try this: ``` SELECT a.type, COUNT(1) AS Cnt FROM animals a GROUP BY a.type; ``` Check this [**SQL FIDDLE DEMO**](http://sqlfiddle.com/#!2/01c38/1) **OUTPUT** ``` | TYPE | CNT | |-------|-----| | dog | 2 | | cat | 2 | | horse | 1 | | zebra | 1 ...
Do you mean ``` select type, COUNT(*) from animals group by type ``` [SqlFiddle](http://sqlfiddle.com/#!2/0cccc7/4)
Count items in table, table field enum type involved
[ "", "mysql", "sql", "select", "count", "group-by", "" ]
I am trying to get past 12 months booking date count, but for the months with no booking, i need to get Null or 0. My query below skips the months with no booking, ``` SELECT bs.date,CONCAT(MONTHNAME(bs.date),' ', YEAR(bs.date)) as 'Month',count(*) AS Bookings, CONCAT(us.firstName,' ', us.lastName) as 'Name' from book...
You can do it by hardcoding the 12 months in there and CROSS JOIN with `users` then LEFT JOIN with `bookings` (I have heard others mentioned that LEFT JOIN is way faster than RIGHT JOIN). So query below ``` SELECT bs.date, CONCAT(MONTHNAME(hardcoded.date),' ', YEAR(hardcoded.date)) as 'Month', count(bs.da...
I'm not very familiar with MySQL syntax, but I would approach this by first creating a temp table with only month and year integer columns and inserting a record for each month of the past year. A simple WHILE loop using DATESUB and a decrementing counter would probably suffice. Then left join the temp table with your ...
MySQL Query - return value for past 12 months record for each month
[ "", "mysql", "sql", "" ]
I have the following table: ``` Country Year 100 201313 100 201212 101 201314 101 201213 101 201112 102 201313 102 201212 103 201313 103 201212 104 201313 104 201212 ``` I need a query that delivers just one country and just the greatest value of year, for example: ``` Country Year 100 201313 101 201314 102 201313 1...
Query: [SQLfiddleexample](http://sqlfiddle.com/#!2/31613/5) ``` SELECT c.Name, s.Description, s.Year FROM countries c JOIN seasons s ON c.Id=s.Id LEFT JOIN seasons s2 ON s.ID = s2.ID AND s2.Year > s.Year WHERE s2.id is null ORDER BY c.Name ASC ``` Result: ``` | NAME | DESCRIPTION | YEAR | |-------...
Your Query should be ``` SELECT t.Country, MAX(t.Year) FROM Table t GROUP BY t.Country ORDER BY t.Country ASC ``` **EDIT:** After the updated requirement, to SELECT other info the query can be modified as follows to work. ``` SELECT c.Name, s.Description, s.Year FROM ( SELECT s.id as id, MAX(s.Year) as ...
Combine 2 SQL queries to get Distinct values from one column and biggest from second
[ "", "mysql", "sql", "" ]
I Want to write a sql query which will should always return false. if i write ``` select 1 from dual where 1=2; ``` nothing is returned. how can i use where 1=2 which always returns "false".
``` SELECT CASE WHEN 1=2 THEN 1 ELSE 0 END FROM DUAL ```
That's because there is nothing where 1 = 2. ``` select false from dual ``` (Substitute the value you want it to return for false.)
SQL to always return false
[ "", "sql", "oracle", "" ]
``` SELECT num, code, LN AS LabelName FROM product INNER JOIN link ON product.seqno = link.seqno INNER JOIN master ON link.code = master.code ``` Like is there any other way to write this SQL? ``` DB layout is like this: 1)TABLE: product num(key) ln seqno 2)TABLE: link seqno(key) code(key) 3)Table: master cod...
You don't actually use the master table ``` select num,code, LN as LabelName from product inner join link on product.seqno = link.seqno ``` of course you might have taken that part out of your question -- but then how can we answer? (NB, as written your query might get different results as only codes in the maste...
Since you talked of *master-detail*, the concept typical for ISAM databases and implying manual management of records locating, I would make a guess you actually needed only ONE set of records, not all the whole database read. Depending on what you needed then it would go like ``` SELECT product.num, link.code, produc...
Make this query faster?
[ "", "sql", "firebird", "" ]
I have two tables as below tbl1 ``` id qNum 1 1 2 2 3 3 ``` tbl2 ``` id qNum displayNum 1 1 3 2 2 1 3 2 2 4 2 4 ``` Ideally I need a sql results to look like this ``` qNum display1 display2 display3 display4 1 0 0 ...
Your query is almost correct, you're just missing an aggregate function: ``` SELECT tbl1.qNum, MAX(CASE when tbl2.displayNum=1 then 1 else 0 end) AS filter1, MAX(CASE when tbl2.displayNum=2 then 1 else 0 end) AS filter2, MAX(CASE when tbl2.displayNum=3 then 1 else 0 end) AS filter3, MAX(CASE when tbl2.displayNum=4 the...
You have use `MAX` function to pivot the table Try this: ``` SELECT tbl1.qNum, MAX(CASE WHEN tbl2.displayNum=1 THEN 1 ELSE 0 END) AS filter1, MAX(CASE WHEN tbl2.displayNum=2 THEN 1 ELSE 0 END) AS filter2, MAX(CASE WHEN tbl2.displayNum=3 THEN 1 ELSE 0 END) AS filter3, MAX(CASE WHEN tbl2.dis...
joining with a group by and pivot
[ "", "mysql", "sql", "select", "group-by", "max", "" ]
I have seen questions on stackoverflow similar/same as the one I am asking now, however I couldn't manage to solve it in my situation. Here is the thing: I have an excel spreadsheet(.xlsx) whom i converted in comma seperated value(.CSV) as it is said in some answers: My excel file looks something like this: ``` ----...
Ok the Problem was that i need to change the `path` of the `Excel file`. I inserted it in the **public account** where *all users can access it*. If you face the same problem move your `excel file` to ex `C:\\User\Public` folder (this folder is a public folder without any restrictions), otherwise you have to deal with...
1. Based on your file, neither of the first two columns needs to be an array type (character[]) - unlike C-strings, the "character" type in postgres *is* a string already. You might want to make things easier and use `varchar` as the type of those two columns instead. 2. I don't think you do. 3. Check that you don't st...
Import data from Excel to PostgreSQL
[ "", "sql", "database", "excel", "postgresql", "" ]
I am querying part numbers from an Oracle (JDE) database. If I use the clause `WHERE Item LIKE 'AS-%'`, it correctly returns all the items that begin with 'AS-'. However, when I try to narrow that set by instead using the clause `WHERE Item LIKE 'AS-%A'` in order to find all parts matching the pattern and ending with a...
When you think that your query is misidentifying rows based on your understanding of the rows' values, examine the values using the DUMP() function. This will tell you the exact contents of the cell, including any characters that you cannot see on the display.
Perhaps some control characters at end of the data that you cannot see. Try using regexp\_like: ``` with x as ( select 'AS-123B' as col from dual UNION select 'AS-456A' as col from dual UNION select 'AS-789A' || chr(0) as col from dual ) select * from x where regexp_like (col, 'AS-(.*)A[[:cntrl:]]?') ``` Ou...
Oracle wildcard not matching?
[ "", "sql", "oracle", "" ]
I hava the following table in database (Access - Microsoft SQL Server): ``` | Product Id | Month | Sales | ---------------------------------- | 1144 | 1 | 100 | | 20131120 | 1 | 200 | | 1144 | 2 | 333 | | 1144 | 3 | 333 | | 1144 | 4 | 333 ...
This query should retrive the correct data: ``` SELECT m1.product_id, m1.month, m1.sales, COUNT(m2.month) - 1 AS counter FROM mysales AS m1 INNER JOIN mysales AS m2 ON m1.product_id = m2.product_id AND m1.month >= m2.month GROUP BY m1.product_id, m1.month, m1.sales ``` so the statment to update the...
In `SqlServer`, you can project your column ranking directly using [`row_number()`](http://technet.microsoft.com/en-us/library/ms186734.aspx) ``` select productid, [month], sales, row_number() over (partition by productid order by [month]) - 1 as [Rank] from mysales ``` Assuming the columns `[Prod...
Update table with subquery
[ "", "sql", "sql-server", "subquery", "" ]
I have a strange requirement. Here it is. I have a table. ``` DateTime PhoneNo Network ------------------- -------- --------- 11/01/2014 13:05:45 99999999 NetTwo 11/01/2014 13:05:45 99999999 NetOne 11/01/2014 13:05:45 99999999 NetOne 12/01/2014 13:05:45 99999999 NetOne 1...
Thank you soo much for your efforts. Thanks haki and Thinkjet. @think: I learned merge from you :D.. I got my expected result using subqueries inside the result set of with clause. ``` WITH MainFilter(CLI,DAYS,COUNTS) AS (SELECT TBL_DTL_CALLACTIVITY.CLI, TO_CHAR(TBL_DTL_CALLACTIVITY.CALLSTARTTIME, 'DD'),COUNT(TBL_DTL...
It's not strange - it's called a pivot table this is one way to go ``` select trunc(DateTime) as date , to_char(datetimem,'MON') as month , to_number(to_char(datetime,'yyyy')) as year , PhoneNo, network , sum(case when to_char(DateTime,'hh24') = 0 then 1 else 0 end) as h00, sum(case when to_char(DateTime,'...
Update Count on Date wise in Oracle
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle10g", "" ]
Im using mariadb with heidisql to execute sql: DECLARE @AccountID INT; Insert Into accounts(first\_name, mi, last\_name, email, is\_admin, is\_enabled, date\_created) Values('testfirstname', 'a', 'testlastname', 'user@email.com', 1, 1, NOW()); set @AccountID = Last\_Insert\_Id(); I keep getting an error: QL Error ...
Remove the `DECLARE`. It is not neccessary.
I'm using mariadb version 10.0.19 The above problem is described and has an easy solution [here: Delimiters in the mysql Client](https://mariadb.com/kb/en/mariadb/delimiters-in-the-mysql-client/) in short: **DELIMITER //** create function .. as usual BEGIN .. as usual END **// DELIMITER ;** ( The acce...
mariadb declare variable syntax error
[ "", "sql", "mariadb", "heidisql", "" ]
Im trying to format all my DATA in my sql before display information Both my joins work fine, I have a piece of data (status) that has associated titles to go with the value but the `CASE` statment isn't working. I currently have a PHP swtich statement that does this data conversion but I'd like to do it in SQL if pos...
The case should be in the `SELECT` list, not after the `INNER JOIN`. Also second issue is the use of l.status = after each THEN statement. MySql syntax only requires the final value after the THEN statement, not a value assignment. Also note that you don't need the `l.status =` part in your `when` statements, because ...
1. You want your `CASE` in `SELECT` clause 2. Your `CASE` syntax is invalid 3. As an alternative you can use a MySQL (since your question tagged with `mysql`) specific less verbose function `ELT()` That being said you can do either ``` SELECT l.leadid, l.companyname, CASE l.status WHEN 7 THEN ...
Adding a case statment to SQL join statement
[ "", "mysql", "sql", "sql-server", "" ]
I created a sql server database with name of `abc-123`, in that I created a table Emp, when I run like ``` select * from abc-123.emp; ``` I am getting the results. But when I am trying to grant some privilege to the user I unable to do that, *getting syntax error near hyphen .* will any one help me?
Make sure you are escaping the names with [] (T-SQL) or "" (ANSI SQL). You are using non-standard naming. ``` -- Sample select SELECT * FROM [abc-123].[dbo].[emp]; SELECT * FROM "abc-123"."dbo"."emp"; ``` 1 - Can you send me an example of the grant TSQL? If you are doing the action from SSMS, right click and script t...
Use Back Quote for the DB name ``` select * from `abc-123`.emp; ``` or, select the existing database with a USE statement and run the query. ``` USE `abc-123`; select * from emp; ```
can I give SQL Server database name with hyphen like abc-123?
[ "", "sql", "sql-server", "" ]
I need to use `between` in a stored procedure. This is my code ``` ALTER PROCEDURE sp_tb_sales_entry_total_product_where_date @to_date varchar(15), @from_date varchar(15) AS BEGIN SELECT * FROM tb_sales_entry_total_product WHERE [Sales Date] BETWEEN @to_date AND @from_date END ``` I passed two val...
Operator `BETWEEN` in SQL [has the following syntax](http://technet.microsoft.com/en-us/library/ms187922.aspx): ``` test_expression [ NOT ] BETWEEN begin_expression AND end_expression ``` Since the `begin_expression` needs to be first, you have to switch the order of `from_date` and `to_date`: ``` SELECT * FROM tb_s...
Switch them ``` WHERE [Sales Date] BETWEEN @from_date AND @to_date ```
How to use between in stored proc in SQL Server
[ "", "sql", "sql-server", "stored-procedures", "" ]
``` select * from MYTABLE t where EQUIPMENT = 'KEYBOARD' and ROWNUM <= 2 or EQUIPMENT = 'MOUSE' and ROWNUM <= 2 or EQUIPMENT = 'MONITOR' and ROWNUM <= 2; ``` I am trying to run a query that returns matches on a field (ie equipment) and limits the output of each type of equipment to 2 records or less per equipment typ...
``` WITH numbered_equipment AS ( SELECT t.*, ROW_NUMBER() OVER( PARTITION BY EQUIPMENT ORDER BY NULL ) AS row_num FROM MYTABLE t WHERE EQUIPMENT IN ( 'KEYBOARD', 'MOUSE', 'MONITOR' ) ) SELECT * FROM numbered_equipment WHERE row_num <= 2; ``` [SQLFIDDLE](http://sqlfiddle.com/#!4/c5182/2) If you w...
The Row count can be specific to every *Equipment* type! ``` SELECT * FROM MYTABLE t where EQUIPMENT = 'KEYBOARD' and ROWNUM <= 2 UNION ALL SELECT * FROM MYTABLE t WHERE EQUIPMENT = 'MOUSE' and ROWNUM <= 2 UNION ALL SELECT * FROM MYTABLE t WHERE EQUIPMENT = 'MONITOR' and ROWNUM <= 2; ```
SQL Oracle rownum on multiple where clauses?
[ "", "sql", "oracle", "rownum", "" ]
I am using `SQL Server 2008 R2`. I am having a database table like below : ``` +--+-----+---+---------+--------+----------+-----------------------+ |Id|Total|New|Completed|Assigned|Unassigned|CreatedDtUTC | +--+-----+---+---------+--------+----------+-----------------------+ |1 |29 |1 |5 |6 |...
The error message itself is very explicit. You can't put a column without applying an aggregate function to it into `SELECT` clause if it's not a part of `GROUP BY`. And the reason behind is very simple SQL Server doesn't know which value for that column within a group you want to select. It's not deterministic and the...
Try this............ ``` SELECT min(Id) Id, Total, New, Completed, Assigned, Unassigned, CreatedDtUTC FROM TblUsage GROUP BY Total, New, Completed, Assigned, Unassigned, CreatedDtUTC ```
Group by records by date
[ "", "sql", "sql-server", "date", "select", "group-by", "" ]
I just started designing a database in `MySQLWorkbench 6.0`. I created a few tables but now when I click the "Add table" button it shows a message: `"Index out of range"` and the program crashes. Any idea what is wrong or what could I have done to get this error ? None of the tables have any values, they just have th...
Have you tried restarting MySQL Workbench? I haven't heard of such a problem before, but maybe steps you did in a certain order caused this exception. In any case you should file a bug report for it at <http://bugs.mysql.com> to get this fixed. Only via such a report developers can take notice.
Once the alert popped up, I hit ok and then clicked on the little wrench icon above the utf selection. I had to change how it would separate the columns from ';' to ',' This fixed my issue without having to change any of the content in the csv.
Error "Index out of range" in MySQL Workbench 6.0.8.11354 (6.0), what is wrong?
[ "", "mysql", "sql", "mysql-workbench", "" ]
Basicly I have tables much like picture below. ![enter image description here](https://i.stack.imgur.com/9C9hO.png) At first I'm getting SaleOrderID by given CustomerID : ``` Select SaleOrderID From tblSaleOrder where CustomerID = 512992 ``` Which returns, 1002,1003,1005,1009 And I want to use that numbers...
Use a subselect within an `in` clause: ``` select * from tblSaleOrderDetail where SaleOrderID in ( select SaleOrderID from tblSaleOrder where CustomerID = 512992) ``` When using a subselect within an in clause remember that you must only select one column within the subselect. You could also perform ...
This is a very basic SQL operation, called the `join`. Although you can use `in` for this purpose, the more typical way is: ``` select sod.* from tblSaleOrder so join tblSaleOrderDetail sod on so.SaleOrderID = sod.SaleOrderID where so.CustomerID = 512992; ``` If you are learning SQL, the `join` operation is...
Sql Select by using another table value(s)
[ "", "sql", "select", "" ]
I have looked all over and cannot seem to find the answer to this error: > Could not find stored procedure 'dbo.aspnet\_CheckSchemaVersion'. I am writing an ASP.NET application from an empty web project and trying to add roles/membership to the application. I have made the login/logout pages myself but I am using the...
Please provide `UserID` and `Password` to your connection string. Its not there in connection string.
Paraphrasing @RonakBhatt from the comments on the OP: **Even though you are using windows authentication, create a user using SQL authentication and add those credentials to the connection string.** Thank you @RonakBhatt for pointing that out. I figured one could still connect via windows authentication
localhost cannot find stored procedure 'dbo.aspnet_CheckSchemaVersion'
[ "", "asp.net", "sql", "sql-server", "iis-7", "localhost", "" ]
I am working with SQL server 2008R2. I have a query that returns the below dataset: ``` ID FirstName LastName Relation 1 Sam Ali Employee 1 Maya Ali Dependent 2 Nadia Amle Employee 1 Sue Ibram Dependent 3 Saher Jacobs Employee 2 Alie Salem Dependent ``` I want the query ...
Use a self-join so you can get the employee associated with each dependent, and order by that. ``` SELECT t1.ID, t1.FirstName, t1.LastName, t1.Relation, t2.LastName AS EmployeeName FROM YourTable AS t1 JOIN YourTable AS t2 ON t1.ID = t2.ID WHERE t2.Relation = "Employee" ORDER BY EmployeeName, t1.ID, t1.LastName ``` I...
You can use barmer answer like this ``` SELECT * FROM TABLE ORDER BY ID, LastName ```
Order SQL Server Query by two columns
[ "", "sql", "sql-server-2008-r2", "" ]
I have this simple table setup [see fiddle](http://www.sqlfiddle.com/#!2/469b36/4) ``` CREATE TABLE mytable (`id` int, `itemid` int); INSERT INTO mytable (`id`, `itemid`) VALUES (1, 111), (2, 222), (3, 333), (4, 444), (5, 111), (6, 222), (7, 333), (8, 564), (9, ...
Try this: ``` SELECT mt.id, mt.itemid, (SELECT mt2.itemid FROM mytable mt2 WHERE mt2.id < mt.id ORDER BY mt2.id DESC LIMIT 1) AS lastitemid FROM mytable mt HAVING lastitemid = 111 ORDER BY id DESC LIMIT 5 ``` Check the [**SQL FIDDLE DEMO**](http://www.sqlfiddle.com/#!2/469b36/6) **OUTPUT** ``` | ID | ITEMID ...
If the ids are guaranteed to be consecutive, you can do this. ``` SELECT curr.id, curr.itemid, previous.itemid AS lastitemid FROM mytable curr JOIN mytable previous ON previous.id = curr.id - 1 WHERE previous.itemid = 111 ``` Otherwise, you'd need something like ``` SELECT curr.id, curr.itemid, previous.itemid AS...
Filter data based on last row mysql
[ "", "mysql", "sql", "select", "sql-order-by", "having", "" ]
I would like to generate sql code using the 'stuff' function based on a table name as a parameter This works: ``` declare @sql as nvarchar(max); select @sql = stuff((SELECT distinct [Site] FROM [ProcterGamble_analytics].[dbo].DATA_table FOR XML PATH(''), TYPE ...
You don't really need the `@presql` portion, just need to double up single quotes so they are handled properly when the dynamic portion is processed: ``` DECLARE @sql AS NVARCHAR(MAX) ,@table AS NVARCHAR(MAX) = 'DATA_table'; SET @sql = 'stuff(( SELECT distinct [Site] FROM [ProcterGamble_ana...
Your `sql` statement is confused as to what is a string and what is the code that generates the string. I think this will work: ``` select @sql = 'select stuff((' + @presql + ' FOR XML PATH(''''), TYPE ).value(''.'', ''NVARCHAR(MAX)'') , 1, 0, '''')'; ...
T-SQL: Using parameter for table name in stuff
[ "", "sql", "sql-server", "t-sql", "" ]
I have One table with People, and I have a second table to record if these people are "Absent" The Absent Table (Absences) has the AbsenceID, PersonID and AbsentDate The People Table has PersonID, FirstName, LastName I am trying to make an SQL that will Get all the values from the People table, except for those that a...
``` SELECT * FROM People where PersonID NOT IN (Select PersonID from Absences where DateValue(Absences.AbsentDate) = '20140111') ^ YYYYMMDD ```
Since `AbsentDate` is a Date/Time field, it is storing both date and time and you are looking for equality on both. So '11/01/2014' is equivalent to searching for '11/01/2014 00:00:00.000', which I can almost bet nothing is stored as. So, the better method is to look for your value *between* '11/01/2014 00:00:00.0000' ...
Select From One Table where Does not exist in another
[ "", "sql", "ms-access", "" ]
I'm feeling a little rusty with creating queries in MySQL. I thought I could solve this, but I'm having no luck and searching around doesn't result in anything similar... Basically, I have two tables. I want to select everything from one table and the matching row from the second table. However, I only want to have th...
Basically, there's nothing wrong with your query. I believe it is exactly what you need because it is returning the data you want. You can not look at as if it is duplicating your `daily_entries` you should be looking at it as if it is return all `notes` with its associated `daily_entry`. Of course, you can achieve wh...
Use mysql's non-standard group by functionality: ``` SELECT n.notes, n.task_id, de.date, de.location, de.eid FROM notes n LEFT JOIN (select * from (select * from daily_entries ORDER BY date DESC) x group by eid) de ON de.eid = n.eid ```
MySQL - Select everything from one table, but only first matching value in second table
[ "", "mysql", "sql", "select", "" ]
Guys I have this table ``` +--------------------+------+ |stime (datetime) |svalue| +--------------------+------+ |1/13/2014 8:40:00 AM|5 | +--------------------+------+ |1/13/2014 8:45:00 AM|6 | +--------------------+------+ |1/13/2014 8:46:00 AM|5 | +--------------------+------+ |1/13/2014 8:50:00 AM|...
You can use a [CTE](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) to generate time sequence from `MIN(stime)` to `MAX(stime)`: ``` WITH TMinMax as ( SELECT MIN(stime) as MinTime, MAX(stime) as MaxTime FROM T ) ,CTE(stime) as ( SELECT MinTime FROM TMinMax UNION ALL SE...
This seems to do the job: ``` declare @t table (stime datetime,svalue int) insert into @t(stime,svalue) values ('2014-01-13T08:40:00',5), ('2014-01-13T08:45:00',6), ('2014-01-13T08:46:00',5), ('2014-01-13T08:50:00',4) ;with times as ( select MIN(stime) as stime,MAX(stime) as etime from @t union all select...
Fill in missing values
[ "", "sql", "sql-server", "" ]
What's the simplest way to write and, then, read `Emoji` symbols in `Oracle` table? Currently I have this situation: * `iOS` client pass encoded `Emojis`: `One%20more%20time%20%F0%9F%98%81%F0%9F%98%94%F0%9F%98%8C%F0%9F%98%92`. For example, `%F0%9F%98%81` means ; * Column type is `nvarchar2(2000)`, so when view saved ...
After all, we do `BASE64` encoding/decoding of the text. It’s suitable for small texts.
This seems more a client problem than a database problem. Certain iOs programs are capable of interpreting that string and show an image instead of that string. SQL Developer does not do that. As long as the data stored in the database is the same as the data retrieved from the database, you have no problem.
Storing and returning emojis
[ "", "sql", "oracle", "unicode", "emoji", "" ]
I have a SQL Server database (2012 express) with many tables. I have produced three different VIEWS based on different combinations of the underlying tables. Each of these views consists of three columns, Year, Month & Total The Total column in each of the 3 Views is of a different measure. What I want to be able to do...
You could try building the full list of Months/Years from your tables using a `UNION` subquery, and then use that to drive your joins.. Something like this: ``` SELECT a.[Year], a.[Month], b.Fees AS [Billing], f.Estimate AS [Estimate], w.Fees AS [WIP] FROM (SELECT a.[Year], a.[Month] FROM MonthlyBilling...
You could set up a small date table with year and month and left join the views with that, and use the `ISNULL(variable,0)` function to replace NULL with 0. Another option instead of a date table would be to use a common table expression to generate a date range to join with. In any case I suggest you look up the date ...
Combining Multiple SQL Views ON Year & Month
[ "", "sql", "" ]
Please help me to know delete records based on the rownum where even id is duplicate it won't happen but if it is the case. ``` select rownum,a.* from a; ROWNUM ID NAME ---------- ---------- ---------- 1 1 leo_1 2 2 leo_2 3 3 leo_3 4 ...
Use the `rowid` ``` DELETE FROM table_name a WHERE EXISTS( SELECT 1 FROM table_name b WHERE a.id = b.id AND a.name = b.name AND a.rowid > b.rowid ) ``` Of course, you could do `a.rowid < b.rowid` as well. The `rowid` is just the physical address of...
``` DELETE FROM a WHERE rowid not in (SELECT MIN(rowid) FROM a group BY name); ```
Delete duplicate records using rownum in sql
[ "", "sql", "oracle", "" ]
I need to find exact file name by executing SQL query on the table containing the file\_name column .In file\_name column the complete path of files are stored like D:/Workspace/app.js I can find app.js with query Query ``` SELECT * FROM details WHERE file_name LIKE '%app.js' ``` but the problem is if I write the ...
Thanks to all of you , I got the result I wanted ``` sql = "SELECT * FROM details WHERE file_name RLIKE ?"; ps = conn.prepareStatement(sql); ps.setString(1, "[[:<:]]"+fname+"[[:>:]]"); ``` This gives the exact string that fname varible contains.
How about this? ``` SELECT * FROM details WHERE file_name LIKE '%/app.js' OR file_name LIKE '%\app.js' ```
Find exact file name from the file name with complete path stored in database
[ "", "sql", "" ]
I've have two sql queries which I'm trying to combine The first: ``` SELECT * FROM wp_posts JOIN wp_postmeta on (post_id=ID) WHERE meta_key = "packageID" and meta_value = 1 ORDER BY post_date limit 50 ``` Joins the wordpress wp\_post table to the wp\_postmeta and gets all the posts meeting with packageID = 1 (I t...
You can try this one,if there are more than one thumbnails for the post you can get the list of thumbnails separated by comma ``` SELECT *, (SELECT GROUP_CONCAT(meta_value) FROM wp_postmeta WHERE post_id = wp.ID AND wpm.meta_key = "_thumbnail_id") AS `thumbnails` FROM wp_posts wp JOIN wp_...
try with the following code ``` SELECT * FROM wp_posts wp JOIN wp_postmeta wm on (wp.post_id=wm.ID) WHERE wp.meta_key = "packageID" and wp.meta_value = 1 ORDER BY wp.post_date limit 50; ``` use proper alias and try it.
combine two sql queries -
[ "", "mysql", "sql", "wordpress", "" ]
I am trying to delete large amounts of data from a table that is a vendor design. It is over-indexed and any update/insert/deletes are painful. Removing NC indexes is not available to me. I am testing different ways to delete the data in batches. I discovered today that the below statement is considerably faster when...
``` /* Some Test Data */ CREATE TABLE Stats_Test_Table (ID INT NOT NULL PRIMARY KEY IDENTITY(1,1), VALUE INT) GO DECLARE @i INT = 1 WHILE (@i <= 100) BEGIN INSERT INTO Stats_Test_Table VALUES (@i) SET @i = @i + 1; END GO /* Execute the following command to flush any executiong plan already existing in ...
By moving the where clauses (or equivalent) to/from a variable vs. hard coded values you can often see a difference in performance due to the query optimizator. I.e., when hard code the optimizer may recognize that use a particular index would be optimal Sometimes you can get a big advantage by changing the isolation ...
Significant Performance Difference in Delete using Derived Table
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a sql code like below: ``` SELECT user_name, user_e_mail, user_phone FROM users WHERE user_name=:user_name OR user_e_mail=:email OR user_phone=:phone ``` Normally, I'm trying to get 0 or 1(if there is match or not). But I don't want to create more sql query. Shortly, my question is how to know which on...
The standard SQL syntax for this would return a separate flag for each condition: ``` SELECT user_name, user_e_mail, user_phone, (case when user_name = :user_name then 1 else 0 end) as MatchesName, (case when user_e_mail = :user_e_mail then 1 else 0 end) as MatchesEmail, (case when user_phone = :u...
One approach would be like this: ``` SELECT user_name, user_e_mail, user_phone, :user_name = user_name AS user_name_matches, :email = user_e_mail AS email_matches, :phone = user_phone AS phone_matches FROM users WHERE user_name=:user_name OR user_e_mail=:email OR user_phone=:phone ``` and here's a [SQL...
how to know which one matching when using WHERE and OR term
[ "", "sql", "" ]
As part of a new process requirement, we will be creating table and which will contain approximately 3000 - 4000 records. We have a copy of these records in plain text on a txt file. Loading these records in the table leaves me with two choices 1. Use a shell script to generate SQL file containing INSERT Statements f...
`SQL*Loader` is the more efficient method. It gives you more control. You have an option do `DIRECT` load and `NOLOGGING`, which will reduce redo log generation, and when indexes have been disabled (as part of direct loading), the loading goes faster. Downside, is if load is interupted, indexes are left `unusable`. Bu...
SQL\*Loader will be more efficient than thousands of individual `INSERT` statements. Even with 60,000 rows, though, both approaches should complete in a matter of seconds.
What is more efficient INSERT command or SQL Loader for bulk upload - ORACLE 11g R2
[ "", "sql", "oracle", "sql-loader", "oracle11gr2", "" ]
I have this `DATETIME` field in my oracle database shown in the image ![enter image description here](https://i.stack.imgur.com/6WxfN.png) I'm trying to make a query which returns something between specific dates but this query returns nothing. ``` SELECT * FROM tbl_meter WHERE TO_DATE(DATETIME,'DD/MM/YYYY') BE...
``` SELECT * FROM tbl_meter WHERE TRUNC(DATETIME) BETWEEN to_date('%s','DD/MM/YYYY') AND to_date('%s','DD/MM/YYYY'); ``` Asssuming `DATETIME` is of `DATE` data type. If it is of `TIMESTAMP` datatype then, ``` SELECT * FROM tbl_meter WHERE TRUNC(CAST(DATETIME AS DATE)) BETWEEN to_date('%s','DD/MM/YYYY') AND to_da...
It looks like you are using the same parameter twice. I expect you to have ``` select * from tbl_meter where to_date(datetime, 'DD/MM/YYYY') between to_date('%s1', 'DD/MM/YYYY') and to_date('%s2', 'DD/MM/YYYY') ```
Oracle db get values between specific dates
[ "", "sql", "oracle", "" ]
It's a very simple query: ``` SELECT * FROM temp_company WHERE number NOT IN (SELECT number FROM company) ``` It was taking 15 minutes before but that was on a Mysql installation with too low buffer pool size and 15 minutes was OK because this is a monthly task. I upgraded to Mysql 5.7 (from something like 5.1 or 5.2...
It turned out that the problem was that the temp\_company table number field did not have ascii\_bin set as its Collation like the Company table. As explained on the MySQL forums (<http://forums.mysql.com/read.php?24,603620,603732#msg-603732>), varchar fields with different collation or character sets are regarded as ...
I don't know why it's suddenly running more slowly, but I recommend converting to a join, which should perform better: ``` SELECT t.* FROM temp_company t LEFT JOIN company c ON c.number = t.number WHERE c.number is null ``` This is a fairly standard way of tackling a `not in (...)` via a join, and works because outer...
MySQL NOT IN Query much slower after Mysql Upgrade
[ "", "mysql", "sql", "mysql-5.7", "" ]
On outer joins(lets take a left outer join in this case) how does adding a filter on the right side table work? ``` SELECT s.id, i.name FROM Student s LEFT OUTER JOIN Student_Instructor i ON s.student_id=i.student_id AND i.name='John' ``` I understand that if the filter was on the `Student` table it would be more li...
All rows will be returned from your left table regardless. In the case of a left join, if the filter isn't met, all data returned from the right table will show up as null. In your case, all students will show up in your results. If the student doesn't have an instructor, i.name will be null. Since you are only select...
Should be the same as: ``` SELECT s.id FROM Student s LEFT OUTER JOIN (Select * from Student_Instructor where name='John' ) i ON s.student_id=i.student_id ```
Adding filter on the right side table on Left outer joins
[ "", "sql", "sql-server", "join", "left-join", "right-join", "" ]
I have a table with following columns and 2 rows : ``` COL1,COL2,COL3,NAME,DATE ``` Value of COL1,COL2,COL3 in both rows are A,B,C. Value of NAME in 1st row is 'DEL' and 2nd row is 'LAP'. Value of DATE in 1st row is '11.12.13' and 2nd row is '13.11.13'. Now i want a view with singlerow and following columns ``` COL...
[SQL Fiddle](http://sqlfiddle.com/#!4/21abc/3) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE table_name (COL1,COL2,COL3,N_NAME,D_DATE) AS SELECT 'A','B','C', 'DEL', '11.12.13' FROM DUAL UNION ALL SELECT 'A','B','C', 'LAP', '13.11.13' FROM DUAL UNION ALL SELECT 'A','B','C', 'DEL', '12.12.13' FROM DUAL...
``` with tab (COL1,COL2,COL3,N_NAME,D_DATE) as ( select 'A','B','C', 'DEL', '11.12.13' from dual union all select 'A','B','C', 'LAP', '13.11.13' from dual) select COL1, COL2, COL3, min(decode(N_NAME, 'DEL', D_DATE, NULL)) DEL, min(DECODE(N_NAME, 'LAP', D_DATE, NULL)) LAP from tab group by COL1, COL2, ...
Oracle rows to columns
[ "", "sql", "oracle", "" ]
--I want to use SQL - `BETWEEN` on TIME datatype. I want to execute below query but it does not give correct result. here, `starttime` and `endtime` both fields are typeof `smalldatetime` whichi do cast into TIME field as i need time comparision only and date's value is not actual its just dummy. ``` SELECT count(...
``` WHERE CAST(t1.StartTime as TIME) >= CAST(t2.StartTime as TIME) AND CAST(t1.StartTime as TIME) <= CAST(t2.EndTime as TIME) ``` Using this Snytax makes your queries SARGable. [Read Here](http://msmvps.com/blogs/robfarley/archive/2010/01/22/sargable-functions-in-sql-server.aspx) for more information about making yo...
I suspect based on your example you are looking for times in t1 between a start and end time in t2 but the two tables do not necessarily have a relationship between them on any key. Trying to use a join in that scenario will not work easily, you'd have to move M. Ali's solution to the join predicates rather than in th...
How to apply SQL 'between' keyword on TIME data type
[ "", "sql", "sql-server", "database", "sql-server-2008", "between", "" ]
I have this table: ``` XPTO_TABLE (id, obj_x, date_x, type_x, status_x) ``` I wanna create a unique constraint that applies to the fields `(obj_x, date_x, type_x)` only when `status_x <> 5`. I have tried to create this one but Oracle says: ``` line 1: ORA-00907: missing right parenthesis ``` ``` CREATE UNIQUE INDE...
@jamesfrj: it looks like you are trying to ensure that your table should contain only one record for which `status <>5`. You can try creating a unique functional index by concatenating the columns, as given below ``` create table XPTO_TABLE (id number, obj_x varchar2(20), ...
Under Oracle 11, you can create a bunch of virtual columns that get non-NULL value only when STATUS\_X is 5, and then make *them* unique: ``` CREATE TABLE XPTO_TABLE ( ID INT PRIMARY KEY, OBJ_X INT, DATE_X DATE, TYPE_X VARCHAR2(50), STATUS_X INT, OBJ_U AS (CASE STATUS_X WHEN 5 THEN OBJ_X ELSE NULL END), ...
Conditional unique constraint with multiple fields in oracle db
[ "", "sql", "oracle", "conditional-statements", "unique", "unique-constraint", "" ]
I have two separate databases. I am trying to update a column in one database to the values of a column from the other database: ``` UPDATE customer SET customer_id= (SELECT t1 FROM dblink('port=5432, dbname=SERVER1 user=postgres password=309245', 'SELECT store_key FROM store') AS (t1 integer)); ``` This is the...
***Technically***, to remove the error, add **`LIMIT 1`** to the subquery to return at most 1 row. The statement would still be nonsense. ``` ... 'SELECT store_key FROM store LIMIT 1' ... ``` ***Practically***, you want to match rows *somehow* instead of picking an arbitrary row from the remote table `store` to updat...
The fundamental problem can often be simply solved by changing an `=` to **`IN`**, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer: ``` WITH accounts_to_delete AS ( SELECT account_id FROM accou...
Postgres Error: More than one row returned by a subquery used as an expression
[ "", "sql", "database", "postgresql", "subquery", "dblink", "" ]
I want to create a report by using BIRT. I have 5 SQL criterias as the parameter for the report. Usually when I have 3 criterias, I am using nested if-else for the WHERE statement with javascript. Since right now I have more criteria it becomes more difficult to write the code and also check the possibilities, especia...
There is a magical way to handle this without any script, which makes reports much easier to maintain! We can use this kind of SQL query: ``` SELECT * FROM mytable WHERE (?='' OR city=? ) AND (?=-1 OR age>? ) AND (?='' OR department=? ) AND (?='' OR title=? ) ``` So each criteria has two dataset parameters, with a "O...
Depending on the report requirements and audiance you may find this helpful. Use text box paramaters and make the defualt value % (which is a wild card) ``` SELECT * FROM mytable WHERE city like ? AND age like ? AND department like ? AND title like ? ``` This also allows your users to search for partial names...
IF-ELSE Alternative for Multiple SQL criteria for use in BIRT
[ "", "sql", "if-statement", "birt", "" ]
I am trying to query a huge database (aprroximately 20 millions records) to get some data. This is the query I am working on right now. ``` SELECT a.user_id, b.last_name, b.first_name, c.birth_date FROM users a INNER JOIN users_signup b ON a.user_id a = b.user_id INNER JOIN users_personal c ON a.user_id a = c.user_id ...
Try this: ``` SELECT a.user_id, b.last_name, b.first_name, c.birth_date, FLOOR(DATEDIFF(CURRENT_DATE(), c.birth_date) / 365) age, DATEDIFF(b.left_date, b.join_date) workDays FROM users a INNER JOIN users_signup b ON a.user_id a = b.user_id INNER JOIN users_personal c ON a.user_id a = c.user_id WHERE b....
Or you can do just this ... ``` SELECT TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age_in_years, TIMESTAMPDIFF(MONTH, birthday, CURDATE()) AS age_in_month, TIMESTAMPDIFF(DAY, birthday, CURDATE()) AS age_in_days, TIMESTAMPDIFF(MINUTE, birthday, NOW()) AS age_in_minutes, TIMESTAMPDIFF(SECOND, birthda...
MySQL - Getting age and numbers of days between two dates
[ "", "mysql", "sql", "select", "inner-join", "datediff", "" ]
Can anybody help me to create a good way to transfer data from one table to another table? For example: **table1** ``` ID | Name 1 | Juan 2 | Two ``` **table2** ``` (no content) ``` What I want is a loop that will transfer the data of `table1` to `table2`. While not all data of `table1` is transferred to `tabl...
The standard SQL approach is: ``` insert into table2(id, name) select id, name from table1; ``` You don't need a loop.
I suppose you mean to do this in VB. Let conn, rs1 and rs2 already initialized, you can obtain your goal as shown: ``` rs1.Open "Table1", conn rs2.Open "Table2", conn, 3, 3 Do Until rs1.EOF rs2.AddNew() rs2("id") = rs1("id").Value rs2("name") = rs1("name").Value rs2.Update rs1.MoveNext() Loop rs2.Close() rs1...
Transfer data from one table to another table
[ "", "sql", "vb.net", "visual-studio-2010", "loops", "" ]
i have table like ``` +---+----+ |TID|DATA| +---+----+ |1 |C | +---+----+ |1 |F | +---+----+ |1 |D | +---+----+ |1 |E | +---+----+ |2 |X | +---+----+ |2 |C | +---+----+ |2 |B | +---+----+ |2 |F | +---+----+ |3 |C | +---+----+ ``` i want to count frequency from combination of data C and F gr...
Try this: ``` SELECT COUNT(*) FROM ( SELECT tid, SUM(CASE WHEN `data` LIKE '%C%' THEN 1 WHEN `data` LIKE '%F%' THEN 1 ELSE 0 END ) AS freq FROM `table` GROUP BY tid HAVING freq = 2 ) t ```
You should use `OR` instead of `AND` ``` select count(data) from tabel where data like '%C%' OR '%F%' group by tid ```
mysql count combination of non unique data in row
[ "", "mysql", "sql", "select", "group-by", "having", "" ]
Given the following table: ``` date_field_one date_field_two arbitrary_value ---------------- ---------------- ----------------- 1/1/11 1/3/11 cheese 1/1/11 1/4/11 the color orange 2/2/11 2/3/11 1 2/2/11 ...
Edit for new response! The solution posted by M.Ali may be the best fit for your specific case as it will ensure you only ever get one row result from your base data, even if there exist multiple candidate rows for your answer ( as in, date\_field\_one, date\_field\_two combinations are not distinct ). The following wi...
``` ;WITH CTE AS ( SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY date_field_one ORDER BY date_field_two ASC) FROM TableName ) SELECT * FROM CTE WHERE rn = 1 ```
Ensuring only distinct records are returned with DISTINCT
[ "", "sql", "sql-server", "" ]
I have a database like this: ``` |--------------------------------------------------------------------------| | NAME | SCORE1 | SCORE2 | SCORE3 | SCORE4 | RATING | |--------------------------------------------------------------------------| | Joe Bloggs | -50 | 0 | -10 |...
You may want to use the [GREATEST()](http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_greatest "GREATEST()") function: ``` With two or more arguments, returns the largest (maximum-valued) argument. ``` This code snippet does what you wanted for score2 and score3 columns in your example: ``` ...
With the information from your comment I think what you're looking for is the [GREATEST](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest) function. Use it as follows: ``` SELECT GREATEST(Score1, Score2, Score3, ...) AS Score, Rating FROM db ORDER BY 1, Rating ``` ORDER BY 1 means ...
SQL: Combine multiple columns into one for sorting (output only)
[ "", "mysql", "sql", "sorting", "" ]
I have a view that list available dates from an online calendar (basically, I created entries for all available dates and then compare this to the dates that have been booked out - the view then show all dates within 'AvailableDates' where 'Date' <> 'BookedDate'. So far I can get it to run a list that looks like this....
You might want to have the year in there, too, or you might get false results. ``` SELECT YEAR(your_column) AS the_year, DATE_FORMAT(your_column, '%b') AS the_month_abbreviated, GROUP_CONCAT(DATE_FORMAT(your_column, '%D') ORDER BY DAY(your_column) SEPARATOR ', ') AS the_days FROM your_table GROUP BY YEAR(your_colum...
You have to convert the datecolumn to month and use GROUP\_CONCAT(). Maybe this can work or at least in the right direction. ``` SELECT LEFT(monthname(datecolumn),3),GROUP_CONCAT(DAY(datecolumn)) FROM table GROUP BY CONCAT(YEAR(datecolumn),MONTH(datecolumn)) ``` Missed to format the DAY. Now fixed
My SQL - creating a grouped date list from database dates
[ "", "mysql", "sql", "date", "" ]
This query returns rows that have `is_message` = 'on' and `mass_message` = 'on' ``` SELECT * FROM `messages` WHERE (`sender_id` = '111' AND `recipient_id` = '222') OR (`sender_id` = '222' AND `recipient_id` = '111') AND (`is_message` != 'on' OR `is_message` IS NULL) AND (`mass_message` != 'on' OR `mass_mess...
Try fixing your parenthesis ``` SELECT * FROM `messages` WHERE ( (`sender_id` = '111' AND `recipient_id` = '222') OR (`sender_id` = '222' AND `recipient_id` = '111') ) AND (`is_message` != 'on' OR `is_message` IS NULL) AND (`mass_message` != 'on' OR `mass_message` IS NULL) AND `invite_for_l...
Change your WHERE to ``` WHERE ((`sender_id` = '111' AND `recipient_id` = '222') OR (`sender_id` = '222' AND `recipient_id` = '111') ) AND .... ```
Query not returning the right rows
[ "", "sql", "" ]
Trying to find difference between two avg giving error? <http://sqlfiddle.com/#!3/7160d/9> ``` select * from ( select avg(avg_stars) as avg_1 from ( select r.mid, avg(stars) as avg_stars from rating r inner join movie m on r.mid = m.mid where year < '1980' group by r.mid ) ) - ( select avg(avg_stars) as avg_2 from ( ...
Should be "littlbe bit" simplified ``` select avg(case when year < '1980' then stars end) - avg(case when year > '1980' then stars end) from movie m inner join (select mId, Cast(stars as int) as stars from Rating) r on m.mID = r.mID ``` or (remove the cast if stars is of correct type) ``` select avg(case when year...
Is this you want. ``` select ( select avg(avg_stars) as avg_1 from ( select r.mid, avg(convert(int,stars)) as avg_stars from rating r inner join movie m on r.mid = m.mid where year < '1980' group by r.mid ) x ) - ( select avg(avg_stars) as avg_2 from ( select r.mid, avg(convert(int,stars)) as avg_stars from rating ...
SQL queries avg difference showing error?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a database that contains website URL's. From those URL's I'd like to extract the domain name. Here are two (quiet different) examples: ``` http://www.example.com -> example.com example.co.uk/dir/index.html -> example.co.uk ``` In order to do this I am using a regular expression and the functions REGEXP\_...
Thanks to the hints in the answers I finally got it working! The code I am using now looks like this: ``` REGEXP_REPLACE(website_url, '(http[s]?://)?(www\.)?(.*?)((/|:)(.)*|$)', '\3') ``` Thanks for the help everybody!
Use this : ``` WITH tab AS (SELECT 'https://www.example.co.uk/dir/index.html' AS website_url FROM dual) SELECT REGEXP_SUBSTR(REGEXP_REPLACE(website_url, '^http[s]?://(www\.)?|^www\.', '', 1), '\w+(\.\w+)+') FROM tab; ``` output: ``` |REGEXP_SUBSTR(REGEXP_REPLACE(W| -------------------------------- |example...
Get domain from URL in Oracle SQL
[ "", "sql", "regex", "oracle", "" ]
I have two tables one called games and one called reviews. I am trying to join these two tables together and have looked through the documentations and also the other questions here on stackoverflow. ``` SELECT games.id, games.title, games.developer, reviews.review, reviews.review_title, (SELECT review, COUNT(*) FRO...
You should move the subquery into the `from` clause, instead of `reviews` to get the number: ``` SELECT g.id, g.title, g.developer, r.Numberofreviews FROM games g inner join (SELECT games_ean, COUNT(*) as Numberofreviews FROM reviews GROUP BY games_ean ) r on g.ean = r.games_ean; ``` It do...
You need to use the correlated subquery and for the error it clearly says there should be one column from your subquery ``` SELECT g.id, g.title, g.developer, (SELECT COUNT(*) FROM reviews WHERE games_ean = g.ean) AS Numberofreviews FROM games g INNER JOIN reviews r ON g.ean = r.game...
SQL Inner join with count
[ "", "mysql", "sql", "" ]
I am new to SQL and having and issue. I want to delete from my database wherever somebody in the description column has the hashtag "#whatever". I was able to write the following query: ``` select id from table where description_field LIKE "%#whatever%" and user_id=333 ``` But if i use the LIKE function here it will ...
Use [`RLIKE`](http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp), the regex version of LIKE: ``` WHERE description_field RLIKE '[[:<:]]#whatever[[:>:]]' ``` The expressions `[[:<:]]` and `[[:>:]]` are leading and trailing "word boundaries".
It would be better to save them in multiple columns but ``` SELECT id FROM table WHERE decription_field REGEXP '[[:<:]]#whatever[[:>:]]' and user_id=333 ``` could do the trick
How do I use the LIKE function in SQL but for an exact word?
[ "", "mysql", "sql", "database", "subquery", "" ]
in a relational database, can we have a table without any relation with the other tables?
Yes. The way relations are expressed are with foreign keys. If a table you generate has no Foreign keys, and no foreign keys in other tables point to this table, it has no relationships. It can still be given a relationship later though so don't worry about shooting yourself in the foot.
Of course. Even you can create a table without fields.
in a relational database, can we have a table without any relation with the other tables?
[ "", "sql", "database-design", "relational-database", "entity-relationship", "" ]
Why is this sql giving tables with `minimum` field having null. Also when `A` has no data between the given date ranges, it is providing the table with all `rooms` having `minimum` as null ``` SELECT `rooms`.*,A.`minimum` FROM ( SELECT `room_id`, min(`available_rooms`) AS `minimum` FROM `room_bo...
Try this: ``` SELECT r.*, MIN(rb.available_rooms) minimum FROM rooms r INNER JOIN room_bookings rb ON r.room_id = rb.room_id AND rb.date BETWEEN '2014-02-01' AND '2014-02-10' WHERE r.location = 'kathmandu' AND r.status = 1 GROUP BY r.room_id HAVING minimum IS NOT NULL ```
``` SELECT `rooms`.*,A.`minimum` FROM ( SELECT `room_id`, min(`available_rooms`) AS `minimum` FROM `room_bookings` WHERE `date` BETWEEN '2014-02-01' and '2014-02-10' GROUP BY `room_id` having minimum > 0) as A INNER JOIN `rooms` on `rooms`.`room_id`=A.`room_id` WHERE `roo...
Mysql error not following where condition
[ "", "mysql", "sql", "select", "group-by", "where-clause", "" ]
I'm sure this is really simple but I've been up through the night and am now getting stuck. I have a piece of functionality that clones a record in a database however I need to ensure the new name field is unique in the database. eg, the first record is ``` [ProjectName] [ResourceCount] 'My Project' 8 ``` ...
I resolve this using an IF EXISTS inside a WHILE loop.. Personally I can't see what's wrong with this method but will obviously take any comments into account ``` DECLARE @NameInvalid varchar(100) DECLARE @DealName varchar(100) DECLARE @Count int SET @Count = 1 SET @NameInvalid = 'true' SELECT @DealName = DealName F...
So from my understanding of your problem, here's how I would approach it: My table: ``` CREATE TABLE [dbo].[deal] ( [dealName] varchar(100), [resourceCount] int ) ``` Then create a unique index on the dealName column: ``` CREATE UNIQUE NONCLUSTERED INDEX [UQ_DealName] ON [dbo].[deal] ( [dealName] ASC ) ``` Once yo...
How to ensure my SQL varchar field is unique
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have a database with a table that stores int and string. The integer value is the primary key. I have created a function to just fetch the strings from the database and store them in a list which is then applied to the ListView using an ArrayAdapter as shown below. ``` List<String> list = db.getAllStringNotes(); Ar...
The simple thing is create two List, ``` 1. String - Stored String notes 2. Integer - Stored all Primary Keys ``` So whenever user click on `Listview` user get its position, and based on that position get primary key value from second list and then perform your delete query.
There are many ways to do this: but as you are already using an ArrayList so i would suggest just make another arraylist while fetching from database: So while deleting using the position : Use the Primary Key from the **PrimaryKeyArrayList** and delete values from both the ArrayList; With this you will get exactly w...
How to mirror ListView to Database?
[ "", "android", "sql", "listview", "android-listview", "" ]
I am creating "dynamic" sql statements from Powershell and pass it to PostGreSQL server on Windows. Below is the code ``` for ($i=1; $i -le 9; $i++) { $CurDate = (get-date -format "yyyy-MM-dd HH:mm:ss") $BatchLogInsert = "Insert into `"TEMP`".`"batchLog`" (batchid, filename, status, createdate) values ('" + $NewBatch...
Your double quotes are eaten by Powershell, Postgres sees an unquoted table name, folds it to lowercase and fails to find such a table. Proper double quotes escaping seems to involve backslashes **and** backticks: ``` $BatchLogInsert = "Insert into \`"TEMP\`".\`"batchLog\`" (... ``` It would be easier to avoid using...
Any time you're doing "string building," I recommend that people use .NET string formatting in PowerShell. Furthermore, using the `Start-Process` cmdlet can make passing arguments to executables a lot easier. ``` $PSql = 'C:\PostgreSQL\9.3\bin\psql.exe'; for ($i=1; $i -le 9; $i++) { $CurDate = (Get-Date -Format '...
insert fails in psql.exe (created from powershell)
[ "", "sql", "postgresql", "powershell", "" ]
I have a log table with several statuses. It logs the position of physical objects in an external system. I want to get the latest rows for a status for each distinct physical object. I need a list of typeids and their quantity for each status, minus the quantity of typeids that have an entry for another status that i...
If I understood you correctly, this will give you the desired output: ``` select l1.typeid, l1.status, count(1) - ( select count(1) from log l2 where l2.typeid = l1.typeid and l2.date > l1.date ) from log l1 group by l1.typeid, l1.status; ``` Check this [SQL Fiddle](http://sqlfiddle.co...
You need to get the greatest date per `status`, not per `id`. Then join to the log table where the status *and* date are the same. ``` SELECT dl.id, dl.status FROM `log` AS dl INNER JOIN ( SELECT status, MAX( `date` ) AS date FROM `log` GROUP BY status ORDER BY NULL ) AS dl2 USING (status, date); ``` It wou...
Mysql get latest row for status
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
Inserting data from one table to another is usually as simple as: `SELECT * INTO A FROM B` But just out of curiosity,suppose I have two tables `tbl_A` and `tbl_B`. I have 100 records in `tbl_B` and some 20 rows in `tbl_A` (some of which might be common in both tables), I want to insert rows from `tbl_B` into `tbl_A` ...
You can use `NOT EXISTS`: ``` INSERT INTO tbl_A SELECT IdCol, Col2, Col3 FROM dbo.tbl_B B WHERE NOT EXISTS(SELECT 1 FROM tbl_A A2 WHERE A2.IdCol = B.IdCol) ```
You can use MERGE command Description in MS tech <http://msdn.microsoft.com/en-us/library/bb510625.aspx>
Insert Data from one table to another leaving the already existing rows
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2005", "" ]
I've following query, what i want to do is, i just want month name from the date column, in the following query its displaying month number ``` SELECT MONTH(Invoice_Date), SUM(R.Total) AS TOTAL FROM Sales R GROUP BY MONTH(Invoice_Date) ORDER BY MONTH(Invoice_Date); ``` I tried MonthName function, also i tried convert...
try this ``` SELECT DATENAME(month, Invoice_Date), SUM(R.Total) AS TOTAL FROM Sales R GROUP BY DATENAME(month, Invoice_Date) ORDER BY DATENAME(month, Invoice_Date); ```
Try datepart function of MS SQL <http://msdn.microsoft.com/en-us/library/ms174420.aspx> MS sql query will be: ``` SELECT DATEPART(month,Invoice_Date), SUM(R.Total) AS TOTAL FROM Sales R GROUP BY DATEPART(month,Invoice_Date) ORDER BY DATEPART(month,Invoice_Date) ``` Assuming that Invoice\_Date "Is an express...
SQL Query to retrieve month name from database
[ "", "sql", "ms-access", "" ]
I have the following table ``` +----+----------+------+ |D_ID|date |value | +----+----------+------+ |0 |1992-02-01|119940| +----+----------+------+ |1 |1992-02-01|119941| +----+----------+------+ |1 |1992-02-02|119942| +----+----------+------+ |2 |1992-02-01|119943| +----+----------+------+ |0 |1992-02...
Hope this helps! ## ORACLE: ``` SELECT date , MAX(DECODE(D_ID,0,value,NULL)) as D_ID_0, MAX(DECODE(D_ID,1,value,NULL)) as D_ID_1, MAX(DECODE(D_ID,2,value,NULL)) as D_ID_2 FROM your_table GROUP BY date ; ``` ## MySQL: ``` SELECT date , MAX(IF(D_ID=0,value,NULL)) as `D_ID_0`, ...
Use Pivot ``` WITH tab(D_ID,d_date,d_value) AS (SELECT 0 , '1992-02-01', 119940 FROM dual UNION ALL SELECT 1, '1992-02-01', 119941 FROM dual UNION ALL SELECT 1, '1992-02-02', 119942 FROM dual UNION ALL SELECT 2, '1992-02-01', 119943 FROM dual UNION ALL SELECT 0, '1992-02-02', 119944 FROM dual UNION ALL SELECT 0, '199...
How to write this query to get proper result?
[ "", "jquery", "mysql", "sql", "oracle", "" ]
How can I get last month date like ``` select * from table where date in ( last month ) ``` I dont want the last 30 days AND how can I get last month automatically
**Edit** if you mean last month from today. or previous month from a specific date then you need to do something like this ``` SELECT DATEPART(MONTH, DATEADD(MONTH, -1, [Date])) ``` Or to get records from previous month of the year you can do something like this ``` SELECT * FROM Table WHERE MONTH(Date) = DATEPAR...
Assuming you want all items where the date is *within the last month* i.e. between today and 30/31 days ago: ``` Select * From Table Where Date Between DATEADD(m, -1, GETDATE()) and GETDATE() ```
Select all where date in Last month sql
[ "", "sql", "sql-server", "t-sql", "" ]
## The problem We have a legacy Visual FoxPro reservation system with many tables. I have been asked to do some housekeeping on the tables to reduce their size. * The tables are badly designed with no auto incrementing primary key. * The largest table is 3 million rows. * I am attempting to delete 380,000 rows. * Due...
Instead of doing in batch of so many record numbers, why not a simpler approach. You are looking to kill off everything prior to some date (2010-01-01). Why not try based on starting with 2009-12-31 and keep working backwards to the earliest date on file you are trying to purge off. Also note, I don't know if Departur...
It looks like your condition with date isn't working. Try to execute SELECT statement with using of CTOD() function instead of DATE() you've used. When your condition will work, then you'll be able to run DELETE statement. But remember that as a result of the DELETE execution the rows will only be marked as deleted. T...
How to delete large amounts of data from Foxpro
[ "", "sql", "visual-foxpro", "" ]
I have a table containing user to user messages. A conversation has all messages between two users. I am trying to get a list of all the different conversations and display only the last message sent in the listing. I am able to do this with a SQL sub-query in FROM. ``` CREATE TABLE `messages` ( `id` bigint(20) NOT ...
You seem to be trying to get the last contents of messages to or from user 22 with type = 1. Your method is explicitly not guaranteed to work, because the extra columns (not in the `group by`) can come from arbitrary rows. As explained in the [documentation][1]: > MySQL extends the use of GROUP BY so that the select l...
Since this is a rather specific type of data query which goes outside common ORM use cases, DQL isn't really fit for this - it's optimized for walking well-defined relationships. For your case however Doctrine fully supports [native SQL with result set mapping](http://docs.doctrine-project.org/en/latest/reference/nati...
SQL alternative to sub-query in FROM
[ "", "mysql", "sql", "dql", "" ]
I have 3 tables called `table1` `table2` and `table3`. the `table3` contains records that have `table1.id` and `table2.id` and some other columns as well. So I need to do the following. for each record in table 1 I need to see if in table3 there is a row containing that table1.id and any other table2.id if there is no ...
If I've got it right try this: ``` INSERT INTO Table3 (Table1_id,Table2_id) SELECT Tablei.id,Table2.id FROM Table1,Table2 WHERE NOT EXISTS (SELECT 1 FROM Table3 WHERE Table3.Table1_id=Table1.ID AND ...
Try this: ``` IF NOT EXISTS(SELECT 1 FROM Table3 WHERE Table3.Table1_ID = Table1.ID AND Table3.Table2_ID = Table2.ID) INSERT INTO Table3(Table1_ID, Table2_ID) VALUES (ID1,ID2) END IF ```
Sql insert if row does not exist
[ "", "sql", "t-sql", "" ]
I would like to implement a query in MYSQL that will remove the characters before the space For example : > UA 016 i want to remove 'UA ' with the space , and only keep > 016 here is the query statements: ``` update field_data_field_id set field_id_value = '.... what i need here'; ``` Thanks in advance
``` UPDATE field_data_field_id SET field_id_value=SUBSTRING_INDEX( SUBSTRING_INDEX(field_id_value,' ',2),' ',-1); ```
try this ``` CREATE FUNCTION IsNumeric (val varchar(255)) RETURNS tinyint RETURN val REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$'; CREATE FUNCTION NumericOnly (val VARCHAR(255)) RETURNS VARCHAR(255) BEGIN DECLARE idx INT DEFAULT 0; IF ISNULL(val) THEN RETURN NULL; END IF; IF LENGTH(val) ...
MYSQL query will remove characters from a string
[ "", "mysql", "sql", "character", "" ]
``` SELECT * FROM table -> 35 records SELECT * FROM table WHERE x IN (SELECT x FROM table1) -> 34 records SELECT * FROM table WHERE x NOT IN (SELECT x FROM table1) -> 0 records ``` Any ideas as to how this could be possible?
The simple fix for the `NULL` value is: ``` SELECT * FROM table WHERE x NOT IN (SELECT x FROM table1 WHERE x is not null); ``` However, it is recommended to use `not exists` rather than `not in` because of the `NULL` issue: ``` select t.* from table t where not exists (selec...
One of your `x` values is `NULL`. `NULL` values will never evaluate to `true` in any comparison (since the value is unknown).
Issue with NOT IN
[ "", "sql", "sql-server", "" ]
I'm using JDBC to insert a single row into a DB2 database table using the insert-select style insert. I am simultaneously trying to insert dynamic data from a variable, as well as the `ENTRY_DATE` using `CURRENT DATE`: ``` INSERT INTO mytable (COL_A, COL_B, ENTRY_DATE) SELECT COL_A, ?, CURRENT DATE FROM mytable WHERE ...
I think the problem is that DB2 doesn't know anything about your parameter which is in the column list of the select, so can't know what the select will return, and so it can't prepare the statement properly. Try this: ``` INSERT INTO mytable (COL_A, COL_B, ENTRY_DATE) SELECT COL_A, CAST(? AS CHAR(1)), CURRENT DATE F...
The error message refers to `?` not to CURRENT DATE. Maybe this is what you wanted? ``` INSERT INTO mytable (COL_A, COL_B, ENTRY_DATE) SELECT COL_A, NULL, CURRENT DATE FROM mytable WHERE COL_A > 1; ``` In DB2 a `?` means there will be a parameter passed for that location. But it is saying you can't use a Parameter Ma...
Using CURRENT TIME in an insert with a select in DB2
[ "", "sql", "select", "jdbc", "insert", "db2", "" ]
I am trying to get the output from one SQL statement into another SQL statement, although it does not seem to be working. Is there an alternative, and how would I use it? ``` $id = ($_SESSION["user_id"]); $query1 = "SELECT event_id FROM booking where user_id = '$id'"; $result = mysql_q...
You can join the tables, try using below syntax ``` SELECT event.event_id,booking.* FROM event JOIN booking on event.event_id=booking.event_id WHERE booking.user_id='$id'; ```
What's about using the one query instead of two: ``` $id = ($_SESSION["user_id"]); $query2 = "SELECT * FROM event where event_id IN (SELECT event_id FROM booking where user_id = '$id')"; $result...
Using the output of an SQL statement in another SQL statement?
[ "", "mysql", "sql", "" ]
I am having a problem with a query I have put together, I have followed the explanation on <http://www.sql-server-helper.com/error-messages/msg-147.aspx> (bottom of the page) and I can't see much difference in my code to the example other than an addition to the WHERE clause and an Inner Join. Yet I am still getting t...
WORKING CODE: ``` SELECT * FROM [dbo].[mail] AS rm LEFT OUTER JOIN [dbo].[mytbl] AS ec ON [rm].[webref] = [ec].[Webref] WHERE rm.[webref] = 'XYZ-594112' AND [PolRef@] = ( SELECT MAX([PolRef@]) FROM [dbo].[mytbl] WHERE [Webref] = 'XYZ-594112' ) ```
Just order by `poltef@ desc` and take the top 1: ``` SELECT TOP 1 * WITH TIES FROM mail rm JOIN mytbl ec ON rm.webref = ec.Webref WHERE rm.webref = 'XYZ-594112' ORDER BY poltef@ desc ``` Also, I have removed all unnecessary characters.
WHERE ID = MAX(ID) Getting Error Aggregate May Not Appear
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to import some data into sql using the import and export data wizard. In excel i have a column with 8 numbers. However when i get these in the import wizard said column is displayed as being double. and when i import it i get overflow errors. I then go back to excel, select the cell, format them as being a ...
You can import your table into a temp or staging table with a larger data type; validate and clean your imported data; then load it into your real table. If you can't always enforce the data type in your Excel doc, then make it easier on the server side to import your data, then manipulate it there.
I had a project that ran into this problem last year. What I ended up doing is I imported the data from Excel to Access. Then import from Access to SQL. I don't remember the specifics, but it solved most of my issues.
Preparing excel workbook for importing into SQL
[ "", "sql", "sql-server", "vba", "excel", "" ]
I am working on updating some Python code I have been working with and was looking for some advice on the best way to deal with an idea I am working with. The part of my code that I wish to change is : ``` my_reader = csv.reader(input, delimiter = ',',quotechar='|') mouse.executemany("INSERT INTO Example_Input (ID,Nam...
Assuming your csv had a header field, you could use a [DictReader](http://docs.python.org/2/library/csv.html#csv.DictReader) and generate the field names and parameters its [fieldnames](http://docs.python.org/2/library/csv.html#csv.csvreader.fieldnames) property. The constructor for [DictReader](http://docs.python.org...
On python3, using list comprehensions and dictionaries I came up with the following simple code that is capable of building a Dynamic SQLite insert string based on a given dictionary: ``` # Data to be inserted: data = [ { 'table': 'customers', 'values': { 'name': '"Doctor Who"', 'email': '"docto...
Dynamic INSERT Statement in Python
[ "", "sql", "python-2.7", "sqlite", "" ]
I created a table named `tblEmployees` with code - ``` Create table tblEmployees ( EmployeeID int identity primary key, Name nvarchar(30), Salary float, Gender tinyint ) ``` Then I inserted values- ``` insert into tblEmployees values ('Akmal', 5000, 0) insert into tblEmployees values ('Shakira', 6000...
Your T-SQL script is incomplete because my IDENTITY values are generated starting with 1 (and ending with 5). Note #0: I'm only try to describe some reasons for those missing IDENTITY values. Note #1: Don't run this script on a production server. Note #2: Using `IDENTITY` within a column definition means `IDENTITY(1...
Do not rely on `IDENTITY` columns to produce a contiguous set of values with no gaps. Period. This is not guaranteed at all; several things can cause gaps such as rollbacks, deletes, reseeds, etc. I don't believe you reproduced this problem with that exact code above; there was probably other activity in between those ...
SQL Server Identity column does not behave properly?
[ "", "sql", "sql-server", "" ]
I have a `veh_speed` table with the fields `vid`, `date_time`, `speed`, `status`. My objective is to get the duration(`start_date_time` and `end_date_time`) of the vehicle with speed greater than 30. Currently I am generating the report using `PL/SQL`. Is it possilble to do with an `SQL`. Also it would be great if it i...
You can use analytic functions to group your records into blocks where the speed is 30 or more: ``` select vid, date_time, speed, status, case when speed >= 30 then 30 else 0 end as speed_limit, row_number() over (partition by vid order by date_time) - row_number() over ( partition by vid, case when spee...
This problem is well-known as start-of-group, you can google this. Generic approach is a) identify criteria to differ rows satisfied criteria from others c) sort them in correct order d) making a group column for each period to split them in time e) group them. Just as example for particular case: ``` SQL> select vid...
Grouping the records on a specific criteria and to find the maximum value
[ "", "sql", "oracle", "oracle11g", "gaps-and-islands", "" ]
I'm trying to select all products names and how many has been sold in current date, but I'm having a problem since not all products are sold everyday. (When the product has not been sold it must return 0) TABLE PRODUCTS ``` ID NAME 1 APPLE 2 PINEAPPLE 3 COFFE ``` TABLE SALES ``` I...
try this ``` select name as PRODUCT , ifnull(sum(AMOUNT),0) amount from products p left join PRODUCTS_AND_SALES ps on p.id = ps.PRODUCT_ID group by product ``` [**DEMO HERE**](http://sqlfiddle.com/#!2/d0851/5) EDIT: if you wanna use specefic date then use this ``` select name as PRODUCT ,if(date = '2014...
Use OUTER JOIN instead of INNER JOIN if you show the query you use we will correct it for you.
Select sold and unsold products
[ "", "mysql", "sql", "select", "product", "" ]
given below table: ``` +----+---------+-----------+-------------+-------+ | ID | NAME | LAST NAME | PHONE | STATE | +----+---------+-----------+-------------+-------+ | 1 | James | Vangohg | 04333989878 | NULL | | 2 | Ashly | Baboon | 09898788909 | NULL | | 3 | James | Vangohg | 04333989878 ...
This query uses a CTE to apply a row number, where any number > 1 is a dupe of the row with the highest ID. ``` ;WITH x AS ( SELECT ID,NAME,[LAST NAME],PHONE,STATE, ROW_NUMBER() OVER (PARTITION BY NAME,[LAST NAME],PHONE ORDER BY ID DESC) FROM dbo.YourTable ) UPDATE x SET STATE = CASE rn WHEN 1 THEN NULL ELSE...
Try this statement. **LAST UPDATE:** ``` update t1 set t1.STATE = 'DUPE' from TableName t1 join ( select name, last_name, phone, max(id) as id, count(id) as cnt from TableName group by name, last_name, phone having count(id) > 1 ) t2 on ( t1.name = t2.name and t1.last_name = t2.last_name and ...
Find and update specific duplicates in MS SQL
[ "", "sql", "sql-server", "database", "duplicates", "" ]
I have Table T1 with Column C1,C2 and Table T2 with Column C3,C4,C5. I would like delete records from T1 where C1 = C3 AND C2 = C4 and C5 = '123'. What will be the query I tried following ``` DELETE FROM T1 WHERE (C1,C2) = SELECT (C3,C4) FROM T2 WHERE C5 = '123' ``` but this is not working.
There is no `WHERE (x,y) = (a,b)` syntax in SQL Server, sorry. This is how you perform a delete, based on a join, regardless of how many columns are involved in the join: ``` DELETE t1 FROM t1 INNER JOIN t2 ON t1.c1 = t2.c3 AND t1.c2 = t2.c4 WHERE t2.c5 = '123'; ```
You can do this using `exists`: ``` DELETE FROM T1 WHERE exists (SELECT 1 FROM T2 WHERE C5 = '123' and t2.c3 = t1.c1 and t2.c4 = t1.c2) ) ``` In general, using `exists` is better than using `in` with a subquery because NULLs can cause the latter to do behavior in strange ways.
Delete Query by joining multiple columns
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I was writing some tasks yesterday and it struck me that I don't really know **THE PROPER and ACCEPTED way** of checking if row exists in table when I'm using PL/SQL. For examples sake let's use table: ``` PERSON (ID, Name); ``` Obviously I **can't do** (unless there's some secret method) something like: ``` BEGIN ...
I wouldn't push regular code into an exception block. Just check whether any rows exist that meet your condition, and proceed from there: ``` declare any_rows_found number; begin select count(*) into any_rows_found from my_table where rownum = 1 and ... other conditions ... if any_rows_found...
IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in *my* world - yours may be different :-). In a typical app you're going to ...
Proper way of checking if row exists in table in PL/SQL block
[ "", "sql", "oracle", "select", "plsql", "" ]
Suppose I have the following table: Table USERS\_GROUPS ``` USER_ID | GROUP_ID 100 1 101 1 101 2 102 1 102 2 102 3 103 1 103 2 103 3 ``` I need to select only those users who has all groups (1, 2 and 3) i.e. Query result: ``` USER_ID 102 103 `...
The most flexible way to structure such a query is using `group by` and `having`. If you want those three specific groups: ``` select ug.user_id from users_groups ug group by ug.user_id having sum(case when group_id = 1 then 1 else 0 end) > 0 and sum(case when group_id = 2 then 1 else 0 end) > 0 and sum(...
You can use a combination of `WHERE`, `GROUP BY` and `HAVING` to get the result. The `WHERE` clause will include the list of the `group_ids` that you want. You will apply the `GROUP BY` clause to your `user_id` column and finally you will use the `HAVING` clause to get a count of the distinct `group_ids` - this count s...
How to select rows with given set of values
[ "", "sql", "" ]
I'm trying to limit results in a table to records with dates that don't overlap my data. As you can see in the screenshot below I'm trying to add a clause to filter out records that are equal to the "end" column. See the final line in the query for that. I can't figure out why results still show the record in the scre...
You basically have: ``` a OR b AND c AND d AND e AND f ``` ... and you probably want: ``` (a OR b) AND c AND d AND e AND f ``` Reference: [Operator Precedence](http://dev.mysql.com/doc/refman/5.5/en/operator-precedence.html)
`AND` has a higher [operator precedence](http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html) than `OR` has. That means that your `AND` clauses will be interpreted first so that at the end there's something like ``` where (...) or (... and ... and ...) ``` Since the first condition before the `OR` (`('20...
Why is this "where" clause not limiting sql results
[ "", "mysql", "sql", "select", "operator-precedence", "" ]
I'm trying to right a report to get a breakdown of all the ethnicities in my system by gender. I have this query that I thought was working, but all of the dates are the same in the query, which they are NOT in the individual tables. I think the group\_by is causing an issue, but i'm not 100% and i'm not sure how to p...
It seems that I was looking at the wrong tables `created_at` column in the between clause. ``` AND f1.created_at BETWEEN '2014-01-01' AND '2014-12-31' ``` should have been ``` AND v1.created_at BETWEEN '2014-01-01' AND '2014-12-31' ```
Each non-aggregate field in your select list should be included in your `GROUP BY`: ``` SELECT f1.field_name, f1.created_at, f2.created_at, count(*) AS total FROM application_fields f1 JOIN application_fields_values v1 ON v1.application_field_id = f1.id JOIN application_fields_values v2 ON v1.applicant_id = v2.applica...
Group by query causing incorrect data to appear
[ "", "mysql", "sql", "" ]
I need this select query to return the sum of the same column based on different where clauses. Basically just looking for a way to merge these multiple select queries. Please see below. Any help is very much appreciated! ``` DECLARE @prEndDate smalldatetime SET @prEndDate='2014-01-05' SELECT Employee, SUM(Amount) ...
You could use `UNION` or `CASE WHEN` clauses. ``` SELECT Employee, SUM(CASE WHEN EDLCode=100 AND EDLType='D' THEN Amount ELSE 0 END) as Deduction, SUM(CASE WHEN EDLCode=101 AND EDLType='D' THEN Amount ELSE 0 END) as DeductionPlus SUM(CASE WHEN EDLCode=600 AND EDLType='L' THEN Amount ELSE 0 E...
You can move the condition out of the `WHERE` clause and in to a `CASE` statement, so you only sum the rows that interest you: ``` DECLARE @prEndDate smalldatetime SET @prEndDate='2014-01-05' SELECT Employee, SUM(CASE WHEN EDLCode=100 AND EDLType='D' THEN amount ELSE 0 END) AS Deduction, ...
Multiple Sums off Same Column
[ "", "sql", "sum", "aggregate-functions", "where-clause", "" ]
I'm looking for a query capable of selecting from a single table in such a way that consecutive records for which an attribute is equal are collapsed together. Similar to group by, but instead of grouping every occurence of the attribute together, I want one group for each consecutive range. Example table: ``` +-----...
Could you try this? You can test here <http://www.sqlfiddle.com/#!2/57967/12>. ``` Select grp_new, group_concat(ord) From ( Select ord, if(grp = @prev, @seq, @seq := @seq + 1) as seq, if(grp = @prev, grp, @prev := grp) as grp_new From tab, (SELECT @seq := 0, @prev := '') AS init Order by ord ) x Group by gr...
Use: ``` select pquery.group, GROUP_CONCAT(pquery.order separator ', ') as order FROM ( select t.*, @lastSeq := if( t.group != @lastGroup , 0, @lastSeq + 1 ) as groupSeq, @lastGroup := t.group, @cont := if(@lastSeq =0, @cont + 1, @con...
Selecting groups of consecutive records with a common attribute?
[ "", "mysql", "sql", "" ]
I have a somewhat complex database structure running that tracks products. Here is a diagram of it generated by MySQL Workbench: ![Products Diagram](https://i.stack.imgur.com/kUxWs.png) Under this structure I have 3 products that I've added. All three of these products have the attribute `color` and an option of `red...
As others have said, your schema is the problem as you have a many to many relationship (many products may have many options) which makes queries more difficult. Here is a query that gives you the exact output you asked for. It shows each option, how many unique products that option is assigned to (the COUNT(distinct ...
See if this helps ``` SELECT products.product_name , products.product_id , pvc.combination_id , pvc.combination , pva.attribute , pvo.option , COUNT(pvo.option) as opt_count FROM (`products`) JOIN `product_variant_combinations` pvc ON `products`.`product_id` = `pvc`.`product_id` JOIN `product_variants` pv ON `pv`.`com...
COUNT(table_name.column_name) not giving accurate count. Am I applying GROUP BY on the wrong column?
[ "", "mysql", "sql", "count", "aggregate-functions", "product", "" ]
Basically I am attempted to auto populate a dropdown box with Team member names, this way in the future as team members get removed and added the dropdown will automatically adjusted. This is the simple part, the hard part is that I also need “All” to show up in the dropdown box. Though I can’t seem to find any way to ...
I ended up having to create this function to do what I needed. ``` Sub ValueList(ByRef rs As Recordset, _ strReturnColumn As String, _ strCtrlToChange As String, _ strDefaultValueIn As String, _ frm As Form) Dim strRowSource As String Dim strDefaultValue As String ...
Use a union ``` SELECT 0 AS [Team_Member_ID], 'All' AS [USER_ID] UNION SELECT [team table].[team_member_id], [team table].[user_id] FROM [team table] WHERE [active] = true ORDER BY [user_id]; ```
How do I concatenate a string onto an SQL query in Access?
[ "", "sql", "ms-access", "ms-access-2010", "" ]
I been researching how to convert a date string that I have in my flatfile with also specifying a time. I found results for converting through a derived column in SSIS using DT\_DBTIMESTAMP. But in my situation, I need to add in a time of 9AM: 9:00:00.000 as well since the flat file source doesn't have it. So in my si...
Try this: ``` DATEADD("HH",9,(DT_DBTIMESTAMP)((DT_STR,30,1252)(DT_DBDATE)([Create Date]))) ``` [Create Date]= 5/9/80
Use the Data Conversion to first change the date to the DT\_DBTIMESTAMP then use a derived with the following in the expression; ``` DATEADD("Hh",9,[COLUMN]) ``` Obviously changing the column to the one in your dataflow. This should add 9 hours onto the timestamp.
SSIS: convert date to datetimestamp with specified time
[ "", "sql", "ssis", "substring", "" ]
I need to store a set of flags that are related to an entity into database. `Flags` might not be the best word because these are not binary information (on/off), but rather a to-be-defined set of codes. Normally, you would store each information (say each flag value) in a distinct column, but I'm exploring opportuniti...
If performance is an issue I would go for a some different model here. Say a table that store entities and a relation 1->N to another table (say: flags table: entId(fk), flag, position) and this table would have an index on flag and position. The issue here would be to get this flags in a simple column wich can be do...
If you want a database-independent, reasonable method for storing such flags, then use typical SQL data types. For a binary flag, you can use `bit` or `boolean` (this differs among databases). For other flags, you can use `tinyint` or `smallint`. Doing bit-fiddling is *not* going to be portable. If nothing else, the f...
Storing flags in SQL column, and indexing them
[ "", "sql", "multi-database", "" ]
I have a task management app where the user can create a "waiting for" on a task. If the item that they're waiting for hasn't been received, then the task is still active. I'm trying to set the "actionable" scope to include the tasks that either: * Have a waiting\_for where the received\_date is not nil (whatever the...
Try updating your scopes to this, using the NOT IN feature of SQL: ``` scope :received, -> {includes(:waiting_fors).where("tasks.id not in (select tasks.id from tasks inner join waiting_fors on waiting_fors.task_id = tasks.id where waiting_fors.received_date is null)")} scope :actionable, -> {incomplete.not_snoozed.w...
Do you mean ``` where("waiting_fors.received_date = ?", nil) ``` instead of ``` where("waiting_fors.received_date IS NOT ?", nil) ```
Rails scope with associations - optionally filtering scope with properties of associated class
[ "", "sql", "ruby-on-rails", "" ]
``` Person Table ------------------------------------- PersonId | Name | Surname | ------------------------------------- 1 John Smith 2 Sam Rainbow Address Table ------------------------------------------ AddressId | PersonId | Address | ---------------------...
You need to define a foreign key: ``` ALTER TABLE Address ADD FOREIGN KEY (PersonId) REFERENCES Person (PersonId) ```
Add a foreign key constraint and restrict deletes: ``` ALTER TABLE Address ADD CONSTRAINT Address_PersonId_fkey FOREIGN KEY (PersonId) REFERENCES Person (PersonId) ON DELETE RESTRICT -- what you asked for ON UPDATE CASCADE; -- maybe do something different for updates? ```
Relation between tables
[ "", "sql", "" ]
I'm trying to fix up data where a column which is storing a number of bit flags in an int column. What's happened is somewhere along the lines, an incorrect flag has been set (6) so I need to prepare a script to fix up the affected records. I've tried performing some queries to extract data that appears wrong but it'...
I am assuming you are talking about `bit masking` here in this case. With that assumption, I do not think you will be able to just query the data for a fix. The way `bit masking` works is to add up the values of all the bits(i.e. convert the binary to an int) so the following mask: `1001` would be stored as 9 If you ...
Note that bit 31 can be problematic when handling 32-bit signed values. Otherwise: ``` -- Check each bit in an integer. declare @Sample as Int = 6; with Bits as ( select Cast( 1 as BigInt ) as BitMask, 0 as BitPosition union all select Bitmask * 2, BitPosition + 1 from Bits where BitPosition < 31 ) sel...
Fixing the wrong 'bit'
[ "", "sql", "sql-server", "bit-manipulation", "" ]
I have a fairly complex SQL query - part of which requires to look up a company\_ID value found in the first table to obtain the company\_Name in the second table. The second table may have variants of the company name, but that is OK - I just need the first match. So, tableA looks something like this (approx 2 dozen ...
``` SELECT *, t2.company_name FROM tableA t1 JOIN tableB t2 ON t1.company_id = cast(t2.company_id as CHAR(12)) GROUP BY t1.company_id ``` Will return 1 row for each unique `t1.company_id`
Instead of user2989408's MAX subquery you can also do a ``` SELECT company_id , company_Name FROM tableB QUALIFY ROW_NUMBER() OVER (PARTITION BY company_id ORDER BY company_name) = 1 --if you don't care about MIN/MAX or want a more random result: QUALIFY COUNT(*) OVER (PARTITION BY company_id ROWS UNBOUNDED PRECEDIN...
How do I just get the first matching row?
[ "", "sql", "teradata", "" ]
I’m in the process of creating a report that will tell end users what percentage of a gridview (the total number of records is a finite number) has been completed in a given month. I have a gridview with records that I’ve imported and users have to go into each record and update a couple of fields. I’m attempting to cr...
The following query should provide what you are looking for: ``` Declare @DivNumber decimal(5,1); SET @DivNumber = (.01 * 2541); SELECT CAST(ROUND(@DivNumber / Count(date_record_entered), 1) AS decimal(5,1)) FROM dbo.tablename WHERE date_record_entered IS NOT NULL and date_record_entered >= 20131201 ...
Why do you select the constant value `cast(round(@divNumber / @DateCount, 1) as decimal(5,1)`from the table? That's the cause of your problem. I'm not too familiar with sql server, but you might try to just select without a from clause.
How to accurately figure percentage of a finite total
[ "", "sql", "sql-server", "gridview", "sql-server-2012", "" ]
I have the following sql ``` case gg.finalgrade when NULL then 'Nothing to Show' else gg.finalgrade end as 'Grade' ``` Many of my gg.finalgrade values is shown in the database as NULL, but the above statement simply ignores those values and does not print anything. I want it to show 'Nothing to Show' when the va...
Don't bother using a case expression for this, MySQL has a funciton built in called `IFNULL()` Have a look here for an example of how this works: [SQL NULL Functions](http://www.w3schools.com/sql/sql_isnull.asp) The syntax is: ``` SELECT IFNULL(gg.finalgrade,'Nothing to Show') ```
In SQL this expression is never true: ``` null = null ``` So comparing two values with null will always be false You can use something like this ``` coalesce(gg.finalgrade, 'Nothing to show') ``` or ``` case when gg.finalgrade is null then 'Nothing to show' else gg.finalgrade end ```
SQL - CASE NULL
[ "", "mysql", "sql", "" ]
I have a condition where I want to display a status of Approved or Rejected. I have been given a database which was created by someone and is in a mess. Not structured. I have a table with names and process\_code like below for example : ``` name | process_code A | 7 B | 7 C | 3 D | 4 ... ``` What I w...
just missing the `end` of the case when clause, and a comma (and not sure you need quotes around process\_code). ``` SELECT name, process_code AS Status, CASE process_code WHEN '7' THEN 'Rejected' ELSE 'Approved' END FROM association ```
First you need a comma before the case and you need an `end`: ``` SELECT name, process_code AS Status, (CASE process_code WHEN '7' THEN 'Rejected' ELSE 'Approved' END) FROM association; ``` If the code is actually an integer, you might need to make the comparison without the si...
In SQL Query, use CASE to print desired result if condition is met
[ "", "sql", "case", "" ]