Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is it possible to delete part of string using regexp (or something else, may be something like CHARINDEX could help) in SQL query? I use MS SQL Server (2008 most likely). Example: I have strings like "*[some useless info]* **Useful part of string**" I want to delete parts with text in brackets if they are in line.
You can use the PATINDEX function. Its not a complete regular expression implementation but you can use it for simple things. > **[PATINDEX (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms188395.aspx)**> Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if...
Use **REPLACE** for example : ``` UPDATE authors SET city = replace(city, 'To Remove', 'With BLACK or Whatever') WHERE city LIKE 'Salt%'; // with where condition ```
Transact SQL replace part of string
[ "", "sql", "sql-server", "t-sql", "" ]
I am having trouble executing this statement. What I am trying to achieve here is that my result will be sorted with a condition with the use of a parameter. For example, I would like to sort the userName in ascending order, therefore, in my web application coding I have a parameter @condition, when it reads 'userNam...
When you order by a case statement all possible outputs of the case must be of the same type. You need to break your case statement down into multiple case statements. Each case statement should return a single type and `NULL` for the else case. You can combine all those cases into one order by.
You maybe want to try something like this: ``` CASE WHEN @condition = 'username' THEN username WHEN @condition ='joinDate' THEN joinDate WHEN @condition = 'userName' THEN userName WHEN @condition = 'Name' THEN (C.firstName+' '+C.lastName) WHEN @condition = 'dob' THEN dob WHEN @condition = 'use...
SQL Sorting: ORDER BY with parameters
[ "", "sql", "sorting", "sql-order-by", "case", "" ]
I'm very new to SQL, I'm trying to define a 2 tables `Hospital` and `Hospital_Address` but when I'm trying to add foreign key in `Hospital_Address` it throws an error: `"1215: Cannot add foreign key`" ``` create table Hospital ( HId Int not null, HName varchar(40) not null, HDept ...
MySQL requires that there be an index on the `HAreaCd` column in the parent `Hospital` table, in order for you to reference that column in a FOREIGN KEY constraint. The normative pattern is for the FOREIGN KEY to reference the PRIMARY KEY of the parent table, although MySQL extends that to allow a FOREIGN KEY to refer...
You cannot add a foreign key to a non-primary key element of another table usually. If you really need to do so, refer to this question for help : [Foreign Key to non-primary key](https://stackoverflow.com/questions/18435065/foreign-key-to-non-primary-key)
MySQL Error Code 1215: Cannot add foreign key Constraint
[ "", "mysql", "sql", "" ]
The following is my query to go through about a million rows to calculate MTBUR (Mean Time Before Unscheduled Repair): ``` DECLARE @BeginDate date = '01-01-2013', @EndDate date = '12-31-2013' BEGIN SELECT H.AutoType, COALESCE(((SUM(H.Hours))/(CASE WHEN R.ReceivedDate BETWEEN @BeginDate AND @EndDate THEN COUN...
You are correct, adding ReceivedDate is screwing up your results. You are getting one row for each type for RecievedDate. SQL Server if forcing you to add RecievedDate to the group by because you are using it in the select clause. When SQL Server processes each AutoType, what ReceivedDate should it use? It has multipl...
You need to include R.ReceivedDate from your calculation in the group by because you're evaluating the column with the between statement. Its the same as including the column in the select. Basically any column in the select line that doesn't have an aggregation function needs to be in the group by.
SQL Aggregate Function Query not Producing Expected Results
[ "", "sql", "sql-server", "group-by", "aggregate-functions", "" ]
I have a table containing blobs of document text that I am joining to. Using oracle text, i can get the snippet of text containing my search term (using ctx\_doc.snippet). However, I must now specify the number of times this search term was found for each document that matched my join not all documents that i have. I h...
You can continue using CTX\_DOC; the procedure [HIGHLIGHT](http://docs.oracle.com/cd/E11882_01/text.112/e24436/cdocpkg.htm#CCREF0706) can be contorted slightly to do exactly what you're asking for. Using this environment: ``` create table docs ( id number, text clob, primary key (id) ); Table created. insert all i...
If by "blobs of document text" you mean "clob", then you can use this tried true method. Take the difference between length of the document and the length of the document with the search string replaced by something else. That will give you the number of matches. For example: ``` select t.* from (select t.*, ...
Counting the number of hits for a given search query/term per document in Oracle
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle-sqldeveloper", "" ]
So we are building this app, where the retrieval of data is based on small, modular queries. So for a product it would be something like: ``` $product = $this->product->getProductData($prod_id); //get main product record $locations = $this->locations->getAvailableLocations($prod_id); //sale locations $comments = $this...
There's overhead associated with each execution of a SQL statement. Packets sent to the server, SQL text parsed, statement verified to syntactically correct (keywords, commas, parens, etc.), statement verified to be semantically correct (identifiers reference tables, columns, function, et al. exist and user has suffici...
Use your second example (all joins in one query). As long as you have an index on "prod\_id" and anything else you're filtering on or joining on, the database query optimizer will do smart things, such as seeing that prod\_id will only return a few records and that doing that first will make the query about as fast as ...
large single join queries vs multiple smaller ones
[ "", "mysql", "sql", "performance", "join", "scalability", "" ]
I have a table like this **tbl\_user** ``` id user_id amount ``` first i want to update a row based on id ``` $amount = 123; // dyanamic value $sql = "UPDATE tbl_user SET amount=amount-'$amount' WHERE id='$id' LIMIT 1 "; ``` now i want to get updated value of amount column i have applied this sql ``` $sql = "SELE...
The best you could imitate is to use two lines of queries, probably using a variable like: ``` UPDATE tbl_user SET amount = @amount := amount-'$amount' WHERE id='$id' LIMIT 1; SELECT @amount; ``` The best you could do then is to create a `Stored Procedure` like: ``` DELIMITER // CREATE PROCEDURE `return_...
A function can do this easily. It sounds like you want to limit how many times your code connects to the database. With a stored function or procedure, you are only making one connection. Yes, the stored function has two queries inside it (update then select), but these are executed on the server side without stopping ...
mysql update column then select updated value
[ "", "mysql", "sql", "" ]
I have table with two columns. Depending on the length of the data in one column, I need to join the next column. How can i proceed with this. I have the base SQL up but i cant join the columns together and display both data into one table. The current table is like this : ``` ID Code ---------- ------...
Based on your explanation I'm guessing: ``` SELECT CASE WHEN ((LEN(ID))<5) THEN (RTRIM(ID)+LTRIM(Code)) ELSE ID END AS ID FROM tblID ORDER BY ID DESC ``` The syntax of your `CASE` was a bit off, as well as the comparison on length (`<>5` vs `<5`).
Try this: ``` SELECT CASE WHEN LEN(ID) < 6 THEN LEFT(ID + Code),6) ELSE ID END AS Code FROM tblID ORDER BY ID DESC; ```
Check the length and add corresponding column
[ "", "sql", "sql-server", "" ]
I have two tables. Table-A filled with transactional data. Table-B being a reference table for rates given a particular week. I would like to get the rate from Table B into Table A based on the Date being within the week outlined in Table B. I tried multiple query techniques and all fell flat on their face. Any help wo...
``` UPDATE A, B SET A.Rate = [B].[Rate] WHERE (([A].[DT] Between [B].[StartDate] And [B].[EndDate])); ``` I changed `A.Date` to `A.DT` because `Date` is a reserved word in Access.
Try this : ``` select b.rate from a,b where a.date <= b.end_date and a.date >= b.start.date ``` OR ``` select b.rate from a,b where a.date between b.start_date and b.end_date ```
Query based on date range
[ "", "sql", "ms-access", "vba", "" ]
Having a tough time with this one. I have a Job model, and a JobStatus model. A job has many statuses, each with different names (slugs in this case). I need an 'active' method I can call to find all jobs where none of the associated statuses has a slug of 'dropped-off'. ``` class Job < ActiveRecord::Base belongs_to...
``` Job.where.not(id: JobStatus.where(slug: 'dropped-off').select(:job_id)) ``` will generate a nested subquery for you.
Not the cleanest method, but you could use two queries. ``` # Getting the ID of all the Jobs which have 'dropped-off' JobStatuses dropped_off_ids = JobStatus.where(slug: 'dropped-off').pluck(:job_id) # Using the previous array to filter the Jobs Job.where.not(id: dropped_off_ids) ```
Rails 4: ActiveRecord or MySQL query where no related models have attribute
[ "", "mysql", "sql", "ruby-on-rails", "ruby", "activerecord", "" ]
I've a table named `ExamResult` which has following columns ``` studentId, Subject, Standard, Marks ``` and i've following values in my table for studentId=1 ``` 1,maths,9,78 1,english,9,80 1,history,9,67 1,geography,9,90 ``` for studentId=2 ``` 2,maths,9,68 2,english,9,83 2,history,9,70 2,geography,9,69 ``` sim...
Try: ``` SELECT stu.name, exam.standard, AVG(stu.marks) as 'Percentage' FROM Student stu INNER JOIN ExamResult exam ON stu.Id=exam.studentId; GROUP BY stu.name, exam.standard ``` NOTE: This is biased towards Microsoft SQL Server's flavor of SQL. You didn't specify which version you were using. Hopefully you can ...
Have you worked with group-by clause? ``` select stu.name,exam.standard, **average(marks) as Percentage** from Student stu inner join ExamResult exam on stu.Id=exam.studentId **group by stendent_id order by Percentage desc** ```
Calculate percentage in SQL
[ "", "sql", "" ]
I need to make a table that contains a row of every date from 01/01/2012 to present and a count of how many bugs were currently open on each date. This is the data I have, in a table called `Bugs`: `BugID`, `CreatedDate`, `UpdatedDate`, `Status` (status can be open or closed). If the bug is closed, then the UpdatedDat...
``` declare @bugs table(BUGID int,Createddate datetime,Updateddate datetime,Status char(1)) insert into @bugs Select 1,'20140101',NULL,'I' UNION Select 2,'20140102','20140110','U' UNION Select 3,'20140103','20140110','C' UNION Select 4,'20140104',NULL,'I' UNION Select 5,'20140105','20140110','U' UNION Select 6,'2014010...
``` WITH D AS ( SELECT @RangeStartDate DateValue UNION ALL SELECT DateValue + 1 FROM D WHERE DateValue + 1 < @RangeEndDate ) Select D.DateValue, coalesce(count(BugID),0) FROM D LEFT JOIN Bugs B on B.CreateDate <= D.Datevalue and (B.UpdateDate >= D.DateValue or B.UpdateDate is null) Group By D.DateValue...
SQL - Count total bugs open per day
[ "", "sql", "sql-server", "" ]
I have two tables in my SQLite Database (dummy names): **Table 1:** FileID F\_Property1 F\_Property2 ... **Table 2:** PointID ForeignKey(fileid) P\_Property1 P\_Property2 ... The entries in Table2 all have a foreign key column that references an entry in `Table1`. I now would like to select entries from `Table2` w...
The `=` operator compares a single value against another, so it is assumed that the subquery returns only a single row. To check whether a (column) value is in a set of values, use IN: ``` SELECT * FROM Table2 WHERE fileid IN (SELECT FileID FROM Table1 WHERE F_Property1 > 1) ```
The way joins work is not by "mixing" the data, but sort of combining them based on the key. In your case (I am assuming the key field in Table 1 is unique), if you join those two tables on the primary key field, you will end up with all the entries in table2 plus all corresponding fields from table1. If you were doing...
Select values from one table depending on referenced value in another table
[ "", "sql", "sqlite", "" ]
**Query** ``` SELECT DISTINCT code, hour(datetime), sum(price) FROM something ORDER BY code; ``` I have one result table with 3 columns `code`, `hour`, `sum`. I would like to have as many tables as there are different `code`. a code = a table and each table containing "code" (which will be the same in the table), "...
First, your query would more appropriately be written as: ``` SELECT code, hour(datetime), sum(price) FROM something GROUP BY code, hour(datetime) ORDER BY code; ``` If you want a separate result table for each code, you need to create the tables separately. The basic statement is: ``` CREATE TABLE table_code1 as ...
Use union statement for concate mulitple query > `SELECT column_name(s) FROM table1 > UNION > SELECT column_name(s) FROM table2;`
Split a table from a query to many tables (with "DISTINCT")
[ "", "mysql", "sql", "" ]
In my software system, an important lookup column historically had one of three numeric values. We're now going to allow more values in between, but I still need to be able to map all in-between values on the original three-point scale. The system is for rating positive, neutral, and negative based on an integer valu...
I think this is what you're after: ``` INNER JOIN @SiteIDs sti ON sti.SiteID = s.SiteID --AND d.SiteID IN (ISNULL(@SiteIDList, d.SiteID)) AND ISNULL(s.DatePosted, '1/1/1901') >= ISNULL(@StartDate, '1/1/1900') AND ISNULL(s.DatePosted, '1/1/9998') <= ISNULL(@EndDate, '1/1/9999') AND s.Favorite = CASE WHE...
Is this what you want? ``` AND @SID is null or @SID = 6 and SID in (-2, -3, -4, -5) ```
how can I make a single join value match a range of values
[ "", "sql", "inner-join", "" ]
I have a table called `Tasks`. I want to sum the number of tasks status types (open, closed) and priorities grouped by project. Something like this: ``` =============================================================================================== | Project | Closed | Major | Moderate | Minor | Tot...
I would use a subquery to determine the priority and then use that in your outer query: ``` SELECT Project ,count(status) as "Status Count" ,sum(case when status = 'Closed' then 1 else 0 end) as Closed ,sum(case when status = 'Open' then 1 else 0 end) as "Open" -- ,sum(case whe...
One way would be preparing a data source with the results of substring searches, exposing that source as a *Common Table Expression* (CTE), and basing the `GROUP BY` on that source: ``` WITH Task_CTE (Project, Status, Closed, Open, Major, Moderate, Minor) AS ( SELECT Project, status , case w...
SQL sequential IF conditions
[ "", "sql", "sql-server", "" ]
For example: ``` Field1 | Field2 | Field3 | -------------------------- the | lazy | dog ``` into ``` Field1 | Field2 | Field3 | History -------------------------------------- the | lazy | dog | thelazydog ``` Don't care about spaces etc.
Try something like : ``` INSERT INTO Table (Field1, Field2, Field3, History) (Field1, Field2, Field3, Field1+Field2+Field3) ```
Use a virtual column. to handle summing null values use isNull. ``` CREATE TABLE Example ( ID int IDENTITY (1,1) NOT NULL , field1 smallint , field2 smallint , field3 smallint , history AS isnull(field1,0) + isnull(field2,0) + isNull(field3,0) ); ```
How can I merge 2 (or more) columns into a new one for each SQL row?
[ "", "sql", "sql-server-2008", "" ]
I have a table with costumers that are active or inactive. The inactive is the ones who are more then 1 year without any payment. I need to know how many inactive became active the first semester of this year. I only have a table with: "costumer id, amount paid, date paid, status" I'm trying something like that: ```...
Try this, and add some data samples in SQLfiddle to tune this query. ``` select DISTINCT f1.COSTUMER_ID from finance f1 where (DATEPAID >= '2014-01-01' and DATEPAID < '2014-07-01') and datediff(d, ( select top 1 f2.DATEPAID from finance f2 where DATEPAID <> f1.DATEPAID and f1.COSTUMER_ID=f2.COS...
You want to look at the maximum of the date paid for customers who are currently inactive. This seems to implement your business rules: ``` select CUSTUMER_ID, max(DATEPAID) as maxdp from finance group by CUSTUMER_ID having maxdp < '2013-07-01'; ``` Note that I changed `COSTOMERID` to `CUSTOMERID`, which is the bett...
SQL Select help - who paid this year but is inactive
[ "", "sql", "sql-server", "select", "" ]
`select player,date from nba.player_stats where tm='NOP';` This returns a column of NBA players for the New Orleans Pelicans and a column of dates of games that the players played in. There are multiple players for each date. When a player gets hurt and does not play, the player does not show up in the player column f...
This will show all players that played on dates when Ryan Anderson did not play ``` select player, date from nba.player_stats where date not in (select date from nba.player_stats where player = 'Ryan Anderson') ```
There are many ways to write the query, here are a few examples (all selecting NOP players that played when Ryan Anderson did not); Using NOT IN, just check dates where he plays and exclude those; ``` SELECT player, date FROM player_stats WHERE tm = 'NOP' AND date NOT IN ( SELECT date FROM player_stats WHERE play...
SQL - Select Only Players and Dates When a Date Does Not Contain a Player
[ "", "sql", "" ]
I have two table one say `Employee` with columns as ``` EmpId Name Class Region 1 rr x t 2 tr v g ``` Another table `ConfidentalEmployee` with columns as ``` EmpId(foreign key) Name 1 rr ``` Now have to write query with all the fields of Employee table but those Employee's ...
You can try this query ``` SELECT Emp.EmptId, Emp.Name, CASE WHEN CEmp.EmpId IS NULL THEN Emp.Class ELSE 'CAN''T DISCLOSE' END AS Class, CASE WHEN CEmp.EmpId IS NULL THEN Emp.Region ELSE 'CAN''T DISCLOSE' END AS Region FROM Employee AS Emp LEFT JOIN ConfidentialEmployee CEmp ON Emp.EmpId = CEmp.EmpId ``...
You want a join, specifically a `left outer join` and check for matches: ``` select e.EmpId, coalesce(ce.Name, e.Name) as Name, (case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Class end) as class, (case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Region end) as region from empl...
Need Union kind of behavior without using Union of queries/resultset
[ "", "sql", "sql-server", "" ]
I got table like this: ``` Col1 | Col2 AAA | 1 BBB | X AAA | X CCC | 1 ``` I want to find duplicates based on Col1. Then i want to leave the row which has 'X' in Col2 and delete the other one. I found how to find the duplicates: ``` SELECT col1, col2, col3=count(*) INTO holdkey FROM t1 GROUP BY col1, col2 HAVIN...
Assuming the table is called test, this should work. I just tried it :-) ``` DELETE From test WHERE Col1 IN( SELECT Col1 FROM test GROUP BY Col1 HAVING COUNT(1) > 1) AND Col2 = '1' ```
This is a good use of updatable CTEs and window functions: ``` with todelete as ( select t1.*, count(*) over (partition by col1) as cnt from t1 ) delete from todelete where cnt > 1 and col2 <> 'X'; ```
Find duplicate rows and delete specific one
[ "", "sql", "sql-server", "sql-server-2000", "" ]
I'm having a hard time summing up a column on two tables. The scenario is something like this (refer to the image below) ![enter image description here](https://i.stack.imgur.com/ct6pT.png) Table 1 may have a lot of rows per Date. But Table 2 may only consists of two rows of data per Date. What I wanted to do is to s...
Use a `UNION` clause like this: ``` WITH t(d, p) AS ( SELECT [Date], Price FROM Table1 UNION ALL SELECT [Date], Price FROM Table2 ) SELECT d, SUM(p) FROM t GROUP BY d ```
You can do this with `UNION ALL` in either a subquery or a cte, cte shown here: ``` ;WITH cte AS (SELECT [Date], Price FROM Table1 UNION ALL SELECT [Date], Price FROM Table2 ) SELECT [Date], SUM(Price) AS Total_Price FROM cte GROUP BY [Date] ``` ...
SQL SUM function inquiry
[ "", "sql", "sql-server", "" ]
So I want to insert a new column into a table using mysql. Here is an example of a insert-into function from w3schools ``` INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers WHERE Country='Germany'; ``` I've attempted to modified it a bit in order to basically select and insert...
You need to have each in a sub-select like below: ``` INSERT INTO table0 (integerVar1, integerVar2, booleanVar1) SELECT (SELECT int1 FROM table1 WHERE aString = 'something'), (SELECT int2 FROM table2 WHERE bString = 'otherthing'), 0; ``` However, keep in mind that if you have more than one value returne...
The following would work for you as long as the sub queries only returned one row ([**SQL Fiddle**](http://sqlfiddle.com/#!2/18210/1/0)): ``` INSERT INTO table0 (integerVar1, integerVar2, booleanVar1) SELECT (SELECT int1 FROM table1 WHERE aString = "something") AS integerVar1, (SELECT int2 FROM table2 WHERE bSt...
how to select more than one foreign key in a mysql query
[ "", "mysql", "sql", "insert", "foreign-keys", "subquery", "" ]
I have table like this: ``` ********************************** * row * field * item * content * ********************************** * 1 * 231 * 10 * A * * 2 * 232 * 10 * C * * 3 * 231 * 11 * A * * 4 * 232 * 11 * B * ********************************** ``` I woul...
Group by the `item` and take only those having your conditions ``` select item from your_table group by item having sum(case when field=231 and content='A' then 1 else 0 end) > 0 and sum(case when field=232 and content='B' then 1 else 0 end) > 0 ```
I think the most general way to approach this type of problem is with `group by` and `having`: ``` select item from table t group by item having sum(case when field=231 and content=A then 1 else 0 end) > 0 and sum(case when field=232 and content=B then 1 else 0 end) > 0; ``` Each condition in the `having` clau...
SQL query - how to construct a multirow dependent where clause
[ "", "sql", "where-clause", "" ]
I have a Query that is pulling in data for the current month for my by default. I then have a "Filter" option on my page where they can enter in some data to filter the content by and re-run the query. I have my select statement working for the current month however I am not quite sure how to implement the logic for f...
By looking at *"If there is a value in the filter, it needs to look up submissions just on those values category=3 department=5. However, when there those are empty on the filter settings, it needs to ignore the category and department and get me the record regardless of what the value is."* So let say you have filter...
If you need the query hardcoded in sql try: ``` where (category = @category or @category is null) ``` and keep that format for all the variables. If a category is provided, then it filters on the provided value. Otherwise all the rows are returned since the parameter is null. If you can dynamically build the sql que...
TSQL Optional Where Clause
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I am writing a T-SQL stored procedure that conditionally adds a record to a table only if the number of similar records is below a certain threshold, 10 in the example below. The problem is this will be run from a web application, so it will run on multiple threads, and I need to ensure that the table never has more th...
One option would be to use the [sp\_getapplock](http://msdn.microsoft.com/en-us/library/ms189823.aspx) system stored procedure. You can place your critical section logic in a transaction and use the built in locking of sql server to ensure synchronized access. Example: ``` CREATE PROC MyCriticalWork(@MyParam INT) ...
Use `SERIALIZABLE`. By definition it provides you the illusion that your transaction is the only transaction running. Be aware that this might result in blocking and deadlocking. In fact this SQL code is a classic candidate for deadlocking: Two transactions might first read a set of rows, then both will try to modify t...
Conditionally inserting records into a table in multithreaded environment based on a count
[ "", "sql", "sql-server", "multithreading", "t-sql", "" ]
Please take a look at this **[Fiddle Example](http://sqlfiddle.com/#!2/420819/21/0)** I want to convert each field into a row from this table: ``` CREATE TABLE product (`ID` int, `name` varchar(1), `category` varchar(11), `price` int,`year`int) ; INSERT INTO product (`ID`, `name`, `category`, `price`,`year`)...
This will give you expected output: ``` SELECT 'name' AS `field`. GROUP_CONCAT(DISTINCT `name` ORDER BY `name`) AS `value` FROM product UNION ALL SELECT 'category' AS `field`. GROUP_CONCAT(DISTINCT `category` ORDER BY `category`) AS `value` FROM product UNION ALL SELECT 'price' AS `field`. GROUP_CONCAT(DISTINCT `pric...
something like this?? Using union all for better proformance and incase there are any dupilcates. ``` SELECT 'name' field, group_concat(DISTINCT name ORDER BY name SEPARATOR '|') value FROM product UNION ALL SELECT 'category' field, group_concat(DISTINCT category ORDER BY category SEPARATOR '|') value FROM product UNI...
Converting column into row using "|" as separators
[ "", "mysql", "sql", "max", "group-concat", "" ]
I have a `Log` model with following columns: ``` ["id", "username", "event", "parameters", "extras", "created_at", "updated_at"] ``` I have indexes `created_at` and `username`. Now, I would like to get the first log for each `username` ordered by `created_at`. One way to do this is to run the following query for e...
Another case for `DISTINCT ON`: ``` SELECT DISTINCT ON (username) * FROM log ORDER BY username, created_at; ``` Returns *the whole row* for the "first" entry per `username`. Details: * [Select first row in each GROUP BY group?](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7...
I think `group by` clause would do the trick. ``` Log.group(:username).order(:created_at) ``` This will give you a query like this: ``` SELECT `logs`.* from `logs` GROUP BY username ORDER BY `logs`.`created_at` ASC ``` which will return first record for each `username`.
Get a list of first record for each group
[ "", "sql", "ruby-on-rails", "postgresql", "activerecord", "greatest-n-per-group", "" ]
I'm trying to set a column in the fabcon table only if the original column is null. This is the code I've already tried. ``` UPDATE dbo.fabcon SET ext = COALESCE(ext, ( SELECT CASE WHEN [<3] IS NOT NULL THEN '3' END AS extent FROM dbo.spreadsheetData )) ``` This is the...
You need a link between the table `fabcon` and `spreadsheetData`. Assuming it is called `id`: ``` UPDATE dbo.fabcon SET ext = (SELECT CASE WHEN [<3] IS NOT NULL THEN '3' END) FROM dbo.spreadsheetData ssd WHERE ssd.id = fabcon.id ) WHERE ext IS NULL; ``` Note that I remov...
``` DECLARE @PAth INT Select @path = COALESCE(ext,'')+[<3]+';' FROM dbo.spreadsheetData UPDATE dbo.fabcon SET ext = CASE WHEN @PAth IS NOT NULL THEN '3' ELSE '' END AS Extent FROM dbo.fabcon f WHERE f.id = @path ``` may be this works i think
SQL Update when not null
[ "", "sql", "sql-server", "" ]
I have a SQL Server database where I would like to take one main table that has columns that contain IDs and join? them with 3 other tables where those IDs match actual names. Example Table = slips looks like this: ``` ID | UserID | ClientID | TimeID --------------------------------- 10 | 35 | 48 | 27 ``...
``` SELECT s.ID, u.NickName1 As UserID, c.NickName1 As ClientID, t.NickName1 As TimeID FROM Slips s LEFT JOIN Username u ON u.ID = s.UserID LEFT JOIN ClientNames c ON c.ID = s.ClientID LEFT JOIN TimeactNames t on t.ID = s.TimeID ``` Depending on your data, you may want INNER JOINs instead of LEFT JOINs.
You can try this query ``` SELECT Slips.ID,Usernames.Nickname1 AS UnserID,Clientnames ,Nickname1 AS ClientID ,Timeactnames.Nickname1 AS TimeId FROM Slips LEFT JOIN Usernames ON Slips.UserId = Usernames.ID LEFT JOIN Clientnames ON Slips.ClientId = Clientnames.ID LEFT JOIN Timeactnames ON Slips.TimeId = Tim...
SQL create query based on data from multiple tables
[ "", "sql", "sql-server-2008", "join", "union", "" ]
I want to use ORDER BY on every UNION ALL queries, but I can't figure out the right syntax. This is what I want: ``` ( SELECT id, user_id, other_id, name FROM tablename WHERE user_id = 123 AND user_in IN (...) ORDER BY name ) UNION ALL ( SELECT id, user_id, other_id, name FROM tablename WHERE user_id = 456 AND us...
Something like this should work in MySQL: ``` SELECT a.* FROM ( SELECT ... FROM ... ORDER BY ... ) a UNION ALL SELECT b.* FROM ( SELECT ... FROM ... ORDER BY ... ) b ``` to return rows in an order we'd like them returned. i.e. MySQL seems to honor the `ORDER BY` clauses ins...
You just use one ORDER BY at the very end. The Union turns two selects into one logical select. The order-by applies to the entire set, not to each part. Don't use any parens either. Just: ``` SELECT 1 as Origin, blah blah FROM foo WHERE x UNION ALL SELECT 2 as Origin, blah blah FROM foo WHERE y ORDER BY Origin, z `...
How to use ORDER BY inside UNION
[ "", "mysql", "sql", "union", "" ]
I have a calculated field in my query that looks like this: ``` (SELECT avg(RateAmount)/1.15 FROM ReservationStayDate f where f.ReservationStayID = a.ReservationStayID) AS 'Rate Amount Excl.VAT' ``` In the same query, I need to exclude all data where RatePlan begins with 'CO' AND the above result = 0 In other words,...
Without your full query I can't give an exact solution, but in SQL Server you can use [APPLY](http://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx), which will works like a subselect, but it will allow you to reuse the column created, and also create multiple columns. e.g. ``` SELECT a.SomeField, ...
Take your existing query and remove this bit of the WHERE clause: ``` and (avg(RateAmount)/1.15)= 0 ``` then rewrite it like this: ``` SELECT * FROM ( <your original query> ) a WHERE a.[Rate Amount Excl.VAT] != 0; ``` That isn't the prettiest way to do it, but without the full query...
How to write WHERE clause with one of the conditions being the result of a calculated field?
[ "", "sql", "sql-server", "sql-server-2012", "where-clause", "" ]
I am using Oracle databases. I have an sql table `PS_Z_STAGE_TEST_JE` that has three fields (`EMPLID`, `LAST_NAME`, `FIRST_NAME`). I am trying to do a `select` statement that will pull many EMPLIDs from sql table:`ps_vc_plan_mem` and insert them into the `EMPLID` column while leaving the other two fields (`LAST_NAME` ...
The error message is exactly what it says it is. Your last\_name column must be defined as not null. Therefore, you can't insert a null into it. Since you didn't define what to insert into the column in your insert, it tries to insert null by default and fails. You must insert something into last name. I would suggest...
The only obvious problem that I see with your query is the asterisk at the end: ``` INSERT INTO sysadm.PS_Z_STAGE_TEST_JE(EMPLID) SELECT DISTINCT emplid FROM ps_vc_plan_mem WHERE vc_plan_id IN ('PNC-RS', 'PNC-SO', 'PNC-ESPP'); ``` Note that `distinct` is not a function. It is a modifier on `select`, so...
Inserting into One Field Select statement Results
[ "", "sql", "oracle", "" ]
I'm using `CASE` to categorize data in the table and count them but the results aren't accurate live demo [[here]](http://sqlfiddle.com/#!2/f1f44/8) ``` select DATE(date) as day, count(*), count(distinct case when name = 'fruit' then 1 else 0 end) as fruits, count(distinct case when name = 'vege' then 1 else 0 end) a...
Your problem is that `COUNT` counts every result that is not `NULL`. In your case you are using: ``` COUNT(distinct case when name = 'sweets' then 1 else 0 end) ``` So, when the name is not `sweets`, it counts the `0`. Furthermore, since you are using `DISTINCT`, it counts just one or two values. You should either us...
You can't group by an alias. You have to group by the expression. ``` group by date(date) ```
SQL using CASE in count and group by
[ "", "mysql", "sql", "aggregate-functions", "" ]
I am a newbie to SQL. The problem which I am facing is, I want to select a particular name **John** from the customer table, but I am storing John in a string called `var_name`. Now is there any way that I can use this variable name in the select statement instead of writing John? sorry i forgot to explain the questio...
In case you are using SQL server, You can actually declare your var\_name: `DECLARE @var_name nvarchar(50) SET @var_name = (SELECT "something" FROM Customer WHERE Customer_ID = '1234')` `from here, you can do whatever you want with @var_name`
Wrap a single-value select in brackets to use its value in another query: ``` select something from sometable where somecolumn = (SELECT name FROM Customer Where Customer_ID = '1234') ```
How can I use a variable inside a SELECT statement?
[ "", "sql", "sql-server", "select", "" ]
I'm looking for some advice on the approach I should take with a query. I have a table (EMP) which stores employee details and working hours for this year (40 hours per week). A further 2 tables store the primary and secondary offices employees belong to. Since employees can move between offices, these are stored with ...
If I understand correctly, the end result you want to see is the number of total hours worked per employee and office? I've come up with this: ``` -- generate date table declare @MinDate datetime, @MaxDate datetime SET @MinDate = (SELECT MIN(d) FROM (SELECT d = OFFICEPRIMARY_START FROM dbo.OFFICEPRIMARY UNION SELECT ...
This should give you a head start: ``` select datediff(wk,OFFICEPRIMARY_START,OFFICEPRIMARY_END) * 40 as HoursWorkedPrimary ,datediff(wk,OFFICESECONDARY_START,OFFICESECONDARY_END) * 40 as HoursWorkedSecondary ,EMP_NAME ,OFFICEPRIMARY_NAME,OFFICEPRIMARY_START,OFFICEPRIMARY_END ,OFFICESECONDARY_NAME,OFFICESECONDARY_STAR...
SQL Server - Query to split time by count (overlapping offices)
[ "", "sql", "sql-server", "database", "t-sql", "" ]
I have a sql table with one varchar column. Some of the data it contains is like: ``` sadkjlsakjd Physics Test 2 Test Test 1 P Test C Physics Test None dstestsad ``` Now, I need a query that gives the most relevant record first when I search with 'Test' keyword. I am expecting: ``` Test Test 1 <Then other records wh...
Try this: ``` SELECT colName FROM tableName WHERE colName LIKE '%Test%' ORDER BY CASE WHEN colName LIKE 'Test%' THEN 1 ELSE 2 END, colName ```
May be something like this ``` SELECT * FROM Your_Table WHERE Your_Column LIKE '%Test%' ORDER BY CASE WHEN Your_Column LIKE 'Test%' THEN 0 ELSE 1 END,Your_Column ```
SQL Query to find relevant result
[ "", "sql", "sql-server-2008", "t-sql", "select", "sql-order-by", "" ]
I have a table where the table column as following date column data ``` Date ---------- 1900-01-01 1900-01-01 1900-01-01 2013-07-25 2012-07-25 2012-07-25 2013-07-25 2012-07-25 2013-07-25 ``` Can I write a Query to filter date column which is equal to 1900-01-01 or greater than 2013-1-1
> Can I write a Query to filter date column which is **equal to 1900-01-01 or greater than 2013-1-1** ? Yes, you can, it's pretty much *exactly* as you phrased the question. Something like this should do the trick: ``` select something from my_table where date = '1900-01-01' or date > '2013-01-01' ``` If your co...
Try this, ``` select data from Table where date=' 1900-01-01' union all select data from Table where date >'2013-1-1' ```
Greater than a date and Equal to a another date
[ "", "sql", "sql-server-2008", "t-sql", "" ]
How do I implement boolean logic in the select statement while the query is running? ``` SELECT t.[Key] ,t.[Parent_Key] ,t.[Parent_Code] ,t.[Code] ,t.[Desc] ,t.[Point] ,[isChild] -- If Point > 2, then true, if Point == 1 Then false ,t.[By] ,t.[On] FROM [db].[stats] ...
``` SELECT t.[Key] ,t.[Parent_Key] ,t.[Parent_Code] ,t.[Code] ,t.[Desc] ,t.[Point] ,CASE WHEN t.[Point] > 2 THEN 1 ELSE CASE WHEN t.[Point] = 1 THEN 0 ELSE NULL END END AS [isChild] ,t.[By] ,t.[On] FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpPara...
Case is your friend... ``` SELECT Key, Parent_Key, Parent_Code, Code, Desc, point, case when point > 2 then 1 when point = 1 then 0 end isChild, [By], [On] FROM db.stats WHERE Parent_Key= @tmpParameter ```
Boolean Logic in Select Statement
[ "", "sql-server-2008", "sql", "" ]
I have a several small entities in my database that I represent as small table with two columns: id and name. Example of such entities: countries, continent. Should I create an enum type instead, whenever the name of those entities doesn't matter?
Hate to answer a question with a question, but it depends. How often do you expect the values to change, and how often do you release code? Enum types will require a code change. A pure database table will be much easier to change. Enum types are more convenient for coding. For infrequent releases, or if you often ha...
Enum is good when: * You want to limit the choice of possible values, e.g. days of the week, gender, status of a ticket (opened/closed/archived) * You want to reduce storage space (tuples are stored in just 1 byte each) * Reduce the number of disc accesses for joins Enum is bad when: * You are not sure what to put a...
When to use an enum or a small table in a relational database?
[ "", "sql", "database", "enums", "" ]
i have a table of content like this **tblEmployees** ``` employeeID employeeName ___________________________________ 1 Jeffrey L. JR Van Hoosear 2 DAVID GUNGNER MR 3 CATHLEEN E STADECKER MRS. 4 MARTIN W SCHIFFMILLER 5 JAY F MOLDOVANYI VI ``` and Another table l...
**Oracle Query:** ``` select employeeName, REPLACE(employeeName, PREFIX,'') from employee_table, prefix_table WHERE INSTR(employeeName, PREFIX) > 0 ``` In **SQL-Server**, I think it should be: ``` select employeeName, REPLACE(employeeName, PREFIX,'') from employee_table, prefix_table WHERE CHARINDEX(PREFIX,emplo...
The following query selects employeeNames that start or end with a prefix. Then, the prefix is stripped off the employeeName using the `SUBSTRING` function. **EDIT**: Corrected the CASE statement. ``` SELECT te.employeeName, CASE WHEN te.employeeName like '%'+' '+tp.Prefix THEN SUBSTRING(te.employeeName,...
SQL Replace query to remove prefix from name contains (MR., MRS., MR / MRS.....)
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a SQL question from one of the well known IT company couple month ago when they were interviewing me, and I never got it figured out. An order can have multiple lines - For ex., if a customer ordered cookies, chocolates, and bread, this would count as 3 lines in one order. The question is to find the number o...
Try this: ``` Select Count(*) as Orders, Lines from ( Select order_id, Count(*) as Lines from data group by order_id )query group by Lines ``` For exmaple, look at this [sqlfiddle](http://sqlfiddle.com/#!3/9904e/4)
Try This: ``` with a AS ( SELECT COUNT(order_id) AS Orders FROM Table_1 GROUP BY Order_Id ) SELECT Orders, COUNT(*) AS line FROM a GROUP BY Orders ```
SQL Find the number of orders in each line count
[ "", "sql", "" ]
``` SELECT right(name,7), substring(params, charindex('|-|', params)+3,LEN(params)) as 'List Name', convert(varchar,dateadd(hh,-8,created_date), 101) as Date, convert(char, dateadd(hh,-8,created_date), 108) as Time FROM [meldb].[dbo].[mr_message] WHERE name in ('CL_LIST_STARTED', 'CL_LIST_STOPPE...
Did you try it yet? Ok... happy friday :) ``` declare @str varchar(100); set @str = 'jim.smith|-|firstItem|-|secondItem'; --- for your query, change @str to the column name, obviously --- select substring( @str , charindex('|-|', @str) + 3 , ( ( cha...
Do you want to split `params` into three columns? Please check below query. ``` SELECT SUBSTRING(params, 1, CHARINDEX('-', params)-1) AS FullName, SUBSTRING(STUFF(params, CHARINDEX('|-|', params), LEN(params), ''), CHARINDEX('-', params) + 2, LEN(params)) AS 'List Name', SUBSTRING(params, CHARINDEX('|-|', ...
Remove part of a text string
[ "", "sql", "sql-server", "" ]
I am trying to get a record with highest `amount` in given hour. Data in DB: ``` id | date | amount ––––––––––––––––––––––––––––––––– 1 | 2014-07-11 18:10:00 | 10 2 | 2014-07-11 18:20:00 | 20 3 | 2014-07-11 18:30:00 | 100 4 | 2014-07-11 18:40:00 | 10 5 | 2014-07-11 19:10:00 | 50 6 | 2014-07-11 1...
If I'm understanding your question correctly, you can join the table back to itself using the max aggregate, grouping by the hour and date: ``` select d.* from data d join (select max(amount) maxamount, hour(date) datehour, date(date) date from data group by hour(date), date(date) ) d2 on d.a...
something like this? -- assuming table name is transactions ``` SELECT * FROM ( SELECT id, date, amount FROM transactions ORDER BY amount DESC ) AS t GROUP BY HOUR(date) , DATE(date); ``` [WORKING FIDDLE](http://sqlfiddle.com/#!2/81d52/1)
SQL get record with highest amount in given hour
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
Please i am trying to query data with a maximum value from two tables, ``` table1 |user_id | name | | 001 | Paul | | 002 | Sean | table2 |id | class | Year | user_id | |201 | 1A | 2010 | 001 | |202 | 2A | 2011 | 001 | |203 | 1B | 2010 | 002 | ``` The `user_id` in `table2` references the ...
Maybe you could order the full result set first by year, and then group by user id: ``` SELECT * FROM ( SELECT a.user_id, a.name, b.class, year FROM table1 a INNER JOIN table2 b ON a.user_id=b.user_id ORDER BY year desc ) h GROUP BY user_id ``` [SqlFiddl...
Because you are using `group by` already, you can use the `substring_index()`/`group_concat()` hack: ``` SELECT a.user_id, a.name, substring_index(group_concat(b.class order by year desc), ',', 1) as maxclass max(Year) as year FROM table1 a INNER JOIN table2 b ON a.user_id=b.user_id GROUP BY a....
select max value of a row from two tables
[ "", "mysql", "sql", "" ]
This is a MySQL 5.5 DB. You're supposed to be able to insert multiple rows of values with this syntax: ``` INSERT INTO tbl_name (a,b,c) VALUES(1,2,3), (4,5,6), (7,8,9); ``` But I'm getting an error ("Column count doesn't match value count at row 1") on the following query: ``` INSERT INTO users_X_shareItems (userID,...
From the different comments I suspect you're making the assumption that the `INSERT` statement works like a function that accepts variable arguments (such as `COALESCE()` or `CONCAT_WS()`). That's simply not the case: is isn't a function and you need the same item count on each list: ``` INSERT INTO foo (a) VALUES (?)...
Why do you close the VALUES brackets after each single value? SQL know asumes you like to add 5 different rows with every row containing only one value but you said you will provide five values. So your Query should be ``` INSERT INTO users_X_shareItems (userID, itemID, userAction, detail, actionDate) VALUES ('CB381FC...
How is this a mismatch between column count and values?
[ "", "mysql", "sql", "" ]
This is my table structure: ``` File | Version | Function 1 | 1 | 1 1 | 2 | 1 1 | 3 | 1 1 | 2 | 2 2 | 1 | 4 3 | 2 | 5 ``` I need it to return these rows only ``` 1 | 3 ...
An efficient way to do this is often to use `not exists`: ``` select t.* from table t where not exists (select 1 from table t2 where t2.file = t.file and t2.Version > t.version ); ``` This query can take advantage of an index on `table(file, version)`. This rephra...
In SQLite 3.7.11 or later, when you use MAX, the other values are guaranteed to come from the row with the largest value: ``` SELECT File, MAX(Version) AS Version, Function FROM MyTable GROUP BY File ```
SQL: Filter rows with max value
[ "", "sql", "sqlite", "greatest-n-per-group", "" ]
How would you do this? I'm doing an ETL process on databases that do not currently have a Date\_added/Date\_updated column. The DBA does not want to add a Date column to the tables so I have to find some alternative way of select only new/changed records for nightly extractions. The databases are huge so the solution ...
If you have configured your database for the Oracle Flashback Transaction Query feature, then you can query the database as of a past date, as below: ``` SELECT * FROM mytable AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '1' DAY); ``` Thus, from day to day, you can see the changes by using MINUS, as ``` SELECT * FROM m...
**If** your PK is numeric **AND** generated from sequence in increasing order then you can record the start and end time and ID in a control table. The control table would have a range of batch primary keys. The control table can have dates, tablename (if you want to apply that design per multiple jobs), status, etc.
Is there any method to select only new/changed rows without Date column or row dependency in Oracle?
[ "", "sql", "database", "oracle", "data-warehouse", "" ]
I am sharing my SQL if someone has better than this please post here. To get First Highest Salary Run below query: ``` select salary from employee order by salary desc limit 1; ``` To get Second Highest Salary Run below query: ``` select salary from employee order by salary desc limit 1,1; ``` To get Third Highest...
Your code is fine... apart from if multiples of salaries exist... i.e. if the top 10 salaries are 1000 then the top salary = 1000, the top 3rd one = 1000 etc etc Use group by... ``` select salary from employee GROUP BY salary order by salary desc limit 1; ``` or a distinct... ``` select DISTINCT(salary) from employ...
You can get Top Nth salary using this query where `N` is Nth highest salary. ``` SELECT * FROM Employee Emp1 WHERE (N) = ( SELECT COUNT(DISTINCT(Emp2.Salary)) FROM Employee Emp2 WHERE Emp2.Salary >= Emp1.Salary ) ```
How to get First Highest or Second Highest or Third Highest Salary from Employee table
[ "", "mysql", "sql", "" ]
ORACLE 10 g db: convert date format from ``` 02-JUL-14 to 02/JUL/14 ``` I tried using the the select query below to get "02/JUL/14" instead it shows "02-JUL-14": ``` SELECT ROUTINGNUM , to_date (EFFDATE,'DD/MM/YYYY') FROM hat; ``` Can anybody please help reading this.
if EFFDATE is a date column, ``` SELECT ROUTINGNUM , to_char( EFFDATE,'DD/MON/YYYY') FROM hat; ``` if it is a String in the format DD-MON-YY ``` SELECT ROUTINGNUM , to_char( to_date( EFFDATE,'DD-MON-YY') ,'DD/MON/YYYY') FROM hat; ```
TO\_DATE function is used for converting from String to Date type. Use TO\_CHAR function instead.
Date conversion in Oracle not working as expected
[ "", "sql", "oracle", "date", "" ]
I have table where there is a record for each week activities of my resources as follows; ``` Asset Name | Project | Week Beginning | Monday | Tuesday| Wednesday| Thursday| Friday| Saturday | Sunday James Project 1 26-06-2014 0 1 1 0 1 0 0 James Project 1 03-07-2014 1 1 0 1 0 0 0 Dav...
Try This ``` SELECT ASSETNAME,PROJECT,MIN(T.MIN)START_DAY,MAX(T.MAX) END_DAY, DATEDIFF(DD,MIN(t.min) ,MAX(T.MAX)) DURATION FROM ( SELECT ASSETNAME,PROJECT,DATEADD(DD,MIN(WEEK),WEEKBEGINNING) 'MIN',DATEADD(DD,MAX(WEEK),WEEKBEGINNING) 'MAX' FROM #TEMP T CROSS APPLY(SELECT 0 'WEEK' WHERE T.MONDAY=1 UNION ALL SEL...
Firstly, normalize your data, using `unpivot`, and convert the days to an actual date. ``` select AssetName, Project, dateadd(d, CASE dayname WHEN 'Monday' THEN 0 WHEN 'Tuesday' THEN 1 WHEN 'Wednesday' THEN 2 WHEN 'Thu...
Generate interesting view of data
[ "", "sql", "sql-server", "" ]
I have a Table like this in MySQL ``` 1. ID, (int, autoincrement, primary) 2. Date (timestamp) 3. Device (int) 4. Text (text) ``` For a Report, i want to find out, how many records for each type of device there is. Like "Device '5' = 100 rows". Can this be done by a pure sql comand, or do i have to loop through ...
This is a classic usecase of the `group by` clause: ``` SELECT device, COUNT(*) AS num_per_device FROM my_table GROUP BY device ``` Edit: To answer the followup question by @sgtBear in the comment, you can add the device text by joining this query to another one: ``` SELECT a.device, b.device_text, a.num_per...
You can just try below query: ``` Select Count(Device) FROM Table1 Order By Device Group By Device ```
Select sum of each
[ "", "mysql", "sql", "select", "" ]
I using Open Office to create an .odb database that is connected to an Access database, but I am having a hard time querying dates in the .odb database. Here is an entry from the DATE column: ***02/11/13 12:00 AM*** (The column is actually called 'DATE') How would I query this? This is what I have tried: **ERROR:...
Try it like this: ``` SELECT * FROM PHAII01 WHERE DATE = #02/11/13 12:00 AM# ``` or like this ``` SELECT * FROM PHAII01 WHERE DATE = CDate('02/11/13 12:00 AM') ```
I have to format() the values in the DATE column to better fit the query. **This had achieved the desired results** ``` SELECT * FROM PHAII01 WHERE format(DATE,'YYYY-MM-DD') = '2013-02-11' ```
Are my dates strings?
[ "", "sql", "date", "ms-access", "openoffice-base", "" ]
I am trying to just return all rows for an event that has closed within 7 days of the current date. My end\_date has a format such as 2014-06-25 (Y-m-d), what is the best way to select events between NOW and 7 days ago in the past. I have the following.. but this isn't correct SELECT \* FROM end\_date WHERE end\_dat...
Try using `DATE_ADD` ``` SELECT * FROM end_date WHERE end_date <= NOW() AND end_date >= DATE_ADD(now(),INTERVAL -7 day) ```
You can do something like below: ``` SELECT .... FROM .... WHERE DATEDIFF(NOW(), end_at) <= 7; ```
Show events from the last 7 days via MySQL
[ "", "mysql", "sql", "database", "" ]
I have a MySQL table "results" which has the following fields: ``` id (PK, AI), user_id (FK), date, score, time ``` I want to be able to query this table so that it sorts and returns the fields in order of score (descending order) followed by time (ascending order). So something like: ``` SELECT * FROM results ORDER...
You can do this with `not exists`: ``` SELECT * FROM results r WHERE NOT EXISTS (select 1 from results r2 where r2.user_id = r.user_id and r2.id > r.id) ORDER BY score DESC; ``` This will work best with an index on `results(user_id, id)`.
My suggestion: `SELECT user_id, max(score), time FROM results GROUP BY user_id ORDER BY score DESC;` Select id and highest score per `user_id` via `max()` and `Group By`. Then order the records by score descending. EDIT: If you need the time for the user-score and there is only one entry with the same score you can u...
MySQL - if row is duplicate, return only the first one
[ "", "mysql", "sql", "rows", "" ]
I have a table with information like this ``` VehicleID | dtDate | Lat | long ``` A new record is created every so often with new lat and long for the same vehicleID, I am trying to get the latest Date per vehicle so my lat and long would be the latest. ``` select row_number over (partition by vehicleID order by dtD...
``` ;WITH vehicleCTE AS (SELECT ROW_NUMBER() OVER (PARTITION BY vehicleID ORDER BY dtDate DESC) AS rowNum, vehicleID, Lat, Long, dtDate FROM t1) SELECT vehicleID, Lat, Long, dtDate FROM vehicleCTE WHERE rowNum = 1; ```
I'd use a CTE here if this is just an adhoc query: ``` WITH CTE1 AS ( SELECT vehicleID ,Lat ,Long ,row_number OVER ( PARTITION BY vehicleID ORDER BY dtDate DESC ) AS latestdate FROM MyTable ) SELECT vehicleID ,Lat ,Long FROM CTE1 WHERE latestdate = 1 ...
latest distinct record from partition by
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have many tables that have the same column 'customer\_number'. I can get a list of all these table by query: ``` SELECT table_name FROM ALL_TAB_COLUMNS WHERE COLUMN_NAME = 'customer_number'; ``` The question is how do I get all the records that have a specific customer number from all these tables without running ...
I assume you want to automate this. Two approaches. 1. SQL to generate SQL scripts . ``` spool run_rep.sql set head off pages 0 lines 200 trimspool on feedback off SELECT 'prompt ' || table_name || chr(10) || 'select ''' || table_name || ''' tname, CUSTOMER_NUMBER from ' || table_name || ';' cmd ...
To get record from a table, you have write a query against that table. So, you can't get ALL the records from tables with specified field without a query against each one of these tables. If there is a subset of columns that you are interested in and this subset is shared among all tables, you may use UNION/UNION ALL ...
How to select a column from all tables in which it resides?
[ "", "sql", "oracle", "" ]
Ok ok I know you probably all going to kill me for asking this, however I got into an friendly programmer argument with a co-worker about one of our database tables and he asked a question which I know the answer to but I couldn't explain it is the better way. I will simplify the situation for the simplicity of the qu...
The goal of normalization is not performance. The goal is to model your data correctly with minimum redundancy so you avoid data anomalies. Say for example two users share the same phone. If you store the phones in the user table, you'd have sim number, IP address, and cell number stored one each user's row. Then you...
It sounds like you already understand the benefits of normalisation, so I won't cover these. There are a couple of considerations here: 1. Does a user always have one and only phone number? If so, then it is still normalised to add these to the user table. However, if the user can have either no phone number or multip...
Performance gains vs Normalizing your tables?
[ "", "sql", "sql-server", "database", "database-design", "normalization", "" ]
I am not sure if its possible or not, Just want to know if it is. I have column `plan_popular` which has default value `0`. Lets same i have a list : ``` Plan Name | plan_popular | amount =================================== plan A 0 25.00 plan B 1 50.00 plan C 0 ...
You can use an expression to determine the value to assign: ``` UPDATE {CI}plans SET plan_popular = IF(plan_id = ?, 1, 0); ```
try this, ``` UPDATE {CI}plans SET `plan_popular` = CASE `Plan Name` WHEN 'plan C' THEN 1 ELSE 0 END WHERE `Plan Name` IN((select `Plan Name` from {CI}plans where plan_popular=1 ) , 'plan C'); ```
Update Same mysql field twice in single query
[ "", "mysql", "sql", "" ]
I have a table in sql server database in which records of transactions are stored. Table consists of user id of buyer and user id of seller of product. I have to find the circles in the table for example- I have to get the records of type- A sells to B, B sells to C, C sells to D AND D sells to A. Please help.
Use following function: ``` CREATE FUNCTION dbo.CheckIsCircular(@SellerId INT) RETURNS BIT AS BEGIN DECLARE @IsCircular BIT = 0 DECLARE @Sellers TABLE(Id INT) DECLARE @TempSellers TABLE(Id INT) DECLARE @Buyers TABLE(Id INT) INSERT INTO @TempSellers(Id)VALUES(@SellerId) WHILE EXISTS(SELECT * ...
Your problem is a graph traversal challenge; this is not natively supported in TSQL, but you can [simulate it](http://hansolav.net/sql/graphs.html).
find circular transactions in database table
[ "", "sql", "sql-server", "database", "" ]
The below query is working perfect but it return two rows of hours which I don't want ``` SELECT USERINFO.name, USERINFO.BADGENUMBER, departments.deptname, APPROVEDHRS.hours, sum(workingdays) as workingdays,TotalWorkingDays FROM (SELECT DISTINCT (DATEDIFF(DAY, '2014-06-01', '2014-06-30') + 1...
First thing, you might want to use table names in your query so you can see where data is coming from, e.g. ``` select name,BADGENUMBER,deptname,hours, ``` ...would be easier to read as: ``` select ??.name,??.BADGENUMBER,??.deptname,APPROVEDHRS.hours, ``` ...or you could use aliases in the "FROM" part of your query...
If you are left-joining the ApprovedHrs table, then you'd need to limit (with a Where clause or a join clause) the dates from which those approved hours from July came from. To clarify this, I would fully qualify the hours field with ApprovedHrs.Hours, so that it's more clear where this comes from (I'm only assuming "...
total hours column return two output instead of one
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Am very new in *Database development* so I have some doubts regarding my following example: Function f1() - ***language sql*** ``` create or replace function f1(istr varchar) returns text as $$ select 'hello! '::varchar || istr; $$ language sql; ``` Function f2() - ***language plpgsql*** ``` create or repla...
## [**SQL functions**](https://www.postgresql.org/docs/current/xfunc-sql.html) ... are the better choice: * For **simple scalar queries**. Not much to plan, better save any overhead. * For **single (or very few) calls per session**. Nothing to gain from plan caching via prepared statements that PL/pgSQL has to offer....
[PL/PgSQL is a PostgreSQL-specific procedural language based on SQL](http://www.postgresql.org/docs/current/static/plpgsql.html). It has loops, variables, error/exception handling, etc. Not all SQL is valid PL/PgSQL - as you discovered, for example, you can't use `SELECT` without `INTO` or `RETURN QUERY`. PL/PgSQL may ...
LANGUAGE SQL vs LANGUAGE plpgsql in PostgreSQL functions
[ "", "sql", "database", "postgresql", "plpgsql", "" ]
I have the following SQL which selects all ManifestoBatches and gives me a count of each batches items (ManifestoItems): ``` SELECT m.Id, u.UserName, m.TotalRows, m.DateCreated, count(i.Id) as Items FROM ManifestoBatches as m left join ManifestoItems as i on m.Id = i.BatchId inner join AmzUsers as u on m.CreatedBy ...
Instead of ``` count(i.Id) ``` use ``` SUM(CASE WHEN i.ScannerId IS NOT NULL THEN 1 ELSE 0 END)` ```
I think your problem is the `left join`. This produces `NULL` when the values do not match. But it sounds like you have `NULL` values in the field anyway. This may solve your problem: ``` SELECT m.Id, u.UserName, m.TotalRows, m.DateCreated, count(i.Id) as Items FROM ManifestoBatches m join ManifestoItems i o...
SQL filter query on joined column
[ "", "mysql", "sql", "join", "" ]
I need to insert 10 billion rows and update their values few times. Table structure: ``` Column1 Column2 Count 1 1 99 1 2 10003 1 3 1 1 4 23 1 5 9994 ... 99999 1 2 99999 2 2233 99999 3 5904 99999 4 12 99999 5 4598435 ....
There is nothing in any mainstream RDBMS that would make this hard or even impossible. All your requirements are **trivial** for any RDBMS. What you need is a single table with a single index on it. This does not stress any system architecturally. Be aware that RAM is likely to be not enough to cache all data. This m...
I would use a database you know well as long as it can handle your required throughput. So I assume since you are asking your preferred database hasn't met your requirements. If you require high throughput with consistent sub-millisecond lookup latency take a look at [Aerospike](http://www.arerospike.com) which is use...
Insert/Update/Index many rows (10 billion) numbers as values
[ "", "sql", "database", "data-structures", "bigdata", "nosql", "" ]
I am creating a table with `date` column. I would like to add a check constraint to validate if the date is in future. ``` create table test_table ( schedule_date date not null, check (schedule_date >= TODAY) ); ``` Above sql gives me a syntax error. ``` 09:43:37 [CREATE - 0 row(s), 0.000 secs] [Error Code: -2...
You cannot use today in the check constraint. As the official documentation states: > Check constraints are defined using search conditions. The search condition cannot contain user-defined routines, subqueries, aggregates, host variables, or rowids. In addition, the condition cannot contain the variant built-in funct...
As Copilot says, it's simply not permitted by Informix. If any other RDBMS does allow it, I'd be surprised. The inherent ticking time bomb should be obvious when you think about it. The row when inserted meets the constraint, but will fail the constraint as time passes. How is the engine to flag that? The solution is...
Check constraint on date
[ "", "sql", "informix", "check-constraints", "" ]
Let's say I have a table like below: ``` Name Score ----- ----- Don 3 Don 4 Don 0 Pat 3 Cat 5 ``` How to write a query that will filter out Name where the score is 0? I.e.: In the above table, the query must not return the Name "Don" since one of the rows for Don contains 0. (I'm using Oracle db BT...
``` select name from your_table group by name having sum(case when score = 0 then 1 else 0 end) = 0 ```
The first solution that usually jumps to ones mind is something with `EXISTS`: ``` SELECT * FROM players p1 WHERE NOT EXISTS ( SELECT 1 FROM players p2 WHERE p1.Name = p2.Name AND p2.Score = 0 ) ``` Here's a [SQLFiddle showing it in action](http://sqlfiddle.com/#!4/228c2/1), returning ``` | NAME | SC...
Selecting rows where there is repetition in columns
[ "", "sql", "oracle", "" ]
Given this table: ``` CREATE TABLE colors ( image_id int, color char(6) ); INSERT INTO colors (image_id, color) VALUES (1, '22ffcc'), (2, '22ffcc'), (2, '2200cc'), (3, '22ffcc'); ``` [SQL Fiddle](http://sqlfiddle.com/#!2/f9243/2) I want to fetch only those image\_id where image id is any among (...
The typical solution for your problem is to count the distinct values of colors for every image\_id: ``` select image_id from colors where color in ( '22ffcc' , '2200cc' ) and image_id in (2,3) GROUP BY image_id HAVING COUNT(DISTINCT color) = 2; ``` Explanation: To have both colors, the number of counts must be the s...
If you're looking for specific colors that appear on different rows, then you can join the table on itself: ``` select color1.image_id from colors color1 join colors color2 on color1.image_id = color2.image_id where color1.color = '22ffcc' and color2.color = '2200cc' and color1.image_id in (2,3); ```
Using "and" with "in"
[ "", "mysql", "sql", "" ]
I have two mysql database table. They have one-to-one relationship between each others. They are empty. I can't insert value to anyone. Each one has a foreign key of another one. I'm planning to insert value to them in the same time. But, I didn't find which sql query is necessary. What is your offer? Thanks one-to-on...
For 1 to 1 table relationship, that doesn't mean you have to put their PK on each other, instead people usually decide which FK goes to another table and that's all. From what you did, that shows Many to Many table relationship, and the right schema would be creating a new table that has FK to those 2 tables. Details:...
You don't need address\_Id in the student table. What if the student is homeless? What if a student has more than one addresss? He/she might have a mailing address a local address in the college town, and a home address. And even for students with only one address, you can get that address by querying the address table...
insert values into two tables at the same time - one to one relationsship
[ "", "mysql", "sql", "insert", "one-to-one", "" ]
I want to unite the following two queries into one: ``` SELECT pg_get_serial_sequence('purchase_orders', 'id'); SELECT setval('purchase_orders_id_seq', 30000); ``` But if I place the upper SELECT into the setval's first parameter I get: ``` SELECT setval(SELECT pg_get_serial_sequence('purchase_orders', 'id'), 30000)...
If you want to pass a subquery result as a function argument, you need parentheses around it: ``` SELECT setval((SELECT pg_get_serial_sequence('purchase_orders', 'id')), 30000); ``` But in this case, the SELECT is redundant; you can invoke the function directly: ``` SELECT setval(pg_get_serial_sequence('purchase_ord...
## General function and automation All "migration" or "starting database" SQL-script files have some controlled `INSERT` sequence before to use `serial` automation, so it need a simple command to say "ok, back to standard operation". This generic operation is `SELECT MAX(id)+1 FROM schemaName.tableName`... and, as @N...
PostgreSQL increase a table's sequence with one query
[ "", "sql", "postgresql", "sequence", "auto-increment", "" ]
I have thousands of rows in a table. Some rows have similar keywords but can be categorized in the same group. For example: ``` Table : Birds_Name +-------+---------------------+ |ID |Name | +-------+---------------------+ |1 |Blue Peckwood | +-------+---------------...
Try this ``` SELECT SUBSTRING_INDEX(name,' ',-1),count(*) FROM birds_name GROUP BY SUBSTRING_INDEX(name,' ',-1) HAVING count(*)>0; ``` [`Manual`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index) for SUBSTRING\_INDEX function in mysql.
Can you try this. ``` SELECT count(id),name FROM birds_name group by name having count(id) >1 ``` Thanks [SQL Fiddle](http://sqlfiddle.com/#!2/92759/2)
How to find duplicate rows with similar part of string
[ "", "mysql", "sql", "group-by", "duplicates", "" ]
I want to change the datatype (varchar2 to number) of a column in an oracle table and the column is not empty. So what I thought I will do is, create a new column, copy the data from one column to another column. Disable/Drop the previous column and rename the new column. To copy data between the same columns, I can u...
The operation will be done on the same row for each rows. Be aware that if you do not want to update all the table rows then you need to add a `WHERE` clause.
`UPDATE foo_table SET some_column = another_column` uses `some_column` and `another_column` of the same row. But note that it does so on every row of `foo_table`; make sure it's what you want.
Copy a column to another column within a same table in oracle db. Do I need to specify which data goes where?
[ "", "sql", "database", "oracle", "" ]
This is a recreational pursuit, and is not homework. If you value academic challenges, please read on. A radio quiz show had a segment requesting listeners to call in with words that have their characters in alphabetical order, e.g. "aim", "abbot", "celt", "deft", etc. I got these few examples by a quick Notepad++ (NP...
Split the word into individual characters using a [numbers table](http://dataeducation.com/you-require-a-numbers-table/ "You REQUIRE a Numbers table! "). Use the numbers as one set of indices. Use [ROW\_NUMBER](http://msdn.microsoft.com/en-us/library/ms186734.aspx "ROW_NUMBER (Transact-SQL)") to create another set. Com...
Interesting idea... Here's my take on it. This returns a list of words that are in order, but you could easily return 1 instead. ``` DECLARE @WORDS TABLE (VAL VARCHAR(MAX)) INSERT INTO @WORDS (VAL) VALUES ('AIM'), ('ABBOT'), ('CELT'), ('DAVID') ;WITH CHARS AS ( SELECT VAL AS SOURCEWORD, UPPER(VAL) AS EVALWORD, A...
Selecting Strings With Alphabetized Characters - In SQL Server 2008 R2
[ "", "sql", "regex", "sql-server-2008-r2", "" ]
I am using Netezza to manipulate some data. I am trying to add a column to a table with values that are results of computation of other columns. First of all, I ran this sql to create a table to rearrange the order of other table: ``` CREATE TABLE SEQ_6_3_FNN_CID218_ORDERED AS SELECT A.* FROM SEQ_6_3_FNN_CID218 A ORD...
What you are looking for here is often referred to as a "calculated column". Netezza does not implement this feature, nor does it implement triggers (another method by which you might achieve the same result). Since Netezza is focused on data warehousing, the sorts of calculations you're talking about are usually done ...
SQL Server can't do this "natively", but you could accomplish this with an insert and update trigger that responds to changes to the two columns and updates the third column. Edit -- I stand corrected: SQL Server *can* do this natively. See Amirreza Keshavarz's answer.
How to add a column using sql that in every record the unit is the result of computation of other columns?
[ "", "sql", "insert", "netezza", "" ]
My function is: ``` CREATE OR REPLACE FUNCTION FnUpdateSalegtab09 ( iacyrid Integer,iRepId Integer,iDrId Integer,ivrid Integer,imode smallint,itrno varchar,itrdate timestamp,iacid Integer,ivrno varchar,iSuppId Integer,icustname varchar,inetamt money,idisrate real,idisamt money,iRoundOff real,ijrmid integer,iuserid...
Your function has a couple of **`smallint`** parameters. But in the call, you are using numeric literals that are presumed to be type `integer`. A string literal or [string constant](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS) (`'123'`) is not typed immediately. It remains t...
That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next `f()` function ``` create function f() returns integer as $$ select 1; $$ language sql; ``` is called as ``` select f(1); ``` It will error out with ...
ERROR: function ... does not exist and HINT: No function matches the given name and argument types
[ "", "sql", "database", "postgresql", "plpgsql", "" ]
Im using the following statement (this is a shortened version as an example) to get results from my Microsoft SQL Express 2012 database: ``` SELECT id, name, city FROM tblContact ORDER BY RAND(xxx) ``` and injecting a seed stored in the session for the `xxx` part so that the results are consistently random for a gi...
The value of `rand(seed)` will be the same for the entire query, You my want to use the ID column to generate random value on the row per row basis: ``` SELECT id, name, city, RAND(xxx + id) AS OrderValue FROM tblContact ORDER BY OrderValue ``` However I've been developing some functionality in the past where I ne...
Often, the `newid()` function is used for this purpose: ``` SELECT id, name, city FROM tblContact ORDER BY newid(); ``` I have heard that `rand(checksum(newid()))` actually has better properties as a random number generator: ``` SELECT id, name, city FROM tblContact ORDER BY rand(checksum(newid())); ``` If you want...
T-SQL Randomize order of results using RAND(seed)
[ "", "sql", "t-sql", "random", "sql-server-2012", "" ]
I have 3 tables, with Table B & C referencing Table A via Foreign Key. I want to write a query in PostgreSQL to get all ids from A and also their total occurrences from B & C. ``` a | b | c ----------------------------------- id | txt | id | a_id | id | a_id ---+---- | ---+----- | ---+...
If the query involves large parts of `b` and / or `c` it is more efficient to aggregate first and join later. I expect these two variants to be considerably faster: ``` SELECT a.id, , COALESCE(b.ct, 0) + COALESCE(c.ct, 0) AS bc_ct FROM a LEFT JOIN (SELECT a_id, count(*) AS ct FROM b GROUP BY 1) b USING (a_i...
Another option: ``` SELECT a.id, (SELECT COUNT(*) FROM b WHERE b.a_id = a.id) + (SELECT COUNT(*) FROM c WHERE c.a_id = a.id) FROM a ```
Get count of foreign key from multiple tables
[ "", "sql", "postgresql", "left-join", "aggregate-functions", "correlated-subquery", "" ]
I'm struggling with a thing that in my mind should be achievable but I can't get it to work...here the scenario: I have two tables structured as follows: 1- table where data are logged every 10 minutes: (tab\_cycle) ``` timestamp | value1 | value2 ... | valueN 20140715 10:10 | 10 | 20 ... | x 20140715...
You just need to remove the `group by` in the nested subquery: ``` SELECT tab_cycle.timestamp AS startTime, DATEADD(mm, 10, tab_cycle.timestamp) AS endTime, (SELECT COUNT(tab_event.descr) FROM tab_event WHERE tab_event.timestamp BETWEEN tab_cycle.timestamp and ...
I may have the datediff backwards ``` select table1.timestamp, table1.value1, table1.value2, table1.valueN , count(tabl2.timestamp) from table1 left join table2 on datediff(mi, table1.timestamp, table2.timestamp) < 10 and table2.timestamp > table1.timestamp group by table1.timestamp, table1.value1, tab...
Nested query in a select statement for counting entries based on fields derived from the outer query
[ "", "sql", "sql-server", "t-sql", "" ]
I have 3 tables A, B and C: * Table A is small (~1000 rows). * Table B has ~200,000 rows. * Table C has ~2.2 million rows. I'm running a query like this: ``` SELECT A.Id FROM A, B, C WHERE A.Id = B.SomeId OR (A.Id = C.SomeId AND C.SomeValue = 'X') INTO OUTFILE '/tmp/result.txt'; ``` * `A.Id` is the primary key of...
`OR` expressions often make it difficult for MySQL to use indexes. Try changing to a `UNION`: ``` SELECT A.id FROM A JOIN B ON A.id = B.SomeID UNION SELECT A.id FROM A JOIN C ON A.id = C.SomeID WHERE C.SomeValue = 'A' ``` From the [documentation](http://dev.mysql.com/doc/refman/5.5/en/how-to-avoid-table-scan.html): ...
Let's go even smaller. Let's say that your tables look like this: > ``` > A.ID > 1 > 2 > > B.SomeID > 1 > 3 > > C.SomeID | C.SomeValue > 1 | X > 2 | X > ``` Now, let's see what your query will do. First, we look to see if A.ID match and B.SomeID match. In the case of A.ID = 1, we have a match! Sql s...
Unusual MySQL behavior with select query
[ "", "mysql", "sql", "" ]
I need a field (column) of my database to update automatically. For example, the field NUMBER for each record incrementing every minute. How can I do it? I am using SQL Server.
You're probably looking for something called SQL Server Agent jobs here is a good starting point reference: <http://technet.microsoft.com/en-us/library/ms181153(v=sql.105).aspx> This allows you to run some sql code on a schedule of your choosing. P.S. If you have access to sql server management studio, the GUI is ...
You can set up a SQL Agent job to run an update statement once a minute: ``` UPDATE tablename SET NUMBER = NUMBER + 1 ```
How to automatically update database SQL Server?
[ "", "sql", "sql-server", "auto-increment", "" ]
I've spent a good amount of time trying to figure out how to implement a **CASCADE ON DELETE** for recursive primary keys on SQL Server for some time now. I've read about triggers, creating temporary tables, etc but have yet to find an answer that will work with my database design. Here is a Boss/Employee database exa...
The below might work for you (I haven't tested it so it may require some tweaking). Seems like all you have to do is delete the employees from the bottom of the hierarchy before you delete the ones higher-up. Use a CTE to build the delete hierarchy recursively and order the CTE output descending by the hierarchy level ...
Necromancing. There's 2 simple solutions. * You can either read Microsoft's sorry-excuse(s) of why they didn't implement this (because it is difficult and time-consuming - and time is money), and explanation of why you don't/shouldn't need it (although you do), and implement the delete-function with a cursor in a ...
SQL Server - Cascading DELETE with Recursive Foreign Keys
[ "", "sql", "sql-server", "recursion", "constraints", "cascade", "" ]
I have a very set of data as follows: ``` CustomerId char(6) Points int PointsDate date ``` with example data such as: ``` 000021 0 01-JAN-2014 000021 10 02-JAN-2014 000021 20 03-JAN-2014 000021 30 06-JAN-2014 000021 40 07-JAN-2014 000021 10 12-JAN-2014 000034 0 04-JAN-2014 000...
I'll copy my comment from above: I know literally nothing about cubes, but it sounds like what you're looking for is just a cursor, is it not? I know everyone hates cursors, but that's the best way I know to compare consecutive rows without loading it down onto a client machine (which is obviously worse). I see you me...
The problem can be solved in regular TSQL with a common table expression that numbers the lines per customer, along with an outer self join that compares each row with the previous one; ``` WITH cte AS ( SELECT customerid, points, ROW_NUMBER() OVER (PARTITION BY customerid ORDER BY pointsdate) rn FROM mytable...
How to find daily differences over a flexible time period?
[ "", "sql", "sql-server", "olap-cube", "" ]
I'm trying to learn Subquerys. I have troubles with this: **The two tables:** ``` CREATE TABLE DEPT (DEPTNO NUMBER(2) CONSTRAINT DEPT_PRIMARY_KEY PRIMARY KEY, LOC varchar2(3)); CREATE TABLE EMP (ENAME varchar2(10), JOB varchar2(9), DEPTNO NUMBER(2) NOT NULL CONSTRAINT EMP_FOREIGN_KEY REFERENCES DEPT (DEPTNO)); ```...
To simplify your query, you can use: ``` select emp1.ename, emp1.job from EMP emp1 where emp1.deptno in (SELECT DEPT.DEPTNO from DEPT where DEPT.loc = 'CHICAGO'); ``` --- To select name and job from emp1 where emp1's job is same as emp2's job with location Chicago: ``` SELECT emp1.ename, emp1.job FROM emp emp1 WH...
The `exists` operator is applied on a subquery, not a column: ``` SELECT emp1.ename, emp1.job FROM emp emp1 WHERE EXISTS (SELECT emp2.job FROM emp emp2 FULL JOIN dept ON (emp2.deptno = dept.deptno) WHERE dept.loc = 'CHICAGO'); ```
SQL Subquery with JOIN
[ "", "sql", "database", "oracle", "" ]
I have a big database around 46GB in Mysql format and I managed to convert all the database to MSsql except two tables, the biggest ones. When I try to migrate those 2 tables, one by one , after a while I get the error message "The connection has been disabled" I encreased the timeout from SSMA option from 15 to 1440 ...
You should be able to use SQL Server Integration Services (SSIS). You can create a dataflow that pulls from MYSql and dumps the Data into MSSQL. You'll need to create a Data flow task that includes an OLE Database Source and connect it to an OLE Database Destination.
I had the same problem using SSMA. I managed to migrate 100+ million rows of a table with 40+ columns. I assume you've done the configuration well. You need to ensure that there is no activity in the MSSQL database. No SELECTS over those tables and no any other activities. Check out the two tables' structures to ensu...
Migrate big tables from MySql to MsSql
[ "", "mysql", "sql", "sql-server", "database-migration", "" ]
I have a sql statement which is trying to retrieve the rows having a count greater than 1 for all the similar rows. In all those rows, one field appears to be holding null value. Case 1 : Let's say the table name is ABC --- BUSINESS\_UNIT, INVOICE, FLAG A 1 (Null) A 1 (Null) --- SQL Statement : SELECT BUSINESS\...
I think I have found what I was intending to look for. SELECT BUSINESS\_UNIT, INVOICE from TABLE ABC group by BUSINESS\_UNIT, INVOICE having COUNT(DISTINCT Flag) >1 Case 1: It returns no rows Case 2 : It returns 1 row --- BUSINESS\_UNIT, INVOICE B 1 --- Thanks Raphael, Dnoeth and Gordon for your help on this!
well, null is also a value, so if you group by a nullable field, null values will be distinct from non null values. If you don't wanna null values, just add a where clause ``` SELECT INVOICE from TABLE ABC where flag is not null group by BUSINESS_UNIT, INVOICE, FLAG having COUNT(*) >1 ```
SQL in Oracle Group by NULL returns multiple rows
[ "", "sql", "oracle11g", "group-by", "crosstab", "" ]
I'm just trying to add in an the newest estimated return date for a car as part of a subquery in my Select statement, I just wanted to know if this was how it is done? I think I heard that Select happens before Order By so wanted to do a quick check. ``` select top 1 ESTIMATE_RETURN_DATE from CHECK.AOS where AOS.AU...
ORDER BY is evaluated **before** the SELECT, as the ordering changes the results returned. `TOP 1` also ensures the lowest `REVISION_NO` is returned, therefore it appears you are using the query correctly.
I was pretty sure, but this explains it <http://use-the-index-luke.com/sql/partial-results/top-n-queries> It selects everything and sorts then stops when it reaches the number to return.
ORDER BY before SELECT?
[ "", "sql", "sql-server", "" ]
The table will look like this ``` STUDENTID | FRIEND1 | FRIEND2 | ADDRESS | TUITIONPAID ``` And student ID, Friend 1 and friend 2 will be a combination of four, five or six numbers and characters TUITION will be a true/false Of course, STUDENTID should be unique for all rows. Am I using the right types? ``` STUDE...
Lets separate the questions. > Am I using the right types? Yes from what I could understand you can use this model you created. > And should STUDENTID be "unique" or "primary key"? A primary key is better, but it can also be unique, since you can have a student that came back to study after a long period away. > A...
You are using the right types except TUITION - BIT (3). Since you want it to be true/false **use BOOLEAN** STUDENTID should definitely be your primary key. It shouldn't be a problem to use 1 table but you could make more. For example: Table 1: STUDENTID 1 - 1,000,000 Table 2: STUDENTID 1,000,001 - 2,000,000 Table ...
Writing a table for MySQL
[ "", "mysql", "sql", "" ]
i working sqllite.i successfully created sql database and i also can insert some values and show it in listview.now i want to write function witch return title where ServerID like my value i wrote function but this function did not return counter ``` public class DatabaseHandler extends SQLiteOpenHelper { private stat...
You can do this way. ``` public String GetCounterFromServerID(String value) { Cursor cursor = db.rawQuery("SELECT " + KEY_Counter + " FROM " + TABLE_CONTACTS + " WHERE serverid like '%" + value + "%'", null); if (!cursor.moveToFirst()) { return null; } if(-1 == cursor.getColumn...
This is wrong ``` return KEY_Counter; ``` because that is your String `"counter"`. You should use: ``` String result = "no data found"; if (cursor != null && cursor.moveToFirst()) result = cursor.getString(cursor.getColumnIndex(KEY_Counter)); cursor.close(); return result; ```
Android sqlite select not working
[ "", "android", "sql", "database", "sqlite", "" ]
I have a database table that looks like below. It contains a key (id) that identified each transaction. Within each transaction, there may be multiple items that were purchased, thus someome with transact 103 has three different id values because they purchased three different items. Here is what I am trying to do. Fo...
One way of doing this would be to `group by store and item` and then calculating the sum. This way you would be able to add more conditions if required based on valid combinations of (Store,Item). You have grouped by `id` which is not worth as each row will have unique id so no group will be formed. For given conditio...
I have no idea why there is a subquery here. Unless I'm missing something, this should work: ``` select sum (item_qty) FROM dbo.vTransactions1 ti WHERE ti.store IN (20, 35) AND ti.item IN (7, 12, 21) ```
Finding the sum of sales when a series of conditions are met
[ "", "sql", "sql-server", "" ]
I have a sales\_cat table, and a user\_cat table. **sales\_cat** * id\_cat * name **user\_cat** * id * id\_user * id\_cat I need to get all the sales\_cat rows, joined with the user\_cat table for a specific user, indicating if that user has or not the category. Example, for id\_user = 4 it should return: ``` id_...
Try Like This ``` SELECT sales_cat.id_cat, sales_cat.name,case when user_cat.id is null then 0 else 1 end as "selected" FROM sales_cat LEFT JOIN user_cat ON user_cat.id_cat = sales_cat.id_cat and user_cat.id_user = 4 ``` <http://sqlfiddle.com/#!2/395ba/25> Thanks @Phil
Try this: ``` select distinct s.id_cat, s.name, case when u.id_user is null then 0 else 1 end selected from sales_cat s left join user_cat u on s.id_cat = u.id_cat and (u.id_user = 4 or u.id_user is null) ``` While the approach is similar to Satson's answer, we move the null check from `user_cat` to `id_user`.
MySQL: Return all rows of table A and true|false if record exists in table B
[ "", "mysql", "sql", "join", "left-join", "" ]
``` CREATE PROCEDURE sp_ViewEffortSummary @UserID INT , @Project_Name nVARCHAR(40), @Date DATETIME AS BEGIN DECLARE @query nVARCHAR(max) DECLARE @T_EmpID nVAR...
There are few issues in your query as: 1. In the very first declaration you have written `@UserID INT` but when executing Sproc you have written it as string as '2312456'. It should be 2312456 as shown below or else change the declaration to `nVARCHAR(10)`. 2. When tables are aliased then use Aliases to refer...
You use alias for `tblPSU` and `tblPC` and must use **`Alias.YourColumnName`** for example use `a.Doc_Work` and `b.Doc_Work` instead of `tblPSU.Doc_Work` and `tblPS.Doc_Work` ``` tblPSU.Doc_Work --> a.Doc_Work tblPc.Doc_Work --> b.Doc_Work tblKT.Rework --> c.Rework tblPC.Rework --> b.Rework ```
Dynamic sql : multi-part identifier could not be found error
[ "", "sql", "sql-server", "" ]
Hi i am trying to delete all the rows in a table by below query ``` db.beginTransaction(); // db is a SQLiteDatabase object int deleted = db.delete("user", null, null); db.endTransaction(); ``` I am getting n number of rows deleted in the table. But still rows exist in the table. Anything wrong in my delete call?
You need to call `setTransactionSuccessful` to commit all the changes done to the database, before calling `endTransaction`: ``` db.beginTransaction(); int deleted = db.delete("user", null, null); db.setTransactionSuccessful(); db.endTransaction(); ``` Source (Android developer reference): > The changes will be roll...
Just try this ``` public int delete(String tableName) { SQLiteDatabase db = this.getWritableDatabase(); int x = db.delete(tableName, null, null); db.close(); return x; } ```
Android SQLite delete table not actually deleting the rows
[ "", "android", "mysql", "ios", "sql", "sqlite", "" ]
I'm currently encountering an issue with dividing by zero - I'm trying to implement `CASE` to just mark the divided number as "1" however, I'm still getting the error - I'm guessing I'm missing something here? Just not sure what... ``` SELECT CASE WHEN c.PageCount IS NULL OR c.PageCount=0 THEN 1 ELSE c.PageCount E...
**For easier readability/maintainability of division formulas, wrap every divisor with [`NULLIF(x,0)`](http://msdn.microsoft.com/en-us/library/ms177562.aspx).** This is easier than checking for zeros with a case statement and ensuring the divisor is identical to the case predicate. Everywhere you see a `/ [...]`, make...
OK, 3rd time the charm? I thought I found the problem twice, but I think I know what's going on now. All sql I know, you can't use an aliased column else where in the select. By aliasing c.PageCount to [PageCount] I believe you are still using the original c.PageCount without the table alias. To test this out, just ch...
Divide By Zero Issue
[ "", "sql", "sql-server", "ssms", "" ]
I am trying to create a very simple PostgreSQL function, though I keep getting a very strange syntax error. The syntax I use is different from anything I have seen online (though this is the one the textbook uses), and thus I can't figure out why it fails... This is the SQL: ``` CREATE OR REPLACE FUNCTION gsum(graphI...
Your basic mistakes: * [`DECLARE` must come before `BEGIN`](http://www.postgresql.org/docs/current/interactive/plpgsql-structure.html). * Statements need to be terminated with `;`. * Function body of a plpgsql function is a string and needs to be quoted. Use dollar-quoting to avoid complications with quotes in the bod...
It can be plain SQL in instead of plpgsql ``` create or replace function gsum(graphid integer) returns bigint as $$ select sum(weight) as total from edge where gno = graphid; $$ language sql; ``` Notice that if `weight` is integer `sum` will return `bigint` not `integer`.
SQL (Postgres) function definition - RETURNS
[ "", "sql", "database", "function", "postgresql", "plpgsql", "" ]
SO bear with me I want to create a view that combines data from 2 tables: RETRY: ``` TaskId status 1 13 2 4 ``` Files ``` FileId(key) TaskId Study 1 1 2.3 2 1 2.3 3 2 4.5 4 2 4.5 ``` I need a joined view: ``` TaskId Study 1...
This might work based on the input data and expected data according to your explanation ``` CREATE VIEW [dbo].[TASK_TO_STUDY] As ( SELECT DISTINCT r.task_id,f.Study FROM dbo.RETRY_TASKS r JOIN dbo.FILES f ON f.task_id = r.task_id ); ```
Group by the task. Then you can use an aggregate function (like `min`) to take a specific study ``` CREATE VIEW [dbo].[TASK_TO_STUDY] As ( SELECT dbo.RETRY.task_id, MIN(dbo.FILES.Study) as Study FROM dbo.RETRY_TASKS LEFT JOIN dbo.FILES ON dbo.FILES.task_id = dbo.RETRY.task_id GROUP BY dbo.RETRY.task_id ...
Create a view from 2 tables without repetitions
[ "", "sql", "sql-server", "" ]
I Have a table with below data ``` column1 column2 DIU02 3D ITEM MAINTENANCE DIU02 DISTRIBUTION ITEM UPDATE APPLICATION DIU02 DIU - Distribution Item Update ``` I want for unique DIU02 , all data come in single column using comma seperation. Its for SQL Server Database Below is the Query DECLARE @Data VAR...
``` SELECT @Data = COALESCE(@Data + ',', '') + column2 FROM ( SELECT DISTINCT column2 FROM Table WHERE column1= 'DIU02' ) t ```
I bet you're looking for that one (MS SQL): ``` DECLARE @List VARCHAR(8000) SELECT @List = COALESCE(@List + ',', '') + CAST(column2 AS VARCHAR) FROM yourtable WHERE column1 = 'DIU02' SELECT @List ``` [SQL Fiddle](http://www.sqlfiddle.com/#!3/40af5/1)
Using Distinct and COALESCE Together using variable
[ "", "sql", "sql-server", "database", "" ]
I have a scenario, I have two databases **DB1** and **DB2**. Both database have **same structure**. DB1 contains a table "table1" with **AUTO INCREMENT PRIMARY KEY** 1,2,3,4,5 and DB2 also contains "table1" with primary key 1,2,3,4,5. when I insert data from DB2 to DB1, the data from DB2 will become 6,7,8,9,10. But I...
``` DECLARE @MaxId INT SELECT @MaxId = MAX(Id) FROM Db1 SET IDENTITY_INSERT db1 ON INSERT INTO Db1(Id, Column1, Column2, ...) SELECT @MaxId+ ROW_NUMBER()OVER(ORDER BY Id), Column1, Column2, ... FROM db2 SET IDENTITY_INSERT db1 OFF ``` Try this..
**You may use one of these two scenorio** First: * Copy db1.table1 data in temp table * Truncate db1.table1 * Copy data from db2.table to db1.table1 * Copy data from temp table to db1.table Second: * Copy db1.table1 data to db2.table1 * Truncate db1.table1 * Copy data from db2.table to db1.table1 **Use can use thi...
database copy with same structure having primary key issues
[ "", "mysql", "sql", "" ]
I would like to filter Name,X combinations for which is never X=Y Let's assume the following table: ``` *Name* *X* *Y* A 2 1 A 2 2 <--- fulfills requirement for Name=A, X=2 A 10 1 A 10 2 B 3 1 B 3 3 <--- fu...
Just put the columns into parentheses ``` SELECT * FROM TABLE WHERE (NAME, X) NOT IN (SELECT NAME, X FROM TABLE WHERE X=Y); ``` The above is ANSI standard SQL but not all DBMS support this syntax though. A `distinct` is not necessary for a sub-query for `IN` or `NOT IN`. However `NOT EXIS...
I use this on SQL Server ``` SELECT * FROM TABLE WHERE (SELECT NAME + ';' + X) NOT IN (SELECT NAME + ';' + X FROM TABLE WHERE X = Y); ```
SQL "IN" statement for multiple columns
[ "", "sql", "distinct", "" ]
I have code written in an ASP file which is not working ``` Set Conn = Server.CreateObject("ADODB.Connection") Conn.Open "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Server.MapPath("dbbb.mdb") Dim strSQL Dim strSQL strSQL = "SELECT * FROM people WHERE id =" & Request.QueryString("id") Set rs = Conn....
Your ID field will generally be looking for an number value. So before executing the database query you should check the QueryString Request does actually contain a number. Here is what I do and it will also prevent sql injections. Create Variable ID and Assign the value of the querystring to it. Check the ID value is ...
The most likely problem here is that you are not handling an empty value for your `id` `QueryString` value. Try checking the `id` field *before* executing the code to read the data from the database. As pointed out by others, be careful with SQL injection attacks. Always either use parameters, or if you wish to contin...
asp db receive "SELECT * FROM people WHERE id =" & Request.QueryString("id")
[ "", "sql", "database", "vbscript", "asp-classic", "request.querystring", "" ]
I want an alternative way to write the following query ``` SELECT COUNT(DISTINCT col1) FROM table. ``` I dont want to use `distinct`. Is there an alternative way?
Try `GROUP BY` as a subquery and `COUNT()` from outside query. It would achieve same result. ``` SELECT COUNT(*) FROM ( SELECT Col1 FROM Table GROUP BY Col1 ) tbl ```
Try this ``` SELECT COUNT(Col1) FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col1) As RNO, Col1 FROM Table_Name) WHERE RNO = 1 ```
Alternative for count distinct
[ "", "sql", "sql-server-2008", "" ]
I have a SQL Server script that I'm using to insert some data into a database. I won't upload the whole script here just for space/time savings sake, but I will include the important bits. So here is the problem. I have a table that has a column for some `loginhtml`, this column is of a non-nullable type. I would like...
I may not have mentioned this in the initial post, and I would like to apologize for that. But the way the database is set up, is applications can have parent applications, so setting the loginhtml to the parent application and "technically" skipping adding it to the new application can be done by doing this: ``` if(@...
As long as the column in non null, then you can't insert a null value into it. You could try setting it to a blank string or other default value. You could aslo select the parent's html and insert that instead. There is no way to skip over inserting any column.
Insert statement with a NON-NULLABLE column
[ "", "sql", "sql-server", "insert", "non-nullable", "" ]