Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In the SQL space (specifically T-SQL, SQL Server 2008), given this list of values: ``` Status Date ------ ----------------------- ACT 2012-01-07 11:51:06.060 ACT 2012-01-07 11:51:07.920 ACT 2012-01-08 04:13:29.140 NOS 2012-01-09 04:29:16.873 ACT 2012-01-21 12:39:37.607...
Here is a query that does this, by identifying the groups where the student statuses are the same and then using simple aggregation: ``` select top 1 StudentStatus, min(WhenLastChanged) as WhenLastChanged from (SELECT StudentStatus, WhenLastChanged, (row_number() over (order by "date") - row...
``` SELECT [Status], MIN([Date]) FROM Table_Name WHERE [Status] = (SELECT [Status] FROM Table_Name WHERE [Date] = (SELECT MAX([Date]) FROM Table_Name) ) GROUP BY [Status] ``` Try here `Sql Fiddle`
Find minimum value in groups of rows
[ "", "sql", "sql-server", "t-sql", "group-by", "" ]
I have a temp table with some columns containing numbers. I want to use the columns in the temp table and compare them WITH an IF statement. ``` ... INSERT INTO #tmp EXEC [p_GetComplete] @Car_ID IF Col1 + Col2 = Col3 BEGIN PRINT 'OK' END ELSE BEGIN PRINT 'NO' END ... ```
SQL Is made to operate on SET, so avoid CASE WHEN and IF as long as you can: You can do it this way (recommended): ``` SELECT 'Ok' FROM #tmp WHERE Col1+Col2=Col3 UNION ALL SELECT 'NO' FROM #tmp WHERE NOT (Col1+Col2=Col3) ``` or this way: ``` SELECT CASE WHEN Col1+Col2=Col3 THEN 'Ok' ELSE NO FROM #tmp WHERE ```
You can use case statement, when wanting to insert different value to #tmp table, according to some conditions. Such as on: [SQL Server: CASE WHEN OR THEN ELSE END => the OR is not supported](https://stackoverflow.com/questions/5487892/sql-server-case-when-or-then-else-end-the-or-is-not-supported) If you want search...
IF statement from a temp table
[ "", "sql", "sql-server", "" ]
I 've a query that links many tables. So when executes a stored procedure it gives... ``` Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ``` What can I do for this.. May I have to increase the time out of the SQL server. I'm using SQl 2008. Could you...
When one transaction holds a lock on a data resource and another transaction requests an incompatible lock on the same resource, the request is blocked and the requester enters a wait state. By default, the blocked request keeps waiting until the blocker releases the interfering lock. To get lock information, including...
Timeouts are never in sql server, but always in the client calling them. So, if you can not tune the query (which may be the case) change the timeout in the application you use to issue the query.
The timeout period elapsed.. in my query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How I can write a query that can find me orders having same order lines (details)? Sample Data **Table: Order** ``` ORDER_ID -------- A B C D ``` **Table: OrderDetails** ``` OrderID ProductID ------------------ A ProductX A ProductY A ProductZ B ProductX B ProductY C ProductZ D ProductX D ProductY ...
Maybe something like this is what you want? ``` SELECT DISTINCT Orders.OrderID FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID WHERE OrderDetails.ProductID IN ('ProductX', 'ProductY', 'ProductZ') GROUP BY Orders.OrderID HAVING COUNT(*) = 3 ``` Also note that `Order` is a reserved keyword ...
``` SELECT OrderId FROM (SELECT DISTINCT o.OrderId, p.Product FROM Orders o INNER JOIN OrderDetails p ON o.OrderId = p .OrderId WHERE p.Product IN ('ProductX', 'ProductY', 'ProductZ') ) tab GROUP BY OrderId HAVING COUNT(*) = 3 ```
Sql Query for finding Orders having same order lines
[ "", "sql", "oracle", "" ]
I have the following question: For each city display the number of clients who only rented cars of type 'Toyota' or 'BMW' and never rented 'Mercedes' The tables are as follows: `Car [CarId int, type varchar(30)]` `Client [ClientId int, CityId int, Name varchar(30)]` `City [CityId int, CityName varchar(30)]` `Rent...
Declare @count1 int, @count2 int Select @count1 = Count(\*) From Client inner join Rent on Client.ClientId = Rent.ClientId inner join Car on Car.CarId = Rent.CarId Where Car.type In( 'Toyota','BMW') --except Select @count2 = Count(\*) From Client inner join Rent on Client.ClientId = Rent.ClientId inner join ...
``` select city.cityname, count(*) as cnt from client join city on client.cityId = city.cityId where exists(select * from rent join car on rent.carid = car.carid where client.clientid = rent.clientid and car.[type] in ('Toyota', 'BMW')) and not exists(select * from rent join car on ren...
How could I form a tsql query with 'and' and 'not' for a result
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I have data that is in two tables and I have a query combining the data as below. I am trying to eliminate duplicates based on the Id column where I pick the record with the oldest split date. Could anyone kindly assist me with the SQL statement to effect this? ``` |ID |SecID |ReportingDate |SplitDate |Adjustor...
One approach, that should be ok in Access SQL (though you might need to change the aliases): ``` SELECT a.* FROM Table1 a INNER JOIN ( SELECT ID, sdate = min(SplitDate) FROM Table1 GROUP BY ID ) b ON a.ID = b.ID AND a.SplitDate = b.sdate ``` Also you could take the inner query and make its own qry in Access.
For test data in a table (or saved query) named [Source] ``` ID SecID ReportingDate SplitDate Adjustor ---- ----- ------------- ---------- -------- 1465 2 2009-12-31 2010-11-01 0.1 1465 2 2009-12-31 2012-12-27 0.2 1466 2 2010-12-31 2012-12-27 0.2 1468 2 ...
SQL Statement to eliminate duplicates based on value in another column
[ "", "sql", "ms-access", "group-by", "aggregate-functions", "" ]
For unit testing purposes I need to completely reset/clear SQLite3 databases. All databases are created in memory rather than on the file system when running the test suite so I can't delete any files. Additionally, several instances of a class will be referencing the database simultaneously, so I can't just create a n...
This works without deleting the file and without closing the db connection: ``` PRAGMA writable_schema = 1; DELETE FROM sqlite_master; PRAGMA writable_schema = 0; VACUUM; PRAGMA integrity_check; ``` Another option, if possible to call the C API directly, is by using the `SQLITE_DBCONFIG_RESET_DATABASE`: ``` sqlite3_...
**The simple and quick way** If you use in-memory database, the fastest and most reliable way is to close and re-establish sqlite connection. It flushes any database data and also per-connection settings. If you want to have some kind of "reset" function, you must assume that no other threads can interrupt that funct...
How do I completely clear a SQLite3 database without deleting the database file?
[ "", "sql", "sqlite", "" ]
Hi i need a bit of help with the SQL query below ``` DECLARE @company nvarchar(50) DECLARE @theweek date SET @company = 'RWF' SET @theweek = '2014-02-03' SELECT [thedate],[PRN],[StartTime] ,[FinishTime],[Grade],[BreakTime],[TotalCost],[Department],[CompanyCode] FROM LabourHireCost WHERE thedate BETWEEN @THEWEEK AND...
Based on your current results vs. expected results, it looks like the query is already returning the data that you want. If you want to present it differently, that would be done in your client application (whether it is web app, reporting software, or even Excel), but SQL Server generally should not be used for breaki...
Well how about using a cte to calculate the amount of time everyone (time frame between start and finish )worked on x date and then selecting it?
SQL query group rows by column PRN
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to get the unpaid and partial amount separately in single query ``` select if(i.status = 'unpaid', sum(i.total_amount), '') unpaid, if(i.status = 'partial', sum(i.paid_amount), '') partial from {CI}invoices i where i.customer_id = ? and date(i.invoice_date) < '2014-01-01' and i.s...
Try the following: ``` SELECT SUM( IF(i.status = 'unpaid', i.total_amount, 0) ) unpaid, SUM( IF(i.status = 'partial', i.paid_amount, 0) ) partial FROM {CI}invoices i WHERE i.customer_id = ? AND date(i.invoice_date) < '2014-01-01' AND i.status IN ('unpaid', 'partial') ```
Give this a go: ``` select sum(case when i.status = 'unpaid' then i.total_amount else 0 end) as unpaid, sum(case when i.status = 'partial' then i.paid_amount else 0 end) as partial from {CI}invoices i where i.customer_id = ? and date(i.invoice_date) < '2014-01-01' and i.status not like 'paid...
How to get separate fields data with IF() statement in single query
[ "", "mysql", "sql", "" ]
I am executing the below query and using alias name for all columns. I have named alias with a . since that is a requirement. now, I want to refer to the alias name directly in the where clause and i do is as given below: ``` SELECT pt.prod_desc AS"PROD_DESC", ( CASE WHEN pt.prod_level='2' THEN 'Product' WHEN pt.prod...
You already know you [can't use the alias in the `where` clause](http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries002.htm#sthref2213), but that only applies in the same level of SQL. You can wrap your query in an outer query: ``` SELECT * FROM ( SELECT pt.prod_desc AS"PROD_DESC", ... END)AS ".PRNT_P...
Put the query in a subquery, then you can refer to the aliases in your where clause, e.g.: ``` SELECT * FROM ( SELECT pt.prod_desc AS"PROD_DESC", ...etc... FROM dims_prod_type pt) pt WHERE pt.".PRNT_PROD_ID" like 'A%'; ```
Using alias name in WHERE clause
[ "", "sql", "oracle", "column-alias", "" ]
have table like this : ``` user_id Date Status 1000 2013-04-02 11:46:10.000 IN 1001 2013-04-02 11:50:08.000 OUT 1005 2013-04-02 11:46:24.000 IN 1005 2013-04-02 12:50:04.000 OUT 1005 2013-04-02 12:50:10.000 ...
You can use a [CTE](http://msdn.microsoft.com/en-us/library/ms175972.aspx) + `ROW_NUMBER`: ``` WITH CTE AS ( SELECT user_id, Date, Status, RN = ROW_NUMBER () OVER (PARTITION BY user_id, Status ORDER BY Date DESC) FROM dbo.TableName ) DELETE FROM CTE WHERE RN > 1 ``` Yo...
This answer will also work for older versions of mssql ``` delete t from table t where exists(select 1 from table where t.user_id = user_id and t.status = status and t.date < date) ``` The weakness of this answer is that if you have a senario with the same timestamp, the ...
Delete rows with date check
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have two oracle select statememts, selecting data from same table. ``` SELECT empid, empname, days, SUM (amount) Amount1 FROM tbl_details WHERE particulars IN ('Basic Pay', 'Allowances') GROUP BY empid, empname, days SELECT empid, empname, days, SUM (amount) Amount2 FROM tbl_details WHERE particulars IN ('Water...
I think below will help you ``` SELECT empid, empname, days, Sum (CASE WHEN particulars IN ( 'Water Charge', 'Housing Allowance' ) THEN amount ELSE 0 END) Amount2, Sum (CASE WHEN particulars IN ( 'Basic Pay', 'Allowances' ) THEN amount EL...
Use a [UNION](http://www.techonthenet.com/sql/union.php): ``` SELECT empid, empname, days, SUM (amount) Amount FROM tbl_details WHERE particulars IN ('Basic Pay', 'Allowances') GROUP BY empid, empname, days UNION SELECT empid, empname, days, SUM (amount) Amount FROM tbl_details WHERE particulars IN ('Water Charge'...
Bind two select statements
[ "", "sql", "oracle", "select", "join", "subquery", "" ]
I recently encountered a problem caused by a typo in the database creation script, whereby a column in the database was created as `varchar(0)` instead of `varchar(20)`. I expected that I would have gotten an error for 0-length string field, but I didn't. What is the purpose of `varchar(0)` or `char(0)` as I wouldn't ...
It's not allowed per the [SQL-92](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt) standard, but permitted in MySQL. From the [MySQL manual](http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html): > MySQL permits you to create a column of type `CHAR(0)`. This is useful primarily when you have to b...
Just checked MySQL, it's true that it allows zero-length CHAR and VARCHAR. Not that it can be extremely useful but I can think of a situation when you truncate a column to 0 length when you no longer need it but you don't want to break existing code that writes something there. Anything you assign to a 0-length column...
What's the purpose of varchar(0)
[ "", "mysql", "sql", "sqldatatypes", "" ]
I need to query two columns "oc\_filter\_group\_description.name" and "oc\_filter.name" and get all matching results. The alias seems to be causing me the problem. I've tried using a sub query but being a complete novice I really don't know what I'm doing. Here is the code as it stands. The OR clause is what needs ...
You can't reference column aliases defined in the `select` in the `where` clause. This is your query: ``` SELECT *, (SELECT name FROM oc_filter_group_description fgd WHERE f.filter_group_id = fgd.filter_group_id ) AS `group` FROM oc_filter f LEFT JOIN oc_filter_description fd ...
This might look a minor thing, but you shouldn't use backticks and whenever possible avoid keywords: ``` SELECT *, ( SELECT name FROM oc_filter_group_description fgd WHERE f.filter_group_id = fgd.filter_group_id) AS T_GROUP FROM oc_filter f LEFT JOIN oc_filter_description fd ON (f.filter_id = fd.filter_id) WHE...
multiple tables OR clause and with alias
[ "", "mysql", "sql", "opencart", "" ]
I have 2 tables: `'matches'` and `'players'`. In 'matches' I have individual goals scored and who by. In 'players' I have individual players and goals scored. How do I automatically update the player's total goals scored in the 'players' table when the players name gets a goal next to it in the 'matches' table?
I would create a third table `GOALS`. ``` create table GOALS( GOAL_ID INT, PLAYER_ID INT, MATCH_ID INT, GOAL_TIME DATE, ETC... ); ``` Then use this table to join to the `PLAYERS` and `MATCHES` tables. This allows all `GOALS` to be stored in one location. If you need to determine the amount of goals sco...
Try this one ``` Here third table needed create table GOAL( GID INT(PK), PID INT(FK of players), MID INT (FK of matches) ); when This (GOAL) inserted then use a trigger used and update goal of players CREATE TRIGGER ins_trig AFTER INSERT ON GOAL -> FOR EACH ROW -> BEGIN -> UPDATE players SET go...
mysql: update 2 tables based on 1 input
[ "", "mysql", "sql", "" ]
Does anyone have a good approach for generating a daily summary from a table containing intervals of times given by start and stop dates (where a null stop means continues indefinitely)? The best way to describe the problem is with an example. Imagine a database tracking schedules for workers at a restaurant, where em...
A partition outer join can help fill in calendar data. It is similar to a cross join but may perform much better with non-trivial table sizes. A cross join will join every row in set A with every row in set B. A partition outer join will join every row in set A with every defined subset in set B. The example below g...
I have used a CTE with the sample data that you have provided. I have also changed a few column names to allow me to execute the query. The example is as follows: ``` WITH tbl AS (SELECT 'bottle washer' AS position, 'Fred' AS name, to_date ('01/02/2013', 'mm/dd/yyyy') AS star...
Is there a good SQL approach for summarizing a table with blocks of date ranges as input?
[ "", "sql", "oracle", "" ]
I am creating a high scores table stored on a database for my game, but I was wondering the best practices are for storing such tables. Should the table be resorted each time a new score is added or should the data being received by a query just be sorted? It seems like it would be easier on the server to just sort wh...
Rows in a relational database such as MySQL, Oracle, PostgreSQL, etc. are not maintained in any order. In the theory of relational databases result sets are returned in no specified order unless the query contains an `ORDER BY` clause. Any ordering is (must be) applied each time the data is retrieved. Implementations ...
I recommend sorting the data in your MySQL query. As you said it is easier to only sort when needed, not when every record is added.
Are database tables sorted before or after being retrieved?
[ "", "mysql", "sql", "database", "" ]
i have this tables: Table1: ``` id Name 1 Example1 2 Example2 ``` Table2: ``` id Date.............. 1 5.2.2014........ 1 6.2.2014......... 1 6.2.2014........ 2 16.1.2014....... 2 17.1.2014....... ``` And I need take id and Name from table1 and join table1.id = table2.id and from table2 take only t...
You can use `row_number()` to filter out all but the latest row per `id`: ``` select * from ( select row_number() over (partition by id order by Date desc) as rn , * from Table2 ) as t2 join Table1 as t1 on t1.id = t2.id where t2.rn = 1 -- Only latest row ```
Well, a simple attempt would be ``` SELECT t1.*, (SELECT TOP 1 t2.Date FROM Table2 t2 WHERE t2.ID = t1.ID t2.Date) t2Date FROM Table1 t1 ``` If you were using SQL Server, you could use [ROW\_NUMBER](http://technet.microsoft.com/en-us/library/ms186734.aspx) Something like ``` ;WITH Vals AS ( ...
Join data from two tables and top from table 2
[ "", "sql", "" ]
I'm trying to create a IF NOT EXISTS query in Oralce like this: ``` DECLARE cnt NUMBER; BEGIN SELECT COUNT(*) INTO cnt FROM MY.MYTABLE WHERE MYFIELD = 400; IF (cnt = 0) THEN SELECT 'NO ROWS' AS FAIL FROM DUAL; ELSE SELECT 'SOME ROWS' AS PASS FROM DUAL; END IF; END; ``` but this fa...
Use into to assign value to variable. ``` DECLARE cnt NUMBER; res NVARCHAR2(50); BEGIN SELECT COUNT(*) INTO cnt FROM MY.MYTABLE WHERE MYFIELD = 400; IF (cnt = 0) THEN SELECT 'NO ROWS' INTO RES FROM DUAL; ELSE SELECT 'SOME ROWS' INTO RES FROM DUAL; END IF; END; ``` Also you ca...
I prefer this way of checking for existence: ``` declare dummy varchar2(1); begin select null into dummy from MY.MYTABLE where MYFIELD = 400 and rownum = 1; dbms_output.put_line('some rows'); -- some rows exception when no_data_found then dbms_output.put_line('no rows'); -- no rows end; ``` ...
How to create a IF NOT EXISTS query in Oracle?
[ "", "sql", "oracle", "" ]
I have a table which looks like ``` MyTable ( Student ID, Exam) ``` I want to place a trigger/constraint which describes: A student ID can appear many times and does not have to be unique. However, the pair (Student ID, "French") can only appear once. So each student can only have one "French" entry. French is hard...
Yes, French can only appear once per student, but everything else can appear multiple times. I'm thinking perhaps this is best solved with a index? Similar to: [Oracle SQL Constraint where clause](https://stackoverflow.com/questions/12177369/oracle-sql-constraint-where-clause) ``` CREATE UNIQUE INDEX MyIndex ON MyTab...
Because of the specialized nature of the restriction (only French is restricted) I don't think this can be done with a constraint (although I'd be glad to learn otherwise). One way you CAN solve it is to use a statement trigger: ``` CREATE OR REPLACE TRIGGER NO_DUPLICATE_FRENCH_TRIGGER BEFORE INSERT OR UPDATE ON ...
Trigger/Constraint to restrict inserts or updates
[ "", "sql", "oracle", "plsql", "triggers", "" ]
Question: > Write a SELECT statement that returns these column names and data from the Products table: > > ProductName - The ProductName column > > ListPrice - The ListPrice column > > DiscountPercent - The DiscountPercent column > > DiscountAmount - A column that’s calculated from the previous two columns > > Discoun...
There are several ways this can be done. The common table expression (CTE method) Ex: ``` ;With Data As ( SELECT ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent AS DiscountAmount FROM Products ) Select ProductName, ListPrice, Discoun...
Seems like G.Mastros forgot to sort the result set by discount price in descending sequence. So your whole query should be ``` SELECT ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent As DiscountAmount, ListPrice - (ListPrice - DiscountPercent) As DiscountPrice FROM ...
Calculating column when an ALIAS is involved
[ "", "sql", "sql-server", "alias", "" ]
I need to replace a `NULL` value in a column only when other conditions are matched. ``` Columns: Parent, Child, flag01, lag02 ``` Parent columns has many `NULL` values, but I want to replace the `null` values only when `flag01` and `flag02` is "ok". If `flag01` and `flag02` are both "`Ok`" and Parent is NULL, repla...
So as I though you want a select statement. ``` select case when (parent is null and flag01 = 'OK' and flag02 = 'OK') then 'CT_00000' else parent end as columnSomeName, Child, flag01, lag02 from yourTable ```
``` UPDATE Table_Name SET Column_Name = 'CT_00000' WHERE flag01 = 'OK' AND flag02 = 'OK' AND Parent IS NULL ``` just to select data ``` SELECT CASE WHEN (flag01 = 'OK' AND flag02 = 'OK' AND Parent IS NULL) THEN 'CT_00000' ELSE Column_Name END AS Column_Name FROM Table_Name ```
Change column value when matching condition
[ "", "sql", "oracle", "" ]
I'm creating a traffic report for my company but I'm really stuck on this piece of code.. I have a report number, and type of accidents denoted by number i.e; 1-slight, 2-serious, 3-fatal and 4-not injured. usually an accident report contains more than one number, for instance: a report number 2014123 has a driver w...
The use of `injuryCode` suggests that you need an `Injury` table (if you don't have one already). Ideally, this includes some sort of severity column that you could order by - something like this: ``` CREATE TABLE Injury (injuryCode CHAR(1), severity INTEGER, description VARCH...
This is not an answer, but an attempt to improve your skills. If you stored the injury code as a number like this: ``` 0 = Not injured 1 = Slight 2 = Serious 3 = Fatal ``` Then you could use this clear and simple SQL: ``` select reportnumber, max(injurycode) as injurycode, count(*) as involved from accidents gr...
SQL query to select multiple values
[ "", "sql", "db2", "case", "" ]
I know there are a lot similar questions. Actually I used [this](https://stackoverflow.com/questions/12526194/mysql-inner-join-select-only-one-row-from-second-table) and it works, but I can't figure out how to include records, which don't have match in second table. I use sample Northwind db on MS SQL Server. Using t...
You got repeated customer names, because you link over orderdate. So if you have two or more orders on the last date for some customer you get all these last orders. If I assume that the orderid has the same sequence as the orderdate, following statement should return only one line for each customer. ``` select cs.*, ...
Best way to do this would be CTE with `ROW_NUMBER()` this query will have better cost because you hit `Orders` table only once instead of twice to get the data and once to get max record. ``` WITH LastOrder AS ( SELECT CustomerID ,OrderID ,OrderDate ...
join just last record in second table, but include records don't have match in second table
[ "", "sql", "sql-server", "join", "" ]
I need to find out the SUM of values in a column, which is like '$2' and the type is varchar. How can I convert this on the fly find the SUM ?
You are probably better off using MySQL's implicit conversion: ``` select sum(trim(replace(col, '$', '')) + 0.0) ``` The silent conversion will include cents. In addition, non-numeric characters are after the number will not cause an error. The `trim()` will remove leading spaces which could also affect conversion.
This will remove the first characters ans summarizes the remaining: ``` select sum(substring(field,2)) from table ```
SUM of amounts with Dollar sign
[ "", "mysql", "sql", "" ]
I have made two tables: one with 5 columns and the other with 3 columns. By using left outer join I want my resultant table to show all 5 columns of first table along with just first column of second table. any solution? It shows all 3 columns of second table but I want it to show just one.
`SELECT *` always shows *all* columns from all tables in the query. If you want a subset of these, you have to be more specific. Example: ``` SELECT t1.*, t2.column1 FROM t1 LEFT OUTER JOIN t2 ... ```
``` SELECT T1.*, T2.FirstColumnName FROM T1 LEFT OUTER JOIN T2 ON T1.Id = T2.Id ```
left outer join sql 2012
[ "", "sql", "" ]
What I am trying to do is something like this ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...); ``` This is wrong obviously. But I am trying to get something that would work the way this would (if it did).
You were **very** close ``` INSERT INTO books (borrower_name, isbn) SELECT 'Jane', isbn FROM table_name -- WHERE id = ? ``` *You might want to limit number of rows coming from `table_name` by using `WHERE` clause and proper condition(s)* Here is **[SQLFiddle](http://sqlfiddle.com/#!2/fc28e/1)** demo --- More o...
What you were doing is also right, u only missed `()` for select statement: ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...); ``` should be modified to: ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",(SELECT isbn from TABLE...)); ``` and it will work perfectly fine!! here ...
How to insert into a table from another table and from user input?
[ "", "mysql", "sql", "" ]
Complicated SQL query needed here, not sure if it's even possible. I have a table like this: ``` ------------------------ |uid |lesson_id |score | ------------------------ |1 |0 |20 | |1 |0 |25 | |1 |0 |15 | |1 |0 |40 | |1 |1 |70 | |1 |0 |10 ...
You can just use subqueries: ``` SELECT uid, SUM(MaxScore), Avg(MaxScore) FROM ( SELECT uid, lesson_id,max(score) as MaxScore FROM scores GROUP BY userid, lesson_id ) AS m GROUP BY uid ``` or for just one user: ``` SELECT SUM(MaxScore), Avg(MaxScore) FROM ( SELECT lesson_id,max(score) as MaxScore FRO...
Here are a simple sample **[SQLFIDDLE](http://sqlfiddle.com/#!2/bf33c9/1)** ``` select Avg(tt.maxscores) from ( select lesson_id,max(score) as maxscores from t group by lesson_id ) as tt ```
MAX, SUM then AVG all in one SQL query?
[ "", "mysql", "sql", "database", "" ]
I am attempting to generate item cost history. Items have cost values that change over time. For easier reporting, I'm trying to generate output that has a cost value by item by week ending date. What I'm fighting with is outputting the most recent item cost value for a given week end date, since most of the time the e...
I'm not sure if this is the best way to do it, but this gets me the result I want. ``` select item_id , tran_end_dt , cost from (select distinct item_id, tran_end_dt from item cross join datestable) a outer apply (select top 1 item_cost as cost from itemcosthist ich w...
See this I think I have here what you are looking , but not too sure why you would like to do so anyway heres my solution ``` SELECT item_id ,eff_dt ,item_cost FROM ItemCostHist UNION SELECT item_id ,DATEADD(dd, 7-(DATEPART(dw, eff_dt)), eff_dt) [WeekEnd] ,item_cost FROM ItemCostHist ``` ...
Most recent cost value as of date by item
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a list of data that I would like to order descending but i would like to start out with numbers then go to strings. Example of what I'm looking for. ``` 43a 34a 22a 11d ztc xtc ytc ``` but if you just do ``` SELECT list FROM table ORDER BY list DESC; ``` It outputs the list like this. ``` ztc xtc ytc 43a...
**Test table** ``` CREATE TABLE Data (str varchar(3)) INSERT INTO Data SELECT '43a' UNION SELECT '34a' UNION SELECT '22a' UNION SELECT '11d' UNION SELECT 'ztc' UNION SELECT 'xtc' UNION SELECT 'ytc' ``` **TSQL** ``` SELECT str FROM DATA ORDER BY 1-ISNUMERIC(LEFT(str, 1)) , str DESC ``` [ISNUMERIC](http://technet.mi...
Something like this: ``` ;WITH CTE AS ( SELECT A FROM (VALUES('ztc'), ('xtc'), ('ytc'),('43a'),('34a'),('22a'),('11d')) T(A) ) SELECT * FROM CTE ORDER BY Left(A, PATINDEX('%[a-Z]%', A) - 1) DESC ```
How do you order a list by numbers then by strings descending?
[ "", "sql", "sql-server", "" ]
I have the following table ``` product_id product_name image_path misc ---------- -------------- ------------ ------ 1 flex http://firstpl... {"course_level_id":19,"group_id":"40067"} 2 Android http://firstpl...
The `REGEXP` function just returns 0 or 1. You will have to use other string functions. Try this: `substr(misc,locate('group_id',misc)+11,5) as Misc`. But that assumes that group\_id always has 5 characters. So this is better: `substring_index(substr(misc,locate('group_id',misc)+char_length('group_id')+3),'"',1) as M...
Since this question was asked MySQL have introduced support for the JSON data type. In MySQL 5.7.8 (and up) you can query the actual JSON string stored in the column using `JSON_EXTRACT()` or the equivalent `->` alias. EG: ``` SELECT product_name, image_path, JSON_EXTRACT(misc,'$.group_id') AS `group_id` FROM ref_p...
How to retrieve values stored in JSON array in MySQL query itself?
[ "", "mysql", "sql", "json", "" ]
I have the following table. city, state, and zipcode are all varchar type and can be NULL. ``` MyContacts -id (int PK) -city (varchar null) -state (varchar null) -zipcode (varchar null) ``` I would like to return city, state, and zipcode formatted as a single value as follows: ``` Seattle WA 98423 if all are not NUL...
``` CASE WHEN COALESCE(city,state,zip_code) IS NOT NULL THEN TRIM(REPLACE(CONCAT(IFNULL(city,""), " ", IFNULL(state,""), " ", IFNULL(zip code,"")), " "," ")) ELSE NULL END ``` OR `CONCAT_WS` already handles NULL effectivel...
Maybe this? ``` SELECT CONCAT_WS(' ',COALESCE(city,''),COALESCE(state,''),COALESCE(zipcode,'')) AS location ```
Using SQL concat and coalesce to display when values are null
[ "", "mysql", "sql", "concatenation", "coalesce", "" ]
Iam trying to use group by statement but it gives me this error :- Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause But I need to group them accordind to their Feeid. ``` select st.ID,af.Fee_Head_Name,SUM(Amount) as tamt from admission af join st...
Try like this ``` SELECT Fee_Head_Name , SUM(Amount) FROM TABLE1 GROUP BY Fee_Head_Name ``` # [GROUP BY](http://technet.microsoft.com/en-us/library/ms177673.aspx) **EDIT** IF you want to select ID also then use this ``` SELECT MIN(ID),Fee_Head_Name , SUM(Amount) FROM TABLE1 GROUP BY Fee_Head_Name ```
``` select af.Fee_Head_Name,SUM(Amount) as tamt from admission af join student st on af.ID= FeeID group by af.Fee_Head_Name ``` group by with column in your select statement
How to use Group By statement
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "group-by", "" ]
I am building a web application with cakephp 2.4 and I have firstly designed my users table with an integer auto-incrementing id, than since my urls are structured as : `http://mywebsite/users/view/username` I realized that instead of using an integer auto-increment, it may be better for performance to use username(VAR...
As per other answers, use an integer for your PK. Pick the correct int size depending on how many records you're expecting. Not using an integer PK with Cake might cause some problems. if you're using a Framework, stick with it's conventions - that's the advantage of a framework! DO NOT generate a unique route for eve...
Don't use varchars as your primary key. It's horrible for performance, you need to explicitly check that you don't have duplicate keys, it's not conventional, foreign keys then need to be varchar, the router won't handle it properly... ugh. If you're worried about SEO, then you can read up on how [the cakePHP router c...
cakephp mysql ,autoincrement id or varchar as primary key
[ "", "mysql", "sql", "cakephp", "" ]
I have a small difficulty with writing a query: I have following table: ``` ID | FromId | ToId -------------------------- 1 10 15 2 10 15 3 15 10 4 15 10 5 15 20 6 14 15 7 20 15 8 20 ...
You can do this as: ``` select least(fromId, toId) as fromId, greatest(fromId, toId) as toId from MyTable t where fromId = 10 or toId = 10 group by least(fromId, toId), greatest(fromId, toId); ``` EDIT: (In response to your question about performance.) You should have indexes on `fromId` and `toId`. Your original ...
I think this should work, ``` SELECT * FROM myTable WHERE FromId = 10 OR ToId = 10; ```
MySql select multiple column unique row
[ "", "mysql", "sql", "distinct", "" ]
I am trying to format a Vertica date column into only the month. I would need the final value in some sort of date datatype so in the report I can order the results by date/time, not order by text. So that February sorts after January etc. ``` select TO_DATE(TO_CHAR(purchase_date), 'Month') from transactions order ...
How about this? ``` select to_char(purchase_date, 'Month') from transactions order by purchase_date; ``` You can order by columns that are not in the `select` list. EDIT: If you want to combine months from multiple years, the above will not work quite right. This will: ``` select to_char(purchase_date, 'Month') fr...
``` Select TO_CHAR((NOW() - INTERVALYM '1 MONTH'), 'MON'); ``` Output: ``` JUN ``` This will help you get only the name of the previous month.
How to format a Vertica date column into just the month?
[ "", "sql", "vertica", "" ]
``` select COUNT(DISTINCT devices) AS "Devices" from measure_tab where measure_tab.time >= 1375243200 and measure_tab.time < 1375315200; ``` The output of the above sql query gives a table with a column named "Devices" with number of devices. I want the time which is one of the attributes of measure\_tab should ...
You can use function as below: ``` select FROM_UNIXTIME(UNIX_TIMESTAMP(),'%a %b %d %H:%i:%s UTC %Y'); ``` output will be: ``` 'Wed Feb 05 05:36:16 UTC 2014' ``` In your query ``` select COUNT(DISTINCT devices) AS "Devices", FROM_UNIXTIME(measure_tab.time,'%a %b %d %H:%i:%s UTC %Y') as d from measure_tab where ...
In Mysql you can use [from\_unixtime()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime) function to convert unix timestamp to `Date`: ``` select COUNT(DISTINCT devices) AS "Devices" from measure_tab where measure_tab.time >= from_unixtime(1375243200) and measure_tab.ti...
How to convert the UNIX TIME into SQL datetime format
[ "", "mysql", "sql", "datetime", "timestamp", "" ]
I am trying to write a query that will produce the top row and bottom row in one query. I can find one or the other but I cant get both in one row. Here is what I have: ``` SELECT (SELECT top(1) Lastname + ',' + firstname FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on orderI...
Here is one way using window functions: ``` select name from (SELECT Lastname + ',' + firstname as name, row_number() over (order by sum(quantity)) as rownum, count(*) over () as cnt FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on or...
Possibly we can use sub query for this. The idea is to find out the Max and Minimum ordered items. Then we can use existing query and write something like sum(quantity) in (Sub Query Here). Or can you check if the following works? ``` SELECT (SELECT Top(2) Lastname + ',' + firstname FROM CUSTOMERS join orders o...
How to return top and bottom row in one query?
[ "", "sql", "sql-server", "" ]
I'm going to use example tables. tblAnimal: ``` --------------------------------- |Animal | Colour | Gender | --------------------------------- |Dog | | | --------------------------------- ``` tblDescription: ``` ------------------------------- | Animal | ID | Description | ----------...
``` Create table tblDescription( Animal varchar(20), ID int, Description varchar(20) ) Insert into tblAnimal(Animal) values ('Dog') Insert into tblDescription Select 'Dog',1,'Male' union all Select 'Dog',92,'White' Select * from tblAnimal Select * from tblDescription ---Update Update a SET Colour = (Select d.desc...
Try this : ``` UPDATE tblAnimal a SET a.Colour = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 92), a.Gender = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 1) ```
SQL Update with CASE statement
[ "", "sql", "sql-server", "sql-update", "" ]
I have two queries, and I want to join the first query with the second in SQL, here are my queries, FIRST QUERY ``` OleDbCommand Query1 = new OleDbCommand(); Query.CommandText = "SELECT [Mastertable].ID " + "FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [relationship].SW1_ID " + "WHERE ([Masterta...
``` OleDbCommand Query2 = new OleDbCommand(); Query2.CommandText = "SELECT [SW Mastertable].SW_PN, [SW Mastertable].[SW_Ver], [SW relationship].[SW2_Category]," + " [SW Mastertable].[Component_Name] " + " FROM " + "(SELECT [Mastertable].ID as ID " + "FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [...
You can join Query1 to the second (outer) Query2 as a derived table as follows: ``` SELECT [SW Mastertable].SW_PN, [SW Mastertable].[SW_Ver], [SW relationship].[SW2_Category], [SW Mastertable].[Component_Name] FROM (SELECT [Mastertable].ID FROM [Mastertable] INNER JOIN [relationship] ON [Masterta...
How to Join a query to another query
[ "", "asp.net", "sql", "" ]
I have 2 tables A and B. Table A contains **names** and table B contains **selected names**. Now I would like to perform the following query on these tables using greendao, Please let me know if it is possible and if it is not are there any alternatives (maybe a raw query). ``` select * from A inner join B on A.nam...
I think this might help. You can use the raw query as a fake join. And you get all you want in the Query object ``` Query query = ATableDao.queryBuilder().where( new StringCondition("nameid IN " + "(SELECT nameid FROM B_Table )").build(); ``` Since "nameid" doesn't seems to be a unique identifier in your sample. I wo...
Try this: ``` List<ATableObj> listATableObj = ATableDao.queryRawCreate(", BTable BT WHERE BT.nameid = T.nameid").list(); ```
How to Perform the following query using Greendao ?
[ "", "android", "sql", "greendao", "" ]
Iam getting the error ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ID' int, 'MGR_ID' int, 'DEPT_ID' int, 'NAME' VARCHAR2(30), 'SAL' int, ' at line 3 while creating a table. I have already a table department with PK ...
Use back ticks ( ` ) to define object names, but not single quotes ( ' ). Your table definition shall be: ``` CREATE TABLE emp ( `ID` int, `MGR_ID` int, `DEPT_ID` int, `NAME` VARCHAR2(30), `SAL` int, `DOJ` DATE, PRIMARY KEY (`ID`) , FOREIGN KEY (`MGR_ID`) REFERENCES emp(`ID`) ...
Don't quote your field names with `'`. That turns them into strings, not field names. ``` CREATE TABLE emp ( id int, mgr_id int, etc... ); ``` If you **DO** need to quote a field name because it's a reserved word, you use backticks: ``` CREATE TABLE emp ( `desc` int <---"desc" is a reserved word etc....
1064 sql error in create table statement
[ "", "mysql", "sql", "" ]
I am running a `SELECT INTO` statement like this so I can manipulate the data before finally dropping the table. ``` SELECT colA, colB, colC INTO #preop FROM tblRANDOM ``` However when I run the statement and then, without dropping the newly created table, I then run either of the following statements, the table isn'...
Temp tables aren't stored in the local database, they're stored in `tempdb`. Also their name isn't what you named them; it has a hex code suffix and a bunch of underscores to disambiguate between sessions. And you should use [`sys.objects`](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms19032...
I'd prefer to query `tempdb` in such manner: ``` IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb.[dbo].[#MyProcedure]') AND type in (N'P', N'PC')) BEGIN print 'dropping [dbo].[#MyProcedure]' DROP PROCEDURE [dbo].[#MyProcedure] END GO ```
Finding #temp table in sysobjects / INFORMATION_SCHEMA
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have the following SQL that creates the table below: ``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (sc.cOLUMN3, 'XXX') AS cOLUMN3 FROM tabel AS c COLUMN1 COLUMN2 COLUMN3 1 1 XXX 1 1 26785 1 1 23432 1 1 XXX ``` I want to add two new ...
``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (c.cOLUMN3, 'XXX') AS cOLUMN3, (CASE WHEN COALESCE(c.cOLUMN3, 'XXX') = 'XXX' THEN 0 ELSE 1 END) AS NEWCOLUMN_A, 1 AS NEWCOLUMN_B FROM tabel AS c ``` Alternatively, since column 3 is derived... ``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE...
First add the columns to the table: ``` ALTER TABLE tabel ADD NEWCOLUMN_A BIT NULL; ALTER TABLE tabel ADD NEWCOLUMN_B BIT NULL; ``` then `UPDATE` the table: ``` UPDATE tabel SET NEWCOLUMN_A = CASE WHEN COLUMN3 = 'XXX' THEN 0 ELSE 1 END, NEWCOLUMN_B = 1 ```
Add new columns to exsiting table in view
[ "", "sql", "sql-server", "" ]
This is the Query I have written ``` Select C.CUST_NAME,P.PROD_DESCRIP from Customer C JOIN (Ord O,OrderItem OT, Product P) ON (C.CUST_ID = O.CUST_ID AND O.ORD_ID = OT.ORD_ID AND OT.PROD_ID = P.PROD_ID) GROUP BY C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC ``` But the issue is it giving me **Right Parenthesis** Missing...
Although that join syntax is allowed in some databases, it is really much clearer to split out the joins: ``` Select C.CUST_NAME, P.PROD_DESCRIP from Customer C JOIN Ord O on C.CUST_ID = O.CUST_ID JOIN OrderItem OT on O.ORD_ID = OT.ORD_ID JOIN Product P ON OT.PROD_ID = P.PROD_ID GROUP B...
``` SELECT C.CUST_NAME, P.PROD_DESCRIP FROM Customer C INNER JOIN Ord O ON C.CUST_ID = O.CUST_ID INNER JOIN OrderItem OT ON O.ORD_ID = OT.ORD_ID INNER JOIN Product P ON OT.PROD_ID = P.PROD_ID GROUP BY C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC ```
Missing Right Parenthesis issue
[ "", "sql", "" ]
Say I run the following query on psql: ``` > select a.c1, b.c2 into temp_table from db.A as a inner join db.B as b > on a.x = b.x limit 10; ``` I get the following message: > NOTICE: Table doesn't have 'DISTRIBUTED BY' clause -- Using > column(s) named 'c1' as the Greenplum Database data distribution key > for this...
1. DISTRIBUTED BY is how Greenplum determines which segment will store each row. Because Greenplum is an MPP database in most production databases you will have multiple segment servers. You want to make sure that the Distribution column is the column you will join on usaly. 2. temp\_table is a table that will be creat...
For your first question, the `DISTRIBUTE BY` clause is used for telling the database server how to store the database on the disk. ([Create Table Documentation](http://postgres-xc.sourceforge.net/docs/0_9_7/sql-createtable.html)) I did see one thing right away that could be wrong with the syntax on your Join clause wh...
DISTRIBUTE BY notices in Greenplum
[ "", "sql", "greenplum", "" ]
A comma separated file contains two columns with two strings. ``` A, abc* A, abc.def.ghi A, abc.def.ghi.jkhl B, abc.def.gh B, cde.def.abc B, cde.def.* ``` The char \* is a wildcard matching zero or more. What is the simplest way to remove reduntant lines, i.e matches to any wildcard line? Preferably with Unix filter...
Using awk ``` awk -F \* 'NR==FNR{if (/\*/)a[$1]} NR>FNR{ if (/\*/) {print;next} s=0 for (i in a) {if ($0~i){s++;break}} if (s==0) print }' file file ``` ### Explanation * `-F \*` Use \* as Field-Splitting * `if (/\*/)a[$1]` save $1 of the line with \* into array a, so get two : `A, abc` and `...
You could do this in SQL as: ``` select t.* from table t where not exists (select 1 from table t2 where t.col1 = t2.col1 and t.col2 like replace(t2.col2, '*', '%') and t.col2 <> t2.col2 ); ```
Filter data based on matches within data
[ "", "sql", "sed", "filter", "awk", "" ]
When using oracle SQL is it possible to run a query based on a text\_string from a subquery? An example might clarify what I'm trying to do ``` select count(sql_text), sql_text from (select sql_text from query_table) sql_table group by sql_text; ``` The outer query is intended to count th...
Generally, this isn't a particularly good design-- storing SQL in tables and dynamically executing it introduces all sorts of security and maintenance issues. It is probably possible (though it's way too late on a Friday that started way too early for me to try to figure it out) to do a really cool XML query along the...
Going through Basics.. When the database executes an `SQL` 1) It would first do `SEMANTIC` check by validating the *syntax* and the *objects* (tables and columns used) in SQL. 2) Based on it, the `optimizer` draws a `PLAN`(calculating the indexes to be used, with the available table statistics and histograms).. ...
Can an oracle SQL query execute a string query selected from a table?
[ "", "sql", "oracle", "oracle11g", "" ]
I have a table that stores basic site information, another one that stores the site address, and a third table for the phone. My phone table contains phone numbers, and the type of number. What I want to do is get my site information, and the main contact number and fax number. So far, my statement looks like this: `...
Yes, you can do this by adding another join to `dbo.phone`. To distinguish between the two uses, you will need to give the second join an alias. So, something like: ``` SELECT site.isiteid, site.iclientid, csitecode, csitename, binactive, caddress1, caddress2, ccity, cstateid, czip...
Add another `JOIN` clause ``` LEFT JOIN dbo.phone f ON dbo.site.isiteid = f.isiteid AND f.iphtypeid = 3 ``` You would then add f.cfax to the `SELECT` list. It might also be good to give the other tables aliases so you can distinguish which columns are coming from which tables.
SQL Query that sorts information into two new columns based on a third column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
The tables are: ``` blogs blog_id, user_id, blog_content users user_id, user_name comments comment_id, blog_id, user_id, comment_content ``` What I'd like to do is get the: blog\_content, the user\_name of the person that created the blog, the comment\_content associated with the particular blog, and the user\_name...
You can have multiple joins on the same table. Each join will retrieve another set of data from that table. In order to include the same table multiple times in a single query, you must create an [alias](http://www.w3schools.com/sql/sql_alias.asp) for at least one of the copies so that SQL knows which one you are refer...
You need to join the comments table back to another copy of the users table: ``` SELECT b.user_id, b.blog_id, b.blog_content, u.user_id, u.name, c.comment_id, c.blog_id, c.user_id, c.comment_content , uc.name as commentor_name FROM blogs b LEFT JOIN users u ON u.user_id = b.user_id LEF...
sql - joining 3 tables on same column
[ "", "mysql", "sql", "" ]
I have 2 columns from a table and i want to add a third column to output the result of a calculation select statement at the moment is: ``` select revenue, cost from costdata ``` my 2 columns are revenue and cost table name: costdata my formula is: `= ((revenue - cost)/ revenue)*100` I want the third column to ...
Query: ``` SELECT revenue, cost, CASE WHEN revenue <> 0 THEN ((revenue - cost) / revenue) * 100 ELSE 0 END As result FROM costdata ```
``` SELECT revenue , cost , ((revenue - cost) / revenue) * 100 As result FROM costdata ``` You mentioned in the comments that you get a divide by zero error. This wll occur when `revenue` equals zero. What you want to happen in this scenario is up to you but this should get you started ``` SELECT revenue...
Add a column into a select for calculation
[ "", "sql", "sql-server", "formula", "" ]
I have two tables named tblborrow and tblreturn wherein they both have date columns. Now, what I am trying to do is to display almost all my columns from both tblborrow and tblreturn, in order by their date\_borrowed and date\_returned in union. My tblborrow contains the following columns: * borrow\_id * isbn * memb...
If you want to separate rows for a borrow/return combination, then `union all` is appropriate. If so, I think this does what you want: ``` SELECT b.isbn, b.member_id, b.staff_id, date_borrowed, 'borrow' as which FROM tblborrow b UNION ALL SELECT b.isbn, b.member_id, r.staff_id, date_returned, 'return' as which FROM tb...
Try this by adding a join on your union set ``` SELECT a.isbn, a.member_id, a.staff_id, b.staff_id, u.combined_date FROM tblborrow AS a LEFT JOIN tblreturn AS b ON a.borrow_id = b.borrow_id LEFT JOIN (SELECT borrow_id, date_borrowed AS combined_date FROM tblborrow ...
MySQL: Using left join and union in one query
[ "", "mysql", "sql", "phpmyadmin", "" ]
Given the following example tables ``` TABLE_A ----- ID ----- 1 2 3 4 5 TABLE_B --------------------------- TABLE_A_ID DETAIL --------------------------- 1 val_x 2 val_x 2 val_y 4 val_y 5 val_other ``` I am...
You could use another `LEFT JOIN` to eliminate ids with a 'val\_y' value; ``` SELECT a.id as table_a_id, b1.detail FROM table_a a LEFT JOIN table_b b1 ON a.id = b1.table_a_id LEFT JOIN table_b b2 ON a.id = b2.table_a_id AND b2.detail = 'val_y' WHERE b2.detail IS NULL ``` [An SQLfiddle to test with](http://sqlfiddle....
``` SELECT sub1.id table_a_id, sub1.detail FROM ( SELECT a.id, detail FROM table_a a LEFT JOIN table_b b on a.id = b.table_a_id) sub1 LEFT JOIN ( SELECT DISTINCT table_a_id FROM table_b WHERE detail = 'val_y') sub2 ON sub1.id = sub2.table_a_id WHERE sub2.table_a_id IS NULL ``` The `sub2` subqu...
MySQL Join: Omit ALL repeating rows IF one row meets a condition
[ "", "mysql", "sql", "database", "join", "" ]
I have a huge (~500mb) SQL file that I need to run on my database. It is a data dump from a production database that I need to put into my development database. Normally, if it were smaller, I'd paste it into the SQL tab and run it, but that would definitely blow up my browser. If I import that SQL file into the devel...
You should try to import it from the console, so you do not depend on the file upload limitations: ``` C:> mysql -u root -p < file.sql ```
I can suggest two options that you can try: 1.I would say try BigDump. I had the exact same problem before. You can read and follow this article for more information: <http://moeamine.com/how-to-upload-a-big-sql-file-to-mysql> You can download big dump from the link below: <http://www.ozerov.de/bigdump/> 2.you can...
How to Run Large SQL File in PHPMyAdmin
[ "", "mysql", "sql", "phpmyadmin", "" ]
I am returning multiple rows of a column as one single row and column: ``` SELECT STUFF(( SELECT '<br/>' + Notes FROM DailyTaskHours WHERE Notes IS NOT NULL AND Notes <> '' AND NonScrumStoryId = DTH.NonScrumStoryId ...
Your database engine is not doing that, ASP.NET is doing it. It is a security feature to help prevent XSS. You can set the **HtmlEncode** property on the bound field like the example at this [MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.htmlencode%28v=vs.110%29.aspx) link: ``` <a...
In your application, you probably want to do an `HttpUtility.HtmlDecode` on the string. From MSDN: > Converts a string that has been HTML-encoded for HTTP transmission into a decoded string. <http://msdn.microsoft.com/en-us/library/system.web.httputility.htmldecode(v=vs.110).aspx> In fact, it's probably preferred t...
Rendering line breaks in HTML from SQL datasource
[ "", "asp.net", "sql", "sql-server", "datasource", "" ]
So if you look at the last `WHERE` clause. `Where inv_location_id in` One of them I am using an `integer` and the other is a `set`. How can I combine these? ``` IF ( @inventory_location_id = NULL ) SELECT clinic_desc , dbo.fn_get_clinic_address_formatted(@application_name, ...
Just change the where to be ``` WHERE ( ( @inventory_location_id IS NULL AND ( inv_location_id IN ( SELECT ilr.clinic_id FROM dbo.inv_location_reconciliation ilr WHERE inv_location_reconciliation_id = @reconciliation_id ) ) ) OR ( ...
I like CTEs with complicated queries because I think it makes them easier to read, so I would do something like below. There are many other ways to solve this problem and I don't claim this is the the fastest. *I haven't tested it so proceed with caution* ``` with clinic_list AS ( SELECT ilr.clinic_id as clinic_...
How can I combine this sql where clause to use one Select?
[ "", "sql", "t-sql", "" ]
I am working with Microsoft SQL Server 2012. I have two tables T1 and T2 and they both have an `ID` column. When I enter the following SQL statement in my Microsoft SQL Server Management Studio ``` select ID from T1 natural full outer join T2 ``` it generated the following error: > Msg 102, Level 15, State 1, Lin...
There are no Natural JOINS in Sql server, You have to explicitly tell sql server on which fields you want table to join. 1) Using `ON` clause and explicitly using the column names from both tables. 2) Or in older JOIN Syntax explicitly using the column names from both tables in WHERE Clause. for another nice answer ...
SQL Server/Transact SQL simply doesn't support Natural Join syntax. Btw, the parser is not complaining about the "natural" because it assumes this is a table alias :-)
Natural full outer join does not work in my SQL Server Management Studio
[ "", "sql", "sql-server", "sql-server-2012", "" ]
So I have received this error: #1066 - Not unique table/alias: 'Purchase' I am trying to do the following: ``` SELECT Blank.BlankTypeCode ,Blank.BlankCode ,Payment.Amount ,Payment.Type ,Purchase.PurchaseDate ,Payment.DatePaid FROM Blank INNER JOIN Ticket ON Blank....
You need to use table aliases. You have mentioned the same table more than once in the `from` clause. The query is something like this: ``` SELECT b.BlankTypeCode, b.BlankCode, pa1.Amount, pa1.Type, p1.PurchaseDate, pa2.DatePaid FROM Blank b INNER JOIN Ticket t ON b.BlankCode = t.Blank_BlankCode INNER JOIN MCO_Blank m...
You need a different alias for the table each time you use it. ``` SELECT B.BlankTypeCode, B.BlankCode, A1.Amount, A1.Type, P1.PurchaseDate, P1.DatePaid FROM Blank AS B JOIN Ticket AS T ON B.BlankCode = T.Blank_BlankCode JOIN MCO_Blank AS M ON B.BlankCode = M.Blank_BlankCode JOIN Purchase AS P1 ON T.Purc...
Inner Joining the same table multiple times
[ "", "sql", "inner-join", "" ]
I'm stuck a little with a combine MySQL query. It's a part of a multi-language, multi-destination site, so I need to retrieve some text parts of the site from multiple table, with fallback. Order of possible hits: > corrected@local\_tbl > english@local\_tbl > corrected@global\_tbl > > english@global\_tbl. Because it'...
``` SELECT * FROM ((SELECT 1 precedence, `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected`='1' LIMIT 1) UNION (SELECT 2 precedence, `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart...
The reason you get no result when one of the subqueries is empty is, with ``` select * from s1, s2, s3, s4 ``` you have an implicit join. And when one of the sub-results is empty, the resulting join is empty as well. To solve this, you can use your subqueries as columns. This will give you the same result, but with ...
MySQL multi-table SELECT
[ "", "mysql", "sql", "select", "subquery", "multiple-tables", "" ]
I need to use my horizontal query result to another SQL query. How to do it, Please help. Suppose I have two Tables: ``` Tab1: ________________________________________ |ID | ARID | SEQ1 | SEQ2 | SEQ3 | SEQ4 | |___|______|______|______|______|______| |a1 | ar01 | A | C | B | D | |a2 | ar02 | C | D | ...
Please use `UNION ALL` to get benefit of INDEX. ``` SELECT t1.ARID, t1.SEQ1 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID = 'ar01' AND t1.SEQN = t2.SEQ1 UNION ALL SELECT t1.ARID, t1.SEQ2 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID = 'ar01' AND t1.SEQN =...
try this for `ARID='ar01'` ``` SELECT A.* FROM Tab2 A, Tab1 B WHERE A.ARID='ar01' AND A.ARID=B.ARID AND (A.SEQN=B.SEQ1 OR A.SEQN=B.SEQ2 OR A.SEQN=B.SEQ3 OR A.SEQN=B.SEQ4) ```
How to use my horizontal query result to another SQL query
[ "", "mysql", "sql", "sql-server", "" ]
Let`s say I have the following table ``` +----+-------+ | Id | Value | +----+-------+ | 1 | 2.0 | | 2 | 8.0 | | 3 | 3.0 | | 4 | 9.0 | | 5 | 1.0 | | 6 | 4.0 | | 7 | 2.5 | | 8 | 6.5 | +----+-------+ ``` I want to plot these values, but since my real table has thousands of values, I thought about...
Depending on your DBMS, something like this will work: ``` SELECT ChunkStart = Min(Id), ChunkEnd = Max(Id), Value = Avg(Value) FROM ( SELECT Chunk = NTILE(5) OVER (ORDER BY Id), * FROM YourTable ) AS T GROUP BY Chunk ORDER BY ChunkStart; ``` This creates 5 ...
You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row: ``` select avg(Value) from some_table where id % 10 = 0; ``` You could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval: ``` sel...
Get Average value for each X rows in SQL
[ "", "mysql", "sql", "" ]
How do I get the current records based on it's Effective Date? Should I use a subquery? Is there anything I could use aside from MAX? I have these table examples. ``` ResourceID is the ID number of the Resource. OrganizationId is the current Organization or Department of the Resource. Effective Date is the start dat...
I suppose there's other ways to do this, but I think this works: ``` DECLARE @OrganizationID varchar(40) SET @OrganizationID = 'SMESM1HTOVEOVE' SELECT ro.ResourceID, ro.OrganizationID, max(ro.EffectiveDate) FROM ResourceOrganization ro WHERE ro.OrganizationID = @OrganizationID GROUP BY ro.ResourceID, ...
You may also try this using CTE ``` ;WITH tmpWithUID As ( SELECT Row_Number() OVER(ORDER BY ResourceID, EffectiveDate, OrganizationID) AS rowNumber, ResourceID, OrganizationID, EffectiveDate FROM dbo.ResourceOrganization GROUP BY ResourceID, EffectiveDate, OrganizationID ) SELECT Reso...
How do I get the current records based on it's Effective Date?
[ "", "sql", "sql-server-2008", "" ]
I have two tables leagues and seasons.. seasons has `league_id, start_date` I am trying to grab the latest season for each league.. and then order the results by the season's start date in asc order. ``` SELECT * FROM leagues JOIN ( SELECT id as season_id, title as season_title, league_id, start_date FROM season...
You will need to use a `MAX()` aggregate in the subquery to get the latest `start_date` per season, and join that back against the `seasons` table. ``` SELECT /* Don't SELECT * in production code - trim this to just the columns you actually need */ leagues.*, seasons.* FROM /* Start with an inner join ...
You can do this quite simply and without subqueries using a self-join: ``` SELECT s1.*, l.* FROM seasons s1 LEFT JOIN seasons s2 ON s2.league_id = s1.league_id AND s2.start_date > s1.start_date JOIN leagues l ON l.id = s1.league_id WHERE s2.league_id IS NULL ORDER BY s1.start_date ``` This method generally outper...
MYSQL subquery using order by and group by
[ "", "mysql", "sql", "" ]
I am trying to write a query to generate automated report. This report is to run for last month's transactions it should run on 1st of every month. I have job to run this report to run 1st of every month. But how can I make this query to choose no of days in a month? (some months will have 30 and some will have 31 and ...
Found solution but forget to reply here. Here is my solution ``` select id,name,address,trans_dt from tab1 where trans_dt between trunc(trunc(sysdate,'MM')-1,'MM') and trunc(sysdate,'MM'); ``` above will give you report from 1st day of month to last day of month from calender.
mySQL ``` SELECT id, NAME, address, trans_dt FROM tab1 WHERE MONTH(trans_dt) = 02 /* Param for month passed in */ AND YEAR(trans_dt) = YEAR(CURDATE()) ``` Oracle ``` SELECT id, NAME, address, trans_dt FROM tab1 WHERE to_char( dt_column, 'mm' ) = 02 /* Param for month p...
How to write a Report query based on number of days in a month?
[ "", "sql", "oracle11g", "" ]
What does this part of code do? ``` ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; ``` I've searched on the internet about the MyISAM and it's the default storage engine, and the CHARSET=utf8 is used for special characters.
`ENGINE=MyISAM` Set DB Engine sample it And InnoDB ... `AUTO_INCREMENT=1` Set Start number of `id` Or Primary KEY `DEFAULT CHARSET=utf8;` SET charset For Other Languages Or other char's This code is part of DB config And usually used in .sql files ... This code is Query And Used in MySQL Database's
You almost got it. with `ENGINE=MyISAM` you specify that you are using `MyISAM` engine. with `AUTO_INCREMENT=1` you are resetting the `auto-increment`field to start from 1. with `DEFAULT CHARSET=utf8` to specify default server character set and collation.
What does this code in SQL do?
[ "", "mysql", "sql", "" ]
I am trying to delete the contents of some tables. I want the user to select the table names and these are concatenated to a string. eg: `Brands,Products,ProductGroups` this string is passed to the stored procedure `DBReset`. I have a function to split the string and return the values as a table. It works fine. Now I w...
## APPROACH 1: You cannot delete from multiple tables from a single query (Unless you have a foreign key constraint between your tables and activate the "cascade delete" option on the constraint) In your case, the most simple approach would be to replace the comma as shown below and use dynamic SQL: ``` DECLARE @CON...
you will most likely need to iterate over the result set from the split, and then use exec to execute the sql with the table in the scope of the current iteration of the loop, adding in your where clause as you go. you can do this via a cursor, or within a while loop.
Delete contents from tables specified by user
[ "", "sql", "sql-server-2008", "stored-procedures", "" ]
``` #Region "FillListView" Sub FillListview() LV.Items.Clear() myqry = "SELECT AccResult.StudNo,Exercises.ID from AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.ID ORDER BY AccResult.FirstName,AccResult.YrandSec Asc;" mycmd = New OleDbCommand(myqry, con) con.Open() ...
Your JOIN condition is incorrect. ``` AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.ID ``` is joining the primary key of the parent table (AccResult.StudNo) with the primary key of the child table (Exercises.ID). You need to join the primary key of the parent table (AccResult.StudNo) with the **forei...
Not sure if I get the question correctly, but it looks like the query only select to columns : ``` myqry = "SELECT AccResult.StudNo,Exercises.ID from AccResult..." ``` then the code try to display all columns. Try to select all columns instead : ``` myqry = "SELECT * from AccResult..." ```
Inner Join in VB.Net
[ "", "mysql", "sql", "ms-access-2007", "inner-join", "vb.net-2010", "" ]
So I have this issue, I have this table Locations{id,name}. In a query how can I get the number of different permutations two by two? For example I have three locations: * Portugal * Spain * UK The combinations are * Portugal,Spain * Spain Portugal * Portugal,UK * UK,Portugal * Spain,UK * UK,Spain So the returned ...
Do like this : ``` SELECT COUNT(1) FROM (SELECT t1.name as name1, t2.name as name2 FROM Locations t1, Locations t2 WHERE t1.name <> t2.name) ``` Here is an example <http://sqlfiddle.com/#!4/41a10/3>
As others have stated, if you just want the number, that's easy to do as it's just a math problem. If you actually want all the combinations, you're looking for a cartesian product, except you want identical pairs filtered out. See below - ``` with tbl as( select '01' as id, 'Portugal' as name from dual union all se...
Oracle arrangements
[ "", "sql", "oracle", "" ]
Friends I am stuck in a stored procedure. I am unable to display distinct records. I have a name `USERS` and `Photos`. Both are inner join using `userID`. Since the table `Photos` has multiple records the search result is repeated. Friends can you help me fix this please? **Stored procedure:** ``` ALTER PROCEDURE d...
You can do something like this using `CROSS APPLY` ``` SELECT u.userID ,u.userName ,P.filename ,u.FirstName ,u.LastName ,u.nationality ,u.Country ,u.City ,u.age ,u.status FROM users u CROSS APPLY ( SELECT TOP 1 photos...
modify Your select query by :- ``` SELECT users.userID, photos.filename, users.userName, users.FirstName, users.LastName, users.nationality, users.Country, users.City, users.age, users.status FROM users INNER JOIN photos ON users.userID = photos.userID WHERE (users.age >= @age) AND (users.age <= @age2) ...
SQL Server : select distinct records with inner join and where clause
[ "", "asp.net", "sql", "sql-server", "" ]
My question is simple. I have two tables, a `product` table and an `image` table with multiple images of each product. `Product` table ``` +-----------+-------------+ | productId | ProductName | +-----------+-------------+ | 1 | product1 | | 2 | product2 | +-----------+-------------+ ``` `Image...
You can select only one imageId (the minimum) per each productId by joining to filtered imageId like this : ``` SELECT p.ProductId, ProductName, i.imageId, imagePath FROM product p INNER JOIN Image i ON i.ProductId = p.ProductId INNER JOIN (SELECT MIN(imageId) As imageId, ProductId FR...
In SQL Server 2005 I did this with a nested query that found min or max imageId grouped by productId. Maybe there's a better way in 2008. ``` select productId, productName, minImageId, imagePath from product inner join ( select productId, min(imageId) as minImageId from Image ...
Join and get only single row with respect to each id
[ "", "sql", "sql-server", "sql-server-2008", "" ]
``` ID | user_id | name | active 1 | 1 | Profile 1 | f 2 | 1 | Profile 2 | t 3 | 2 | Profile 3 | f 4 | 2 | Profile 4 | f 5 | 3 | Profile 5 | f ``` I'm using PostgreSQL. In my application,`users` can create multiple `profiles` and I want to select last distinct **inactive profile...
I would combine [`DISTINCT ON`](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564) with [`NOT EXISTS`](http://www.postgresql.org/docs/current/interactive/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS). Assuming a proper `boolean` type for active: ``` SELECT DISTINC...
[SQL Fiddle](http://sqlfiddle.com/#!15/de3c4/1) ``` select distinct on (user_id) id, user_id, name, active from t inner join ( select user_id from t group by user_id having not bool_or(active) ) s using(user_id) order by user_id, id desc ```
SQL statement to get distinct data
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I've googled this for quite some time but I'm just not sure 'how' to pose the question so that google knows what I mean. I have an application that I'm developing in visual studio. Right now it's just a basic windows form with a search text box for a user to enter data and a search button to search the sql database and...
Thank you @DonA and @Michael for helping me!! Using your info and a few more google's, I devised the following code and very happy to say that it works. :-) ``` Private Sub SearchButton_Click(sender As System.Object, e As System.EventArgs) Handles SearchButton.Click If stunumtxtbox.Text = "" Then MsgBox("...
Some simplification of your work. If your datatable has no rows then you have no matches. ``` Dim count = da.Fill(dt) If count = 0 then ' you have no matches ' do you logic for no matches here Else ' fill data fnametxtbox.Text = dt.Rows(0)("firstName").ToString mnametxtbox.Text = dt.Rows(0)("midleInitial").ToS...
Searching SQL via Windows Form
[ "", "sql", "vb.net", "visual-studio", "" ]
I am looking for a free SQL database able to handle my data model. The project is a production database working in a local network not connected to the internet without any replication. The number of application connected at the same times would be less than 10. The data volume forecast for the next 5 years are: * 3 ...
I work for Percona, a company that provides consulting and other services for MySQL solutions. For what it's worth, we have worked with [many customers](http://www.percona.com/about-us/customers) who are successful using MySQL with very large databases. Terrabytes of data, tens of thousands of tables, tables with bill...
MySQL has a two important (and significantly different) database engines - MyISAM and InnoDB. A limits depends on usage - MyISAM is nontransactional - there is relative fast import, but it is too simple (without own memory cache) and JOINs on tables higher than 100MB can be slow (due too simple MySQL planner - hash joi...
What data quantity is considered as too big for MySQL?
[ "", "mysql", "sql", "database", "postgresql", "" ]
I have a table with a column of floats. All the time that I need a median (or first quartile, for example) I have to compute it first and in other query I compute average, total sum, number of records, etc... (all together). My question is: Is there a way to compute median, average, total sum,... in the same query?
You can do the following in SQL Server 2005 and upwards: ``` SELECT AVG(Salary) as AVERAGE, MAX(case when seqnum = cnt / 2 then salary end) as median, MAX(SALARY) as MAXIMUM, MIN(SALARY) as MINIMUM, SUM(SALARY) as TOTAL, TOTAL as NUMBER_OF_EMP FROM (SELECT e.*, count(*...
I have found this function in SQL Server 2012 that does what I want: <http://technet.microsoft.com/en-us/library/hh231327.aspx> I couldn't solve the problem in just one query but it is more clean than the option I had before. Look this functional example: [SQLFIDDLE](http://sqlfiddle.com/#!6/36e2e6/18/0) Supose I h...
Calculating median in the same query
[ "", "sql", "sql-server", "" ]
What is the good approach to keep a `nvarchar` field unique. I have a field which is storing URLs of MP3 files. The URL length can be anything from 10 characters to 4000. I tried to create an index and it says it cannot create the index as the total length exceeds 900 bytes. If the field is not indexed, it's going to ...
You could use CHECKSUM command and put index on column with checksum. ``` --*** Add extra column to your table that will hold checksum ALTER TABLE Production.Product ADD cs_Pname AS CHECKSUM(Name); GO --*** Create index on new column CREATE INDEX Pname_index ON Production.Product (cs_Pname); GO ``` Then you can retr...
You can use a hash function (although theoretically it doesn't guarantee that two different titles will have different hashes, but should be good enough: [MD5 Collisions](https://stackoverflow.com/questions/201705/how-many-random-elements-before-md5-produces-collisions)) and then apply the index on that column. [MD5 i...
Sql Server - Index on nvarchar field
[ "", "sql", "sql-server", "nvarchar", "" ]
My current table looks like this: ``` ID TYPE QUANTITY 1 A1 3 2 B1 2 3 A1 2 4 B1 8 ``` And after doing the query I want to get that: ``` ID TYPE QUANTITY SUM 1 A1 3 5 2 B1 2 10 3 A1 2 5 4 B1 8 10 ``` The SUM ...
``` SELECT t.ID,t.TYPE,t.QUANTITY,x.SUM FROM TABLE t LEFT JOIN (SELECT ID,TYPE,QUANTITY,SUM(QUANTITY) AS SUM FROM TABLE GROUP BY TYPE)x ON t.type=x.type ``` [**SQL Fiddle**](http://sqlfiddle.com/#!2/b6d4e/6)
My approach is to use a derived table which aggregates the quantity by type first and then join this result with the original data: ``` select t.id, t.type, t.quantity, tmp.overall from table t join ( select table.type, sum(table.quantity) as overall from ...
SQL, add column with summed values of the same type
[ "", "mysql", "sql", "" ]
For the DB gurus out there, I was wondering if there is any functional/performance difference between Joining to the results a SELECT statement and Joining to a previously filled table variable. I'm working in SQL Server 2008 R2. Example (TSQL): ``` -- Create a test table DROP TABLE [dbo].[TestTable] CREATE TABLE [db...
The database engine has an optimizer to figure out the best way to execute a query. There is more under the hood than you probably imagine. For instance, when SQL Server is doing a join, it has a choice of at least four join algorithms: * Nested Loop * Index Lookup * Merge Join * Hash Join (not to mention the multi-t...
This would give the same result? ``` SELECT t.*, s.* FROM dbo.TestTable AS t JOIN dbo.TestRefTable AS s ON t.id = s.id AND s.id = 1123 ``` Basically, this is a cross join of all records from `TestTable` and `TestRefTable` with `id = 1123`.
Join to SELECT vs. Join to Tableset
[ "", "sql", "sql-server", "performance", "t-sql", "database-performance", "" ]
I have a table with approx 100,000 rows per day, each containing the date they were added. However, rows are only added on business days, so no weekends or bank holidays. I'm trying to find an efficient way to find the `Max(BusinessDate)` and also the next highest `max(BusinessDate)`. However, when I try the following...
``` SELECT MAX(dates.BusinessDataDate) AS BusinessDataDate, MIN(dates.BusinessDataDate) AS PreviousDataDate FROM (SELECT TOP 2 'cb_account' AS TableName , BusinessDataDate FROM cb_account GROUP BY BusinessDataDate ORDER BY BusinessDataDate DESC) dates ```
If I've got it right try this: ``` WITH T as ( SELECT MAX(BusinessDataDate) as MaxD FROM cb_account ) SELECT MaxD, (SELECT MAX(BusinessDataDate) FROM cb_account WHERE BusinessDataDate<T.MaxD) FROM T ```
Select Max(Date) and next highest Max(date) from table
[ "", "sql", "sql-server", "query-optimization", "" ]
I have the following data: ``` Server AvgValue Server1 1.29 Server2 0.2 Server3 1.74 Server4 0.58 Server5 2.06 Server6 2.82 ``` I'd like to show the count of servers that have an: 1. AvgValue < 10 2. AvgValue > 10 and < 30 3. ...
I think the most simple approach is to use a query like this: ``` SELECT Server, COUNT(*) AS ServersCount FROM ServersTable WHERE AvgValue < 10 GROUP BY Server ``` You didn't mention anything about the RDBMS that you're using. If you're using MySQL, check the documentation about [COUNT()](https://dev.mysql.com/doc/re...
You can do it in a single query like ``` select server, count(Server) as NUmber_Of_Server, sum(floor(AvgValue)) as Avg_Score from tab group by Server ``` See a demo fiddle here <http://sqlfiddle.com/#!2/0e05e/5>
Count Rows Under Within Specific Ranges
[ "", "sql", "" ]
I have to find how many times a user appears in two different tables ... for now I used a union I have this Query And I Want to do A `SUM` of my record ``` (SELECT s.proprietario_id as p, COUNT(*) as conta FROM sn_like_spotted s GROUP BY s.proprietario_id ORDER BY COUNT(*) DESC, s.id ASC ) UNION ALL (SELECT s.propr...
Use a subquery! ``` SELECT p, SUM(conta) AS conta FROM ( SELECT s.proprietario_id as p, COUNT(*) as conta FROM sn_like_spotted s GROUP BY s.proprietario_id UNION ALL SELECT s.proprietario_id as p, COUNT(*) as conta2 FROM sn_like_risposta s GROUP BY s.proprietario_id ) AS baseview GROUP BY p ORDER BY...
I don't know mySQL but don't you want to union the results set together and then to do the group by? Conceptually somthing like ``` SELECT s.proprietario_id as p, COUNT(*) as conta from ((SELECT s.proprietario_id as p FROM sn_like_spotted s ) UNION ALL (SELECT s.proprietario_id as p FROM sn_like_risposta s )) GROUP...
Sum Union Mysql
[ "", "mysql", "sql", "" ]
I have here a complicated query here where I have nested case with subquery. I am having trouble with getting the right structure of it. Here is my code: ``` select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top ...
If you indent your code, you'll spot errors like this more easily (below). Note however that your query still has grouping issues - you'll either need to add `TranDate` and `RemainingBalance` to the `GROUP BY`, or use aggregates on them. I've taken a guess below without any understanding of your query: ``` select ...
You need an `END` before the Q1 : ``` select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN(Case when Datepart (...
What is the proper structure for Nested Case statement with Subquery Sql Statement?
[ "", "sql", "sql-server", "nested", "subquery", "case", "" ]
Which is intended to fetch the results quicker ? *Single column data* from 400 tables or 400 columns from a *single table* ?
400 results from one table is definitely faster than 1 result from each of the 400 tables. Think about needing to enter the first 400 phone numbers from the NYC phone book. So you decide to read the first number from phonebook A, the second number from phonebook B, ... , and the last number from the 400th phonebook. It...
As per my Knowledge fetching data from single table will be faster. If you are fetching data from single table you do not need to specify any joining condition. If you are having any situation where you want to fetch data from single column you can use the [ColumnStoreIndex](http://blog.aspplatinum.com/) feature of SQ...
Which is intended to fetch the results quicker?
[ "", "mysql", "sql", "database", "" ]
I have the following SQL Query that counts Orders and groups them by each Day (Date). Thus the following results: ``` 01/02/2014 = 10 02/02/2014 = 2 05/02/2014 = 7 07/02/2014 = 4 ``` Query: ``` SELECT TOP(@NumberOfRecords) DATEADD(dd, 0, DATEDIFF(dd, 0, AddedDate)) AS Date, COUNT(DISTINCT ID) AS Count ...
``` DECLARE @mindate DATETIME DECLARE @maxdate DATETIME DECLARE @diff INT SELECT @maxdate = MAX(addeddate), @mindate = MIN(addeddate) FROM OrderSpecs SET @diff = DATEDIFF(DAY, @mindate,@maxdate) ;WITH cte(dt,level) AS ( SELECT @mindate AS dt, 0 AS level UNION ALL SELECT DATEADD(day,1,cte.dt),level + 1 fr...
If you issue a lot of such queries then you can create a calendar table that contain all calendar dates ``` CREATE TABLE calendar([date] DATE NOT NULL PRIMARY KEY); ``` And then use an outer join ``` SELECT TOP(@NumberOfRecords) c.Date, COALESCE(o.Count, 0) Count FROM Calendar c LEFT JOIN ( SELECT DATEA...
SQL Count Records, Group By Date and fill in missing date?
[ "", "sql", "" ]
I have a Query which gets the **average score** from the **answers** table, And groups it by the category which the question is in. This query gets the desired result for answers **where the coach\_id = 0** This is the desired result in which for every coach\_id i get another row ![enter image description here](https...
What you want is a conditional sum, I think. Column score\_0, that gets the average score for coach\_id = 0. Column score\_1, that gets the average score for coach\_id = 1. The count will not work neither, as count ... counts everything! Both coach\_id 0 and 1. So you'll have to use a conditional sum there, too. Bes...
Since you haven't provided your table schemas I would have a hard time writing the query for your actual example. What you want is the `SUM(IF(...))` pattern, aggregating on a conditional: ``` SELECT foo_id, SUM(IF(bar_id = 1, baz, 0)) as sum_baz_bar_1, SUM(IF(bar_id = 2, baz, 0)) as sum_baz_bar_2, SUM(IF(bar_...
One query for multiple where?
[ "", "mysql", "sql", "" ]
I have a table which amongst other things contains a DateTime column. What is the best way to get the maximum number of rows within x seconds of each other? So if I have the following rows: ``` 1 2014-02-09 01:01:01 2 2014-02-09 01:01:02 3 2014-02-09 01:01:03 4 2014-02-09 01:05:01 5 2014-02-09 01:05:11...
This query seems to do the job (for TSQL) ``` WITH CTE AS ( SELECT Id, value, CNT.X FROM tbl T1 OUTER APPLY ( SELECT COUNT(*) X FROM tbl T2 WHERE Datediff(second, T1.value, T2.value) BETWEEN 0 AND 10 ) CNT ) SELECT MAX(X) FROM CTE ``` Here is a fiddle that will show only the CTE itself (wi...
You didn't specify which DBMS you're using. This Standard SQL should run (almost) everywhere, you just have to modify how add seconds to a timestamp: ``` SELECT MAX(cnt) FROM ( SELECT Id, value, (SELECT COUNT(*) FROM tbl t2 WHERE t2.value BETWEEN t1.value AND t1.value + INTERVAL '10' SECOND) AS c...
SQL Get maximum number rows where DateTime is within x seconds
[ "", "sql", "" ]
I've got a bit of code that I'm looking at the moment : ``` User.includes([:profile => :schedule]).where('...') ``` This loads all profiles and their schedules. So the query produced by this is select \* user fields, select \* profile fields, select \* schedule fields I'm filtering out users based on one field from ...
This should work: ``` User.joins(profile: :schedule).where('....').select('....') ```
Try this: ``` User.joins(profile: [:schedule]).where('...') ``` or ``` User.joins(profile: :schedule).where('...') ```
How to join more than one table rails
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "" ]
I am using SSIS package to import data from cvs file to table. ``` CVS File Report_Date 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 ``` I want to convert in to 2014-02-05 date format.How can i do tha...
You can use `CONVERT(` function to change that into date. For example ``` SELECT CONVERT(DATE,'20140210',112) ``` After you change it into date you can output it into any format that you want. Read <http://msdn.microsoft.com/en-us/library/ms187928.aspx> for list of all styles that you can use for `DATE` when convert...
I have not tested it with SSIS but if you look at TSQL output of these queries ``` Select Cast(20140125 AS DATETIME) Select Cast('20140125' AS DATETIME) ``` First one failed with "Arithmetic overflow error converting expression to data type datetime." But second succeed.. It means if you convert first it to string a...
Date format conversion of cvs column to table column using SSIS Package?
[ "", "sql", "t-sql", "ssis", "sql-server-2012", "dataflow", "" ]
I am getting the following error while trying to configure FileStream in SQL server 2012. **There was an unknown error applying the filestream settings. check the parameters are valid. (0x80041008)** I am configuring it using SQL server configuration manager. Where as I am able to setup it for SQL server 2008 R2.
I had this same problem just yesterday. In my case it was because I had a 64-bit Windows and a 32-Bit SQL Server. You do not see the exact error, but if you try to do it with T-SQL, then the proper error comes up in SQL, telling you something about "WOW64" not supporting filestream. I just uninstalled and installed ...
In my case the problem I was running the SQL Server **2014** configuration manager. While this usually shouldn't cause problems, in my case it did. Configuring FILESTREAM using the SQL Server *2012* configuration manager worked. If it still doesn't work, make sure you're up-to-date. SQL Server 2012 has received quite ...
There was an unknown error applying the filestream settings. check the parameters are valid
[ "", "sql", "sql-server", "sqlfilestream", "" ]
I have a table with the following: * eventid -> primary key, higher numbers mean newer * itemid -> foreign key to an items table * message -> event message There will be 100/1000s of events for each itemid. What I need is to get the X newest events from the table for every unique value of itemid. In this case X is 20...
If you want a fixed number of "latest" entries, you need to use the window function [row\_number()](http://www.postgresql.org/docs/current/interactive/functions-window.html) (not `rank()`). Although, if the `eventid` happens to be unique (per `itemid`), the only (slight) difference is performance. (Your question update...
I would imagine that it is quite expensive and there may be better ways, but would something like this work for you? ``` select itemid, message from events e where eventid in (select eventid from events f where e.itemid=f.itemid order by eventid desc limit 20) order by itemid ``` The subquery finds the mo...
Select the X newest rows for each unique value of a column
[ "", "sql", "postgresql", "greatest-n-per-group", "window-functions", "" ]
This is my MySQL query: ``` SELECT ROUND(SUM(cfv.NUMBERVALUE),0) AS mysum FROM jissue ji JOIN customfieldvalue cfv ON ji.ID=cfv.ISSUE WHERE ji.pkey LIKE '%PB-%' AND cfv.customfield=11381 AND ji.issuestatus=10127; ``` There are two possible cfv.customfield (11381 and 11382) and five possible ji.issuestatus (10127 -> ...
1. As said wumpz and Anthony Grist, you use `GROUP BY` to return all 2\*5 sums *without sums for missing entries*. 2. To return sums for missing entries, you use LEFT JOIN. Difference between `tableexpr1 JOIN tableexpr2 ON ...` and `tableexpr1 LEFT JOIN tableexpr2 ON ...` is with LEFT JOIN entries from tableexpr1 are o...
Something like this: ``` SELECT cfv.customfield, ji.issuestatus, ROUND(SUM(cfv.NUMBERVALUE),0) AS mysum FROM jissue ji JOIN customfieldvalue cfv ON ji.ID=cfv.ISSUE WHERE ji.pkey LIKE '%PB-%' AND cfv.customfield IN (11381, 11382) AND ji.issuestatus IN (10127, 10128, ..., 10131) GROUP BY cfv.customfield, ji.issuestatus...
Can I combine ten similar SQL queries to one?
[ "", "mysql", "sql", "" ]
Why Mysql's Group By and Oracle's Group by behaviours are different I found many times that Mysql's groupBy functionality and Oracle's GroupBy funcnality are behaving different Many times I found error in Oracle(which is actually wrong query) but Mysql will give result in to this so is there any reason behind this M...
The MySQL designers put in their nonstandard extension to `GROUP BY` in an attempt to make development easier and certain queries more efficient. Here's their rationale. <https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html> There is a server mode called `ONLY_FULL_GROUP_BY` which disables the nonstandard ...
Oracle does not extend the older SQL Standard that states that all items in the select list not contained in an aggregate function must be included in the group by clause. The [MySQL Docs](https://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html) state: --- > In standard SQL, a query that includes a GROUP BY...
Why Mysql's Group By and Oracle's Group by behaviours are different
[ "", "mysql", "sql", "oracle", "group-by", "aggregate-functions", "" ]
I have one DB table which contains Payment(Merchant,Transaction,TimeStamp).where for teach transaction we can have multiple merchants. Now i want to form a query where for transaction in (val1, val2, val3) , we will get the merchant who did latest transaction.eg: ``` Merchant Transaction Time --------------------...
``` SELECT Merchant FROM DB_TABLE WHERE transaction IN(T1, T2, T3) ORDER BY Time DESC LIMIT 1 ```
``` select * from Payment group by transaction order by Time desc; ```
Regarding sql queryformation
[ "", "mysql", "sql", "" ]
I have a table called documents with a row called Nigel Harding ``` DOCUMENTS id | label 24 | Nigel Harding ``` He has been tagged with two other documents one with an ID of 1 & 12 that table is called document tags ``` DOCUMENT_TAGS id | label | Document_id 1 | TAG A | 24 12 | TAG B | 24 ``` I am trying to create ...
I think the most flexible way to approach this type of problem is to use aggregation with a `having` clause. Here is one example: ``` SELECT dt.document_id FROM documents_tags dt GROUP BY dt.document_id HAVING sum(dt.tag_id = 1) > 0 and sum(dt.tag_id = 12) > 0; ``` Each condition in the `having` clause counts...
If I understand your question, you're just lacking `IN` and `DISTINCT`: ``` SELECT DISTINCT documents.id FROM documents LEFT JOIN documents_tags ON documents.id=documents_tags.document_id WHERE documents_tags.tag_id IN (1, 12) ORDER BY documents.label ``` Using `IN` you'll be getting documents for any of the tag ...
SQL Multiple Left joins
[ "", "mysql", "sql", "" ]
I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column. Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate `Sequence` ``` Create SEQUENCE RandomSeq start with 1001 increment by 1 Go Insert into YourTable(Id,col1...) Select NEXT VALUE FOR RandomSeq,col1.... ``` or else you can use `Identity` ``` Identity(seed,increment) ``` You can start the seed from 1101 and increment the se...
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value. If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want. Alternatively you can u...
SQL Server Database unique number generation on any record insertion
[ "", "sql", "sql-server", "database", "" ]
For example, I got a table: ``` Name , Area, Age cat , 1 , 10 dog , 2 , 7 cat , 3 , 11 horse , 4 , 4 cat , 5 , 10 dog , 6 , 9 ``` When I group by 'Name', for each group I want to retain the 'Area' of the MAX 'Age' in that group. In this example, I wanna get: ``` Name , A...
Try something like this: ``` SELECT name, area FROM mytable JOIN ( SELECT name, MAX(age) as maxage FROM mytable GROUP BY name ) AS `max` ON mytable.name = max.name AND mytable.age = max.maxage ``` This first selects the `name` and `MAX(age)` in a subquery, and then joins them to the original table so that yo...
This would be more slightly more efficient than the subquery approach mentioned by @deroby and @DamienBlack: ``` SELECT t1.name, t1.area FROM myTable t1 LEFT JOIN myTable t2 ON t1.name = t2.name AND t2.Age > t1.Age WHERE t2.some_primary_key IS NULL ORDER BY t1.name ``` Note that this requires some column known to ...
SQL Grouping: conditional select in each group
[ "", "mysql", "sql", "group-by", "grouping", "" ]
I must not be using the right Google foo to find the correct answer. I have a table that looks like the following: ID Parent  Status   Name 1              NULL     0              Root 2             1              0              Group 1 3             6              400         WINXP32 4              2              4...
Do you mean something like this (Self join in SQL standard)? If it's possible that you have records with missing Parent ID: ``` select t1.name, t2.name as "Group" from tab t1 left join tab t2 on t1.parent = t2.id where t1.status > 0; ``` If Parent ID is always present, you can use an inner join: ``...
Try like thsi ``` SELECT ID, CASE WHEN STATUS = 0 THEN (SELECT Root WHERE Parent = ID) END [Group] Status, Name FROM TABLE1 WHERE STATUS <> 0 ```
Creating a SQL column based on the value of another column in the same table
[ "", "sql", "" ]
IN this sql we are looking for subst\_instructions from the formulary table. we are getting only 1 or 2 of these, even though there should be others with same med in the first table: ``` select * from (SELECT ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX], [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI],...
Sometimes Nulls can hide data you want. e.g. ``` CREATE TABLE #STAT ( ID INT IDENTITY(1,1), STAT INT NULL ) INSERT INTO #STAT (STAT) SELECT 3 UNION ALL SELECT NULL UNION ALL SELECT 4 UNION ALL SELECT 5 SELECT * FROM #STAT SELECT * FROM #STAT WHERE [STAT] NOT IN (3,4) ``` To get arou...
The `where rn = 1` is going to be limiting, if you run the query without that, do the results look more like you expect?
this sql query not returning all data from joined table
[ "", "sql", "" ]
I need update a field with the same table. In the example below The RewRate is set correct in Co 1 , then I need updated the NewRate for Co 4, 10 and 16. based on the EDL Type, EDL Code. Thanks ![enter image description here](https://i.stack.imgur.com/aonaq.jpg) This code is obviously wrong, but i just do not know ho...
There you go. ``` UPDATE t1 SET t1.NewRate=t2.NewRate FROM PRCI t1 INNER JOIN PRCI t2 ON t1.EDLType=t2.EDLType AND t1.EDLCode=t2.EDLCode WHERE t1.PRCo!='1'; ```
You can change ``` and Craft ='xxx' ``` to ``` and EDLCode = 714. ``` As mentioned in the comments, a where clause might be appropriate.
How to update a field in the same table
[ "", "sql", "sql-update", "" ]
I am using PHP, MySQL. I have two tables 1.categories ``` cat_id cat_name 1 cars 2 mobile 3 computers 4 radios ``` 2.posts ``` id title body cat_id 1 title1 txt1 cars 2 title2 txt2 mobiles 3 title3 txt3 mobiles 4 title4 t...
Here is an SQL query that should do the trick: ``` UPDATE posts JOIN categories ON posts.cat_id = categories.cat_name SET posts.cat_id = categories.cat_id ```
Try ``` UPDATE post p JOIN categories c ON p.cat_id=c.cat_name SET p.cat_id=c.cat_id ```
How to Replace and Update Data From One Table to Another Table in MySQL
[ "", "mysql", "sql", "database", "" ]
I'm struggling with a query where there are some null values, and in my CASE statement, the test for the NULL values is not being processed. I've tried ordering the tests differently, but it doesn't seem to make a difference. ``` SELECT Title, library.LibraryID, Registered FROM libraries LEFT JOIN (SELECT LibraryID,U...
This is your query: ``` SELECT Title, l.LibraryID, Registered FROM libraries lLEFT JOIN (SELECT LibraryID, UserID, (CASE WHEN UserID IS NULL THEN "False" <<<<<<<< PROBLEM WHEN UserID=1 THEN "YES! Registered" ELSE "Not Registered" END) AS ...
I'm almost certain this is to do with your join rather than your case statement. That is, you build your subquery result set with the switch to handle NULLs, then LOJ that to libraries, effectively creating wholly NULL records where no match exists. Thus your efforts with the Registered column are for naught. Try re-st...
Are MySQL CASE statements prioritized?
[ "", "mysql", "sql", "" ]