Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a running inventory table of different products that records the inventory count after every transaction. Transactions do not happen every day, so the table does not have a running daily count. I need to have all dates listed for each product so that I can sum and average the counts over a period of time. inve...
Use `inv join inv` to build up at least 31 rows and construct a table of 31 days. Then join the ids, and finally the original table. ``` select a.d, a.id, a.qty, if(a.id=@lastid, @count:=@count+a.qty, @count:=a.count) `count`, @lastid:=a.id _lastid from ( select a.d, b.id, ifnull(c.qty, 0) qty, ifnull(c.count, 0...
Here are the steps needed: 1. Get all dates between the two given dates. 2. Get the initial stock per ID. This is: get the first date on or after the given start date for that ID, read this record's stock and subtract its transaction quantity. 3. For every date get the previous stock. If there is a record for this dat...
SQL Join Inventory Count Table to Date table
[ "", "mysql", "sql", "join", "" ]
When retrieving a list of objects from SQL Server , I am getting the following error: > System.Data.SqlClient.SqlException > Invalid column name 'AccountName' > Invalid column name 'AccountNumber' I understand that the database does not contain those columns, but I don't believe my code should be passing those co...
Reposting from the comment thread: Type Discovery as described **[here](http://msdn.microsoft.com/en-us/data/jj679962.aspx)** is probably at play. The **[[NotMapped]](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute%28v=vs.110%29.aspx)** attribute has the Attribut...
If these are your EF models and the property is not part of the database structure you should be annotating the properties with the **[NotMapped]** Attribute so that the sql generation does not pick up the property and try to add it into the select statement. Hopefully this site should help with explaining the annotat...
Derived Class Properties Getting Passed to SQL Server via Entity Framework
[ "", "sql", "entity", "derived", "" ]
i have two table, i want merge that data in one table how it is possible my data is look like this, ``` table1 (col1 is column name) col1 ------------------ data1 data2 data3 data4 data5 ...
You can do this by adding a `join` key using `row_number()`: ``` select t1.col1, t2.col1 as col2 from (select col1, row_number() over (order by (select NULL)) as seqnum from table1 ) t1 full outer join (select col1, row_number() over (order by (select NULL)) as seqnum from table2 ) t2 o...
``` SELECT col1, col2 FROM ( SELECT col1, ROW_NUMBER() OVER (ORDER BY col1) rn FROM table1 ) a FULL OUTER JOIN ( SELECT col1 col2, ROW_NUMBER() OVER (ORDER BY col1) rn FROM table2 ) b ON a.rn = b.rn ORDER BY COALESCE(a.rn, b.rn); ``` Here - lacking any other sort criteria - I order the columns by their ...
merge row with two column in sql server
[ "", "sql", "sql-server", "sql-server-2008-r2", "sql-server-2012", "" ]
I use the following SQL query to receive all entries that are older than `payment_target` days. ``` SELECT * from orders WHERE(EXTRACT(EPOCH FROM age(CURRENT_DATE, date_trunc('day', orders.created_at))) - orders.payment_target*86400 >= 0) ``` However, I want to modify this query in a way that `orders.invcoice_sent_...
Instead of `if` you can use `coalesce` which will work on every database supporting ANSI SQL: ``` coalesce( orders.invoice_sent_at, orders.created_at) - orders.payment_target*86400 >= 0) ```
If I understand your question correctly, you can use a declared variable. this will also make your code more readable. something along the lines of: DECLARE @DUEDATE DATETIME SET @DUEDATE = ISNULL(("GET THE VALUE FROM orders.invoice\_sent\_at"),("GET THE VALUE FROM orders.created\_at")) use @DUEDATE in your select.
SQL: conditional SELECT
[ "", "sql", "postgresql", "" ]
this is a question for plsql & oracles. I am new to this. Please help! I have 2 tables: Table A and Table B ``` Table A: ID, Date Table B: Name, Address ``` How do I do a join between 2 tables and then have it just return based on latest date. Also, it will be based on specified ID in a list. My current query retur...
You need to `group` your result set. Also you need an aggregat function, in this case `MAX()` This should work: ``` select unique(ID), MAX(a.Date), b.Name, b.Address from tableA a join tableB b on a.ID = b.ID where a.Date > TO_DATE('12/31/2012', 'mm/dd/yyyy') and a.ID in ('1', '3') group by ID, b.Name, b.Address ``` ...
There's lots of ways to do this: This is one. It gets a subset of max dates by the ID and then joins it into what you have already thereby limiting to the max of each group. ``` Select A.ID, A.Date, B.Name, B.Address FROM A INNER JOIN B on A.ID = B.ID INNER JOIN (Select max(date) maxDate, ID from A group by ID) C o...
PLSQL & Oracle - Join 2 tables and only return based on latest date
[ "", "sql", "oracle", "plsql", "" ]
I have lookup table, whose records are being referenced in other tables. For example, a countries lookup table, and a user table referc the country id from countries table. I want to know, how i can get count of references and all the rows in other tables, which have a record with a country id. If a reference of a ro...
``` DECLARE @TableName sysname = 'YourTable' DECLARE @Command VARCHAR(MAX) SELECT @Command = isnull(@Command + ' UNION ALL ', '') + 'Select count(*) ,''' + SCHEMA_NAME(obj.schema_id)+'.'+OBJECT_NAME(fkc.parent_object_id) + ''' '+ 'From ' + SCHEMA_NAME(obj.schema_id)+'.'+OBJECT_NAME(fkc.parent_object_i...
If you give reference as a foreign key, then sqlserver easily help you by [Viewing dependensy](http://msdn.microsoft.com/en-IN/library/ms190624.aspx) and you just select query to [get all table](http://blog.sqlauthority.com/2010/02/04/sql-server-get-the-list-of-object-dependencies-sp_depends-and-information_schema-rout...
How to know if a row in a table is being referenced in other tables before deletion?
[ "", "sql", "sql-server", "foreign-keys", "" ]
I have a table with records of employees that shows a relationship of employees and who they report to: ``` From_ID position TO_ID position ---------------------------------------- 1 Lowest_employee 3 employee 3 employee 4 employee 4 employee 5 ...
This includes setting up test data, however I think this is what you want: Test Data: ``` DECLARE @Table TABLE ( From_ID int, TO_ID int ) INSERT INTO @Table VALUES(1,3) INSERT INTO @Table VALUES(3,4) INSERT INTO @Table VALUES(4,5) INSERT INTO @Table VALUES(2,6) INSERT INTO @Table VALUES(6,3) INSERT INTO @Tab...
``` WITH q (employee, boss) AS ( SELECT fromId, toId FROM mytable WHERE fromId NOT IN ( SELECT toId FROM mytable ) UNION ALL SELECT employee, toId FROM q JOIN mytable t ...
CTE Recursive Queries
[ "", "sql", "sql-server", "recursion", "common-table-expression", "" ]
What is the difference between `cursor` and `view` ? Because none of them store data in the database.
A cursor is defined and used within the scope of a stored procedure (it is used with PL/SQL). On the other hand, a view is a database object (similar to a table), which can be used even outside of stored procedures as well, as in queries (it can be used with both SQL and PL/SQL). **Reference**: 1. [Views on Oracle D...
A view is a pre-defined query which is stored in the database and can be used much like a table. A cursor is a data structure which provides access to the rowset returned by a query. Share and enjoy.
What is the difference between cursor and view?
[ "", "sql", "oracle", "plsql", "" ]
I have a table "User" with 5 columns 'id','firstname','lastname','age','email'. Is it possible to execute this sql command? ``` SELECT LTRIM(RTRIM(firstname,lastname,email)) FROM User ``` All i need to select is the 3 columns that are trimmed.
You have to handle each column separately, as in: ``` SELECT LTRIM(RTRIM(firstname)) as firstname, LTRIM(RTRIM(lastname)) as lastname, LTRIM(RTRIM(email)) as email FROM [User] ```
You need to trim each field separately ``` select ltrim(rtrim(firstname)), ltrim(rtrim(lastname)), ltrim(rtrim(email)) from User ```
TRIM specific column names in SELECT statement
[ "", "sql", "sql-server", "" ]
Say I have the following schema: ``` create table client (clientid int) create table mv (clientid int, fundid int, date datetime, value decimal) insert into client values(1) insert into mv values(1, 1, '1 may 2010', 35) insert into mv values (1,1, '1 may 2011', 434) insert into mv values (1, 2, '1 may 2011', 635) ```...
Try this query without joins: ``` SELECT mv.clientid, mv.fundid, MAX(CASE WHEN date = '1 may 2010' THEN value ELSE 0 END) as startvalue, MAX(CASE WHEN date = '1 may 2011' THEN value ELSE 0 END) as endtvalue FROM mv GROUP BY clientid,fundid ``` `SQLFiddle demo`
Again bear in mind that I have no access to a db right now :( This query should do something similar to what you want ``` SELECT X.CLIENTID, X.FUNDID, Y.STARTVAL, Y.ENDVAL FROM MV X, (SELECT B.CLIENTID, B.FUNDID, COALESCE(A.VALUE,0) STARTVAL, COALESCE(B.VALUE,0) ENDVAL FROM MV ...
How to join where there is a possibility of no record
[ "", "sql", "sql-server", "t-sql", "join", "" ]
Maybe it's too obvious, but I am sure it has to be a simple way to do that ``` SELECT 'Not Contained Yet' AS FlagRow FROM ( SELECT 'Already Contained' FROM MyTable t WHERE t.id=? AND CURDATE()=t.date LIMIT 1 ) aux HAVING COUNT(*)=0 ``` That simply returns no results if the register is already i...
You should be able to do this with `having`: ``` SELECT 'Not Contained Yet' AS FlagRow FROM MyTable t WHERE t.id = ? and CURDATE()=t.date HAVING COUNT(*) = 0; ```
Using `count()` you get `0` if it does not contain the record ``` SELECT count(*) as contains_count FROM MyTable t WHERE t.id = ? AND DATE(NOW()) = t.date ```
Any trick to make a query that ouputs no row when certain conditions are satisfied and a row when they are not (without subselects)?
[ "", "mysql", "sql", "subquery", "" ]
Im having trouble joining two varchar(31) fields on sql server 2008. below is my query and it works fine ``` select A.CustId,A.Country,B.Country from [ACC].[dbo].[Customer] as A left join [Task Centre].[dbo].[CountryCodes] as B on A.Country=B.Country] ``` the results are as follows ``` CustomerA United Kingdom ...
Try to execute the following query on both tables. This will tell you if there's any "hidden" difference between the tables (for example, blank characters, line breaks, etc.): ``` select Country, CAST(Country AS VARBINARY) AS BinaryCountry from [ACC].[dbo].[Customer] where Country = 'United Kingdom' select Country, C...
Try this: If any space is in value you need to trim and check ``` SELECT A.CustId, A.Country, B.Country FROM [ACC].[dbo].[Customer] AS A LEFT JOIN [Task Centre].[dbo].[CountryCodes] AS B ON LTRIM(RTRIM(A.Country)) = LTRIM(RTRIM(B.Country)) ```
Left join on 2 varchar fields not working
[ "", "sql", "sql-server", "sql-server-2008", "" ]
ORA-00904: "COUNT1": invalid identifier 00904. 00000 - "%s: invalid identifier" \*Cause: \*Action: Error at Line: 8 Column: 73 ``` SELECT a1.branch_name AS myfavourite, COUNT(a1.branch_name) AS count1, SUM(count1) AS total_purchase , a1.branch_id AS branch_id, c...
[The documentation](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_10002.htm) is fairly clear that you can't use a column alias as you are trying to, within the same select list as you can *only* use it in the `order by`: > **`c_alias`** Specify an alias for the column expression. Oracle Database wil...
Try this, ``` With Cte(myfavourite,count1,branch_id,city,description,shopmailid,image) As ( SELECT a1.branch_name AS myfavourite, COUNT(a1.branch_name) AS count1, --SUM(count1) AS total_purchase , a1.branch_id AS branch_id, c1.city, c1.Branch_description AS ...
Error while counting Column (Count1) in oracle
[ "", "sql", "oracle", "" ]
I am trying to create a query in MS SQL Server 2012 which gives me a `count`, `average` and some `sum` values of distinct records in a database table. I'll try to explain my situation and my wishes as best as I can. If there remains something unclear or if some extra information is needed, please let me know. Having t...
Since activity does not appear in any of the aggregate functions you can simply discount this from the results, and use a subquery to get distinct records before your aggregation, then also applying `COUNT(DISTINCT CASE..` to your male/female counts: ``` SELECT COUNT(DISTINCT [Number]) AS Number, ROUND(AVG(C...
Your query did not solve the problem because you only told sql to use the distinct data points for one of the columns, the number. When sql moves out of the parentheses and on to the calculations for the next columns, it is no longer using the distinct command. In order to solve your problem, I would recommend the use...
How can I get distinct average and sum values in one MS SQL query?
[ "", "sql", "sql-server", "database", "sql-server-2012", "distinct", "" ]
Below is image which describe my requirements i have a column having different data i want its count on where condition where data=1 as col1 and where data = 2 as col2 and so on.... ![Below is image which describe my requirements i have a column having different data i want its count on where condition where data=1 as...
``` SELECT COUNT(CASE data WHEN 1 THEN 1 ELSE NULL END) as Col1, COUNT(CASE data WHEN 2 THEN 1 ELSE NULL END) as Col2, COUNT(CASE data WHEN 3 THEN 1 ELSE NULL END) as Col3, COUNT(CASE data WHEN 4 THEN 1 ELSE NULL END) as Col4 FROM yourTable ```
``` SELECT SUM(CASE WHEN data=1 THEN 1 ELSE 0 END) AS col1, SUM(CASE WHEN data=2 THEN 1 ELSE 0 END) AS col2 FROM Table ```
I want to display one columns data sum on different columns based on where clause
[ "", "mysql", "sql", "" ]
the below query give me address against order date for three sites. if more than one orders are completed for a site i want to select only latest record for the site ``` SELECT DISTINCT ORDERS.Address, ORDERS.ORDERDATE FROM ORDERS Left JOIN PHONEDATA AS P ON ORDERS.RECID = P.OrderID where client IN ('site1','site...
Assuming that `client` is in the `orders` table: ``` SELECT o.Address, o.ORDERDATE FROM (select o.*, row_number() over (partition by client order by orderdate desc) as seqnum from ORDERS o ) o Left JOIN PHONEDATA P ON o.RECID = P.OrderID where o.client IN ('site1', 'site2', 'site3') and o...
Try this: ``` SELECT ORDERS.Address, MAX(ORDERS.ORDERDATE) AS ORDERDATE FROM ORDERS O LEFT JOIN PHONEDATA AS P ON O.RECID = P.OrderID WHERE client IN ('site1','site2','site3') GROUP BY ORDERS.Address ```
Selecting one record for a day
[ "", "sql", "sql-server", "t-sql", "" ]
I'm getting grey hair by now... I have a table like this. ``` ID - Place - Person 1 - London - Anna 2 - Stockholm - Johan 3 - Gothenburg - Anna 4 - London - Nils ``` And I want to get the result where all the different persons are included, but I want to choose which Place to order by. For example. I want to get a ...
This is one way to get the specified output, but this uses MySQL specific behavior which is not guaranteed: ``` SELECT q.ID , q.Place , q.Person FROM ( SELECT IF(p.Person<=>@prev_person,0,1) AS r , @prev_person := p.Person AS person , p.Place , p.ID FROM...
You want to use `group by` instead of `distinct`: ``` SELECT ID, Person FROM users GROUP BY ID, Person ORDER BY MAX(FIELD(Place, 'London')), Person ASC; ``` The `GROUP BY` does the same thing as `SELECT DISTINCT`. But, you are allowed to mention other fields in clauses such as `HAVING` and `ORDER BY`.
MySQL ORDER BY Column = value AND distinct?
[ "", "mysql", "sql", "asp-classic", "field", "sql-order-by", "" ]
I really don't know how this is called so I couldn't find an answer. For example I have the following tables: ``` Table products Table users +----------+----------+----------+ +----------+----------+ | id | name | price | | username | products | +----------+----------+-------...
This could be solved by changing your data model. ``` users +----------+----------+ | id | username | +----------+----------+ | 1 | Fred | +----------+----------+ | 2 | John | +----------+----------+ products +----------+----------+----------+ | id | name ...
You could try this: ``` SELECT * FROM products pt where FIND_IN_SET(pt.id,(select us.prices from users us WHERE us.username = "David")); ``` ### Working fiddle: <http://sqlfiddle.com/#!2/4f78d/2>
Link to multiple foreign rows from one row
[ "", "mysql", "sql", "" ]
Thanks in advance for your help. I'm working with an application that a user developed. It prompts you for something to search for and then performs a basic query: ``` SELECT * FROM Table WHERE Entry=[ENTRY]; ``` I cannot change that format. All I can do is modify the text of [ENTRY]. Is there a way I can pull multi...
This totally depends on the code. If there is possibility than you can use Sql injection method to request multiple records. ``` SELECT * FROM Table WHERE Entry='COW' OR Entry ='APPL' OR Entry = 'ROO'; ``` Following this example your variable [ENTRY] should be this: ``` [ENTRY] = "'COW' OR Entry ='APPL' OR Entry = '...
If the developer didn't prevent sql injection, you can try add `;` and create a new query. If you can change `=` to `IN`.
How to pull multiple records using SQL statement?
[ "", "sql", "ms-access", "" ]
Using a few SQL queries on our company Netezza box, I'm trying to concatenate a number of values into a single string. The hitch is that I need these values to be ordered, but Netezza won't let me order by terms that aren't grouped because it applies the ordering after doing the grouping. I'm using a UDA called [group...
EDIT: Even better solution. ``` SELECT GRP, CONCAT_DATA FROM ( SELECT GRP, GROUP_CONCAT(data) OVER (PARTITION BY grp ORDER BY id ASC) concat_data, row_number() OVER (PARTITION BY grp ORDER BY id DESC) rn FROM test ) x WHERE rn = 1; ``` **Note that this solution reli...
The not so simple way to do this, if you have the SQL Functions Toolkit installed would be to use `Arrays`. I think a better way would be to add the group\_concat UDF from IBM. Array example below: ``` CREATE temp TABLE TEST (GRP INTEGER, ID INTEGER, DATA VARCHAR(10)); INSERT INTO TEST VALUES (1,3,'Three'); INSERT INT...
Ordering the input to an aggregate function
[ "", "sql", "netezza", "" ]
I have the following table ``` ID location date -- -------- ----- 01 loc#1 10-06-2014 05 loc#1 11-06-2014 06 loc#2 13-06-2014 08 loc#2 14-06-2014 10 loc#2 15-06-2014 14 loc#1 16-06-2014 17 loc#1 17-06-2014 20 loc#1 18-06-2014 ``` what i need is to get each location and the number of ...
``` select minAdjLoc.ID, max(minAdjLoc.location) 'Loc', count(distinct adjLocs.ID) 'Count' from test minAdjLoc -- Minimum record in each adjacent group inner join test adjLocs -- All adjacent record, including self on adjLocs.location = minAdjLoc.location and adjLocs.ID >= minAdjLoc.ID le...
I think this can work ``` SELECT location, COUNT(*) FROM (SELECT CASE WHEN t1.location <> (SELECT location FROM t WHERE id = (SELECT MAX(id) FROM t WHERE id < t1.id)) THEN t1.id WHEN (SELECT MIN(id) FROM t WHERE id > (SELECT MAX(id) FROM t WHERE location <> t1.location AND id ...
Count adjacent records in sqlite
[ "", "sql", "sqlite", "" ]
``` SELECT SUM( IF( userId = '123456', amount, 0 ) ) AS 'amount' FROM `amountInfo` ``` userId `123456` is not present in table `amountInfo`, in that case it is returning null i want 0(numerical)
You can use coalesce for this **UPDATE** : I was missing the argument to set 0 instead of NULL, pointed by @Barmar ``` coalesce( SUM( IF( userId = '123456', amount, 0 ) ),0 ) ```
Use IFNULL: ``` SELECT IFNULL(SUM(IF(userId = '123456', amount, 0)), 0) AS amount ```
return a SUM zero(0) instead of null
[ "", "mysql", "sql", "sum", "" ]
I want to calculate the time difference between two dates in Oracle sql query. I have written the following query: ``` DECLARE v_time varchar2(40); diff_hours varchar2(40); BEGIN select substr(((select date_time from observation_measurement where observation_measurement_id=2861971)), 1,17) into v_time from dua...
Increasing the size of diff\_hours variable working. Thanks Krishna. :-)
Make `diff_hours` a `NUMBER`variable instead of a `VARCHAR2` variable! Of course you can make `diff_hours` long enough to hold all the insignificant decimals your query produces, but declaring it `VARCHAR2` is pointless anyway!
ORA-06502: PL/SQL: numeric or value error: character string buffer too small in Oracle sql query
[ "", "sql", "oracle", "date", "difference", "" ]
Is there any possibility to write delete query inside **Where clause**. Example: ``` Select ID,Name From MyTable Where ID IN(Delete From MyTable) ``` It may be crazy, but let me explain my situation. In our reporting tool, we are supporting to enter SQL where query. We will use our own **Select** and **From** **Clau...
Yes. They can run a delete. They can type: ``` 1 = 1; DELETE FROM MY_TABLE; ``` Or even worse in some ways, (since you should have backups): ``` 1 = 0 UNION SELECT SOCIAL_SECURITY_NUMBER, CREDIT_CARD_NUMBER, OTHER_SENSITIVE_DATA FROM MY_SENSITIVE_TABLE; ``` Now, in your case its hard to validate. Normally if you a...
It's not quite possible. But he can do something like this : ``` Select ID,Name From MyTable Where (ID=100); (DELETE FROM MyTable Where 1 = 1) ``` by using `ID=100); (DELETE FROM MyTable Where 1 = 1` instead of `ID=100`
Delete Query inside Where clause
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have two tables. ``` |Table One: Adversitements-----------------------| | ID | ADVTITLE | |----|-------------------------------------------| | 1 | IT Staff will be taken. | | 2 | Human resources personnel will be taken. | | 3 | CNC Operator will be...
You missed the `GROUP BY` clause: ``` SELECT adv.advtitle, COUNT(applications.id) as applicantCount FROM advertisements as adv LEFT JOIN applications ON adv.id = applications.advid GROUP BY adv.advtitle ORDER BY applicantCount desc ``` Result: ``` ADVTITLE APPLICANTCOUNT ----------...
You need `GROUP BY` clause ``` SELECT adv.advtitle, COUNT(applications.id) as applicantCount FROM advertisements as adv LEFT JOIN applications ON adv.id = applications.advid GROUP BY applications.advid ``` `SQL Fiddle`
Left join with count return one result
[ "", "mysql", "sql", "left-join", "" ]
this is my scenario... i would like to check if the member has mobile in one table, if yes then to display his mobile.. else to check if he has landline phone from another table... if yes then to display landline... else blank. not sure if we can use case statement on comparing two different fields ``` SELECT a.name a...
If `mobile` is an empty string, it is `not null`, so this condition matches all those records where `a.mobile` is an empty string. So my guess is, none of your empty fields are `null`. Change the condition to: ``` when a.mobile is not null AND a.mobile<>'' then ``` Maybe even better: make the field not nullable, so ...
``` SELECT a.name as name, b.name as parent_name, a.mobile, b.phone, case when a.mobile is not null or a.mobile<>'' then a.mobile else (CASE when b.phone is not NULL or b.phone<>'' then b.phone else '') end as phone FROM family_member a join family_header b where a.name='sam' and a.id...
case statements with two conditions of two different fields
[ "", "mysql", "sql", "" ]
**System background:** Coding in VBA using MS-Access 2010. Currently working on code behind module and calling stored procedure. The stored procedure is written in SQL and run on the Ms-SQL server 2008 application where the database is stored. **Stored Procedure:** The stored procedure's purpose is to: * Retrieve thr...
Check that your your parameter is marked with OUTPUT keyword in your stored procedure Try to specify adParamReturnValue for your output parameter ``` cmd.CreateParameter("@testid", adDouble, adParamOutput, , adParamReturnValue) ``` Then once you called the store procedure with cmd.Execute you have to read the value ...
I'm pretty new to SQL, but where's your return? <http://msdn.microsoft.com/en-us/library/ms188655.aspx>
Output parameter from Stored Procedure only returning zero
[ "", "sql", "sql-server", "stored-procedures", "ms-access-2010", "" ]
I'm creating a NACHA file and if the number of records in the file is not a multiple of 10, we need to insert enough "dummy" records filled with nines (`replicate('9',94)`) to hit that next tens place. I know that I could write a loop or perhaps fill a temp table with 10 records full of nines and select the top N. But...
The formula `(10-COUNT(*)%10)%10` tells you how many rows to add, so you can just select that many dummy rows from an existing dummy table. ``` SELECT nacha_rows FROM NACHA_TABLE UNION ALL SELECT TOP (SELECT (10-COUNT(*)%10)%10 FROM NACHA_TABLE) REPLICATE('9',94) FROM master.dbo.spt_values ```
One idea is to prepare 9 filler rows than append only the ones needed to reach the next tens, same idea of JChao, with a different implementation ``` With Filler AS ( SELECT n.n, replicate('9',94) nacha_rows FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9)) n(n) ) SELECT nacha_rows FROM NACHA_TABLE UNION...
How to return N records in a SELECT statement without a table
[ "", "sql", "sql-server", "" ]
I have 2 tables: Departments and Sales. In my department table I have a labor department id and the id of the sales department it is associated to. I also want to allow a department's sales to "rollup" up to another department. I need help with the query to "rollup" the sales. Here are the tables: ``` TABLE = Departm...
``` select s.[Date], coalesce(d2.LaborDeptid,d1.LaborDeptid) [LaborDept], sum(s.Sales) [TotalSales] from Sales s join Departments d1 on s.SalesDept = d1.AssociatedSalesDept left join Departments d2 on d1.RollUpTo = d2.LaborDeptid group by s.[Date], coalesce(d2.LaborDeptid,d1.LaborDeptid) ```
I had to think about this one a bit, but here is one solution: ``` WITH cte AS ( SELECT CASE WHEN RollUpTo = 0 THEN LaborDeptId ELSE RollUpTo END AS LaborDeptId, AssociatedSalesDept FROM departments) SELECT s.date, d.LaborDeptid, SUM(s.Sales) AS TotalSales FROM Sales s INNER JOIN cte d ON s.SalesDept = d.AssociatedS...
sum with conditional grouping
[ "", "sql", "sql-server", "group-by", "sql-server-2008-r2", "sum", "" ]
I am having trouble with a query I need to write. For some reason I cant seem to get anything to work. I know the solution is very simple but I just can't seem to think of it. Lets say I have a table in my DB called "entrys" that looks like this: ``` ID | Item | value ------------------------------ 1 | item 1 ...
Try using a derived table where your items are named either `Item1` or `Other`. Then group the derived table by name and select the count. ``` SELECT Item, COUNT(*) FROM ( SELECT (CASE WHEN Item = 'item 1' THEN 'Item 1' ELSE 'Other' END) Item FROM items WHERE value = 3) t1...
The key to the aggregation is a `case` statement. Then you need to count the appropriate values as well. In MySQL, you can do: ``` SELECT (CASE WHEN Item = 'item 1' THEN Item ELSE 'Other' END) AS Item, COUNT(*) AS `Count3` FROM entrys e WHERE value = 3 GROUP BY Item; ``` MySQL allows the use of column aliases in the ...
SQL count records equal to 1 value and count and group the rest
[ "", "mysql", "sql", "database", "count", "group-by", "" ]
I have 2 tables: AllClients & AllPolicies. I'm trying to find Client Records where there are no "active policies". An active policy is a policy where the effective date is before today and the expiration date is after today. Here is the sql I've come up with but it won't execute: ``` SELECT ac.LookupCode FROM AllCli...
``` SELECT LookupCode FROM AllClients where LookupCode not in (select LookupCode from AllPolicies where EffectiveDate < '2014-06-24' and ExpirationDate > '2014-06-24') ```
This might help. You haven't expounded much on your mySQL errors, and they might have something to do with your table structures or server setup. ``` SELECT ac.LookupCode FROM AllClients ac LEFT JOIN AllPolicies ap ON ap.LookupCode = ac.LookupCode AND ap.EffectiveDate < @Today AND ap.ExpirationDate > @Today WHE...
SQL Left Join 2 Tables where Condition
[ "", "mysql", "sql", "join", "left-join", "" ]
If you have a query like: ``` INSERT INTO insert_table SELECT * FROM from_table WHERE NOT EXISTS ( SELECT * FROM from_table WHERE insert_table.column = from_table.column ); ``` Is that subquery evaluated for each row only at the initial `SELECT FROM from_table`? My `inser...
The `where` clause is evaluated for each row in the table derived in the `from` clause. If you need distinct keys use `distinct on` ``` insert into insert_table select distinct on (key1, key2) * from from_table where not exists ( select ... ) order by key1, key2, another_column ``` <http://www.postgresql.or...
The subquery **is** executed for each row. However, it's operating on a snapshot of the database, as it was at the beginning of the statement, so it won't see its own inserts. A simpler example to illustrate this is: ``` INSERT INTO some_table SELECT * FROM some_table; ``` This will duplicate the contents of `some_t...
How many times is where clause evaluated in INSERT ... SELECT?
[ "", "sql", "postgresql", "" ]
I've never done an inner join SQL statement before, so I don't even know if this is the right thing to use, but here's my situation. Table 1 Columns: id, course\_id, unit, lesson Table 2 Columns: id, course\_id Ultimately, I want to count the number of `id's` in each unit in Table 1 **that are also in Table 2**. So,...
``` SELECT unit, COUNT( t1.id ) as count FROM table1 as t1 inner JOIN table2 as t2 ON t1.id = t2.id GROUP BY unit ``` hope this helps.
If I understand what you want (maybe you could post an example input and output?): ``` SELECT unit, COUNT( id ) as count FROM table1 as t1 JOIN table2 as t2 ON t1.id = t2.id GROUP BY unit ```
Inner Join SQL Syntax
[ "", "mysql", "sql", "join", "" ]
I am trying to write a script that will show the number of non-null values in each column as well as the total number of rows in the table. I have found a couple ways to do this: ``` SELECT sum(case my_column when null then 1 else 0) "Null Values", sum(case my_column when null then 0 else 1) "Non-Null Values" FROM...
As Paolo said, but here is an example: ``` DECLARE @TableName VARCHAR(512) = 'invoiceTbl'; DECLARE @SQL VARCHAR(1024); WITH SQLText AS ( SELECT ROW_NUMBER() OVER (ORDER BY c.Name) AS RowNum, 'SELECT ''' + c.name + ''', SUM(CASE WHEN ' + c.Name + ' IS NULL THEN 1 ELSE 0 END) AS NullValues FROM ' + ...
You should use `execute`: ``` DECLARE @t nvarchar(max) SET @t = N'SELECT ' SELECT @t = @t + 'sum(case when ' + c.name + ' is null then 1 else 0 end) "Null Values for ' + c.name + '", sum(case when ' + c.name + ' is null then 0 else 1 end) "Non-Null Values for ' + c.name + '",' FROM sys.columns c WHER...
Count number of NULL values in each column in SQL
[ "", "sql", "sql-server", "" ]
SELECT ``` @begindate = dateadd(mm,-1,CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/15/' + CAST(datepart(YYYY,getdate() -1) AS varchar(4))), @enddate = CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/14/' + CAST(datepart(YYYY,getdate() -1) AS varchar(4)) ``` Right now this code returns the dates May...
If DateAdd didn't work, there must have been an error in your implementation. Try it like this after your existing code: ``` SET @begindate = dateadd(year, -1, @begindate); SET @enddate = dateadd(year, -1, @enddate) ```
declare @begindate datetime declare @enddate datetime set @begindate = dateadd(mm,-1,CAST(datepart(mm,getdate()) AS VARCHAR(2)) + '/15/' + CAST(datepart(YYYY, getdate()) - 1 AS varchar(4))) set @enddate = CAST(datepart(mm,getdate() ) AS VARCHAR(2)) + '/14/' + CAST(datepart(YYYY, getdate()) - 1 AS varchar(4)) select ...
Subtracting One Year
[ "", "sql", "date", "dateadd", "" ]
(I've looked it up and couldn't find an answer, If this is a duplicate, just point out a link and I'll delete this question) Let's say I have the following code ``` select CASE WHEN lower(Http_User_Agent) like '%mobi%' then 'Mobile' else 'Desktop' end as Device from Http_User_Agent where Device = 'Mobile...
At the time of execution of the query, the `Device` alias isn't yet assigned to the resultset. So you need to either do this: ``` SELECT CASE WHEN LOWER(Http_User_Agent) LIKE '%mobi%' THEN 'Mobile' ELSE 'Desktop' END AS Device FROM Http_User_Agent WHERE CASE WHEN LOWER(Http_User_Agent) LIKE '%mobi%' THEN '...
You can do this with a subquery: ``` select ua.* from (select ua.*, (CASE WHEN lower(Http_User_Agent) like '%mobi%' then 'Mobile' else 'Desktop' end) as Device from Http_User_Agent ua ) ua where Device = 'Mobile'; ``` Or by repeating the condition: ``` select ...
Filtering based on a newly created column
[ "", "sql", "t-sql", "" ]
I have a table with: id, client, domain and bytes. I have a query that gets the top 3 users either by client: ``` SELECT client FROM log GROUP BY 1 ORDER BY SUM(bytes) DESC LIMIT 3 ``` or by domain ``` SELECT domain FROM log GROUP BY 1 ORDER BY SUM(bytes) DESC LIMIT 3 ``` Is there a way in MySQL to get this two mix...
One solution: <http://sqlfiddle.com/#!2/cc1b1/2/0> ``` SELECT client , (SELECT domain FROM log WHERE client=top_clients.client GROUP BY client, domain ORDER BY SUM(bytes) DESC LIMIT 1) domain1 , (SELECT domain FROM log WHERE client=top_clients.client GROUP BY client...
Here it is: ``` select client, substring_index(group_concat(domain order by sumbytes desc), ',', 5) as top5domains from ( select client, domain, sum(bytes) as sumbytes from log group by client, domain ) cd group by client order by sum(sumbytes) desc limit 5; ``` Courtesy of @Gordon Linoff here: [MySQL GROUP\_CO...
MySQL intertwine two queries based on previous query result
[ "", "mysql", "sql", "" ]
I have a table MY\_TABLE in oracle with a Spatial index MY\_IDX and about 22000 rows. The following query runs in less than ~500 ms and returns ~2600 results. ``` SELECT /*+ INDEX (MY_TABLE MY_IDX) */ ID,GEOM,LABEL FROM MY_TABLE where ( (sdo_filter(GEOM, mdsys.sdo_geometry(2003,8307,NULL, mdsys.sdo_elem_info_array(...
Refractoring the query using an inner query and a union all seemed to force oracle to use the indexes as expected: ``` SELECT ID,GEOM,LABEL FROM MY_TABLE WHERE ID IN ( (SELECT ID FROM MY_TABLE WHERE sdo_filter(GEOM, mdsys.sdo_geometry(2003,8307,NULL, mdsys.sdo_elem_info_array(1,1003,3), mdsys.sdo_ordinate_array(-...
"*On a side note, a different db running oracle enterprise edition produces a plan in which the index is used and the results merged. Can this be done with standard edition?*" To complete the answer: Enterprise Edition supports bitmap indexing techniques. Often when the optimizer has a choice between using multiple in...
Can Oracle be forced to use the spatial index for sdo_filter in combination with an or clause?
[ "", "sql", "oracle", "oracle-spatial", "" ]
Basically, ``` id status timestamp 1 Good 0 2 Good 1 1 Bad 2 ``` I want to have ``` id status timestamp 2 Good 1 1 Bad 2 ``` returned to me. This is because I want to know the most recent status of all the ids in the ta...
Try this .. Join is much faster than sub query. ``` select t1.* From Table t1 LEFT JOIN Table t2 on t2.id=t1.id and t2.timestamp > t1.timestamp where t2.id IS NULL. ```
``` select t1.id, t1.status, t1.timestamp from my_tbl as t1 where t1.timestamp = (select max(timestamp) from my_table t2 where t1.id = t2.id) ``` This will however return ids twice which have the same highest timestamp.
MySQL select all rows from table with distinct ID using newest timestamp
[ "", "mysql", "sql", "" ]
I have a query say `SELECT name,number FROM TABLE WHERE number='123'` What I want is to display multiple records using where clause or any other way so that I can get following data. **Name Number** `ABC 123 PQR 127 PQR 130` I tried using `AND` `&&` `,` in where clause.i.e. `where number=123,127,130` or `where num...
just use an `IN` clause ``` where number in (123, 127, 130) ``` you could also use OR (just for info, I wouldn't use this in that case) ``` where number = 123 or number = 127 or number = 130 ``` Don't forget round braces around the "ors" if you have other conditions in your where clause.
Try this ``` SELECT name,number FROM TABLE WHERE number IN (123,127,130); ``` OR ``` SELECT name,number FROM TABLE WHERE number = 123 OR number = 127 OR number = 130; ```
SQL Where Clause with multiple values
[ "", "mysql", "sql", "" ]
I have 3 tables as you can see: ![enter image description here](https://i.stack.imgur.com/eWR4c.png) The relationships between all 3 tables: * `cal_events.id = cf_cal_events.model_id` * `cf_cal_events.col_10 = source.ID_ELEMENT` I want to delete data from `cal_events` and `cf_cal_events` if `ASUPPRIMER = '1'` I kno...
There's a good example for your problem: [How to Delete using INNER JOIN with SQL Server?](https://stackoverflow.com/questions/16481379/how-to-delete-using-inner-join-with-sql-server) seems to me like it should be: ``` DELETE cal_events, cf_cal_events FROM cal_events INNER JOIN cf_cal_events ON cal_events.id = cf_cal...
Find `multi table syntax` from the [docs](http://dev.mysql.com/doc/refman/5.6/en/delete.html). Something like this ``` DELETE cal_events, cf_cal_events FROM cal_events JOIN cf_cal_events ON cal_events.id = cf_cal_events.model_id JOIN source ON cf_cal_events.col_10 = source.ID_ELEMENT WHERE sour...
DELETE - INNER JOIN - Sub Query
[ "", "mysql", "sql", "inner-join", "delete-row", "" ]
I have my new website which manage by private company. This morning I accidently put Double Quote in url (") and become error as below: URL: `http://domain.com/sys.aspx?page=5&search=1"` ``` Server Error in '/' Application. Syntax error near '"' in the full-text search condition '1"'. Description: An unhandled exc...
> I just call them and they tell me 'we use mysql'. Is that correct? It's possible they use both MySQL and SQL Server at their site. Not likely -- but *possible*. I think it's more likely that they simply made a mistake. I have heard a few IT people say "MySQL" when they actually use Microsoft SQL Server. The error ...
It is Microsoft SQL Client Talking to MS SQL server Yes you have proven SQL injection, into the FULL TEXT search expression, not the SQL statement - that is probably just as bad but I can not say.
What kind of Database is this and could be sql injection?
[ "", "sql", "sql-injection", "" ]
I have an SQL function retuning a composite result. ``` CREATE TYPE result_t AS (a int, b int, c int, d numeric); CREATE OR REPLACE FUNCTION slow_function(int) RETURNS result_t AS $$ -- just some placeholder code to make it slow SELECT 0, 0, 0, ( SELECT sum(ln(i::numeric)) FROM generate_series...
A CTE is not even necessary. A **plain subquery** does the job. ``` SELECT i, (f).* -- decompose here FROM ( SELECT i, (slow_func(i)) AS f -- do not decompose here FROM generate_series(1, 3) i ) sub; ``` Be sure not to decompose the record (composite result) of the function in the s...
Perhaps a LATERAL subquery is what you want. ``` SELECT t.id, f.* FROM some_table t, LATERAL (SELECT slow_func(t.id)) f ``` That will call the function once for each row, and then "unwrap" the result into columns in the output. Any subquery will do for the "unwrapping" but LATERAL is what lets you reference columns f...
Avoid multiple calls on same function when expanding composite result
[ "", "sql", "postgresql", "query-optimization", "plpgsql", "" ]
I'm trying to format a column that is timestamp with time zone using to\_char since i don't want to include the zone part of the column, but the difference between a query running to\_char and without it is like 10 seconds that is a lot of time, i don't have much experience with databases and maybe i'm doing something ...
Just wrap the fast query with one with the desired format ``` select to_char("Timestamp",'YYYY/MM/DD HH24:MI:SS') as "Timestamp", "TotalParticlesAccum", "BioAccumulated", "FlowVolume", "DCOffsetCh0", "DCOffsetCh1", "DCOffsetCh2", "LaserPower", "LaserCurrent", "LaserTemperature", "LaserRunHour", ...
my suggestion is use the raw field for the grouping and ordering but format it the way you want in the select clause: ``` SELECT DISTINCT ON ("Timestamp") to_char("Results"."Timestamp", 'YYYY/MM/DD HH24:MI:SS') ,"TotalParticlesAccum" ,"BioAccumulated" ,"FlowVolume" ,"DCOffsetCh0" ,"DCOffsetCh1"...
Postgresql to_char slowing query a by a lot
[ "", "sql", "postgresql", "" ]
a mysql database i'm working with has thousands of urls. now, a lot of those urls will be from the same domain, but each one will have differing sub-domains and page names. e.g. ``` somewebsite.com/gj29sjw somewebsite.com/29shw0a somewebsite.com/92jslwa anothersite.net/jfdkden anothersite.net/hj2892j another...
You could use [`SUBSTRING_INDEX`](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index) to make the query fairly simple; just take the 2 last period separated groups before the first slash; ``` SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(url, '/', 1), '.', -2) site, COUNT(*) cnt FROM mytabl...
``` select substr(url, 1, instr(url, '/') - 1) as domain_name, count(*) as cnt from your_table group by domain_name order by cnt desc ``` [SQLFiddle demo](http://sqlfiddle.com/#!2/d41d8/39757)
sorting large amounts of urls by top domain in mysql
[ "", "mysql", "sql", "sorting", "url", "count", "" ]
I have a table with several rows of data like this : ``` 16 W:\2-Work\ALBO\00_Proposal\ALxO_Amendement #1_20091022_signed.pdf 17 W:\2-Work\ALBO\00_Proposal\Level1\ALBO_Amendment #1_20110418.docx 18 W:\2-Work\ALBO\00_Proposal\A\BR\T\X_#1_20110418_final.docx 19 W:\2-Work\ALBO\MyOptionl\AO_Amendment_2 August 2013.doc...
As others have said, this probably isn't the best way to do things, if you explain what you'll be doing with the results it might help us provide a better option [Also, for some reason the colours of the code below are showing up odd, so copy and paste it into your Sql server to see it better] ``` drop table #Path c...
One way (de-dupes): ``` ;with T(ordinal, path, starts, pos) as ( select 1, path, 1, charindex('\', path) from #tbl union all select ordinal + 1, path, pos + 1, charindex('\', path, pos + 1) from t where pos > 0 ) select [1],[2],[3],[4],[5],[6],[7],[8],[9],[10] from ( select ordinal, path, ...
Split string in column and add value in column
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I don't exactly know how to phrase the question, but an example would work. So I have this table ``` Users Id Name 1 Tim 2 Jon 3 Matt ``` There is another table ``` Tags TagId TagName 1 Test 2 Other 3 Dummy 4 More ``` In a temp t...
I think the simplest way would be to just join the tags column using `LIKE`: ``` CREATE TABLE #Users (ID INT, Name VARCHAR(4)); INSERT #Users (ID, Name) VALUES (1, 'Tim'), (2, 'Jon'), (3, 'Matt'); CREATE TABLE #Tags (TagID INT, TagName VARCHAR(5)); INSERT #Tags (TagID, TagName) VALUES (1, 'Test'), (2, 'Other'), (3, '...
To me the main question would be how you arrived at the temp table containing the comma delimited column. If it was an import from a file and all the data was comma delimited it would be easy enough to save the file as a csv which will save the user and each tag separately, then create a table in the your database cont...
How to insert multiple values in SQL Server table?
[ "", "sql", "sql-server", "insert", "" ]
**What's faster?** ``` update c set c.createdon=q.CreatedOn ,c.createdby=case when q.createdby is not null then q.createdby end ,c.modifiedon=q.modifiedon ,c.modifiedby=case when q.ModifiedBy is not null then q.ModifiedBy end from crm_annotationbase c join IncidentWorknote q on c.annotationid=q.annotationid ``` **...
Ok.. I had to dig around for this script. From reading the comments, it's a very large table that you are trying to update. The BEST way to speed this update up is to break it into batches. The reason it's taking so long is because of the transactional nature of the system... If something fails, the ENTIRE transaction ...
What you are doing is wrong for two reasons: 1. Direct updates to a Dynamics CRM database is highly unsupported and can lead to several issues with your CRM instance (you need to use CRM Web Services to update the data) 2. `CreatedOn`, `CreatedBy`, `ModifiedOn` and `ModifiedBy` are system fields and they are always fi...
performance of isnull vs select case statement
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "dynamics-crm-2013", "" ]
I have a table called `Leaves` which has `Employee ID`, `Leave Type` and `Date`. For example, If an employee with ID = 1234 applies for a sick leave from 1-June-2014 to 5-June-2014, this will be stored in Leave tables day by day, means that the following records will be added: 1234 sick leave 1-June-2014 1234 sick leav...
This design is a bit strange, because of these daily rows, if the same person will have several escort leaves, then you have to figure out different cases. For this certain case you can use something like this ``` SELECT COUNT(*), leavetype FROM ( SELECT leavetype FROM Leaves GROUP BY employee_id, leavetype ) ...
Perhaps you can try this: ``` select leave_type, count(*) from ( select employee_id, leave_type from leaves where date between ... group by employee_id, leave_type) t group by leave_type; ```
Count number of cases
[ "", "sql", "postgresql", "" ]
I have to check for a value of a particular Column named `RESULT` is blank or not. When I check with `if RESULT IS NULL`, the query failed, but When I checked `RESULT=''`, it worked. What is difference between two. please explain. ``` "UPDATE RLS_TP_2012_03 a, RLS_TP_2012_03 b SET a.COMMENT=b.COMMENT where b.TCODE=...
1. `NULL` is an absence of a value. An empty string is a value, but is just empty. `NULL` is special to a database. 2. `NULL` has no bounds, it can be used for `string`, `integer`, `date`, etc. fields in a database. 3. `NULL` isn't allocated any memory, the `string` with `NULL` value is just a pointer which is pointing...
In tri-value logic, NULL should be used to represent "unknown" or "not applicable" An empty column should represent "known but empty". Some DBMS products don't follow this convention all the time but I consider them deficient. Yes, you know who you are, Oracle :-) In addition, while NULL can be put into any column ty...
Difference between NULL and Blank Value in Mysql
[ "", "mysql", "sql", "" ]
I have a log table which records the run history of various background jobs. Now I need to display the most recent run of each and every job along with some data. Here is my solution: ``` SELECT BackgroundJobId, bjl.LogId, ExecStartTime, ExecEndTime, ErrorDescription, Debug FROM BackgroundJobLog bjl JOIN ( SELEC...
For this query to work fast, you need two things: * A list of distinct `BackgroundJobId` * A composite index on `BackgroundJobLog (BackgroundJobId, ExecStartTime) INCLUDE (BackgroundJobStatusId)` If you have a separate table with jobs, just use it: ``` SELECT bl.* FROM job CROSS APPLY ( SELECT T...
I didn't see that the JOIN is necessary. ``` ;WITH CTE AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY BackgroundJobId ORDER BY ExecStartTime DESC) rn FROM BackgroundJobLog WHERE BackgroundJobStatusId IN (1, 3) ) SELECT BackgroundJobId , LogId , ExecStartTime , ExecEndTime , E...
Using the MAX aggregation window function correctly in SQL Server 2012
[ "", "sql", "sql-server", "" ]
This is rather silly, but i really don't know what's the problem here. I have a table 'profiles' which a column 'country', i filled this table from a tab separated value file and the table view seems to be fine. Now when executing this query: ``` select * from profiles where country = 'Sweden' ``` Nothing gets retur...
Please try with like operator. select \* from profiles WHERE country LIKE '%Sweden%'
Try with [TRIM](http://www.w3resource.com/mysql/string-functions/mysql-trim-function.php) function if any leading or trailing space in country field ``` select * from profiles where TRIM(country) = 'Sweden' ``` OR ``` select * from profiles where TRIM(country) LIKE 'Sweden' ``` OR ``` select * from profiles where ...
Simple MySql select statement returns 0 rows
[ "", "mysql", "sql", "database", "" ]
I have this stored procedure: ``` CREATE PROCEDURE ListIds @ObjectiveId int, @SubjectId int, AS BEGIN SELECT Question.QuestionUId FROM Objective WHERE Objective.objectiveId = @ObjectiveId AND Objective.subjectId = @SubjectId END; ``` How can I make it so that if the stored procedure @Obje...
``` SELECT Question.QuestionUId FROM Objective WHERE (Objective.objectiveId = @ObjectiveId OR @ObjectiveId = 0) AND Objective.subjectId = @SubjectId ```
Try this: ``` CREATE PROCEDURE ListIds @ObjectiveId INT, @SubjectId INT AS BEGIN SELECT QuestionUId FROM Objective WHERE Objective.subjectId = @SubjectId AND (ISNULL(@ObjectiveId,0) = 0 OR Objective.objectiveId = @ObjectiveId) END; ```
How can I make it so a where clause with a value of 0 makes it not check the where in a SQL Server stored procedure?
[ "", "sql", "sql-server", "stored-procedures", "" ]
My goal is to avoid dead locks and so I centralized all locks in the same place ordering by table name and then by ID ascending: ``` SELECT * FROM table1 WHERE ID = 1 FOR UPDATE SELECT * FROM table1 WHERE ID = 2 FOR UPDATE SELECT * FROM table1 WHERE ID = 3 FOR UPDATE SELECT * FROM table1 WHERE ID = 4 FOR UPDATE SELEC...
Even though it's a little unclear but some part of the answer to your question is stated in the [MySQL's documentation](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in): > **expr IN (value,...)** > > Returns 1 if expr is equal to any of the values in the IN list, else > returns 0. *If all ...
Rows are locked in the order they are read, so no order is guaranteed. Even if you add an `ORDER BY` clause, the rows will be locked as they are read, not as they are ordered. [Here is another good question](https://stackoverflow.com/questions/5694658/how-many-rows-will-be-locked-by-select-order-by-xxx-limit-1-for-upda...
could a rows lock made with IN(,,,) generate dead locks?
[ "", "mysql", "sql", "locking", "innodb", "deadlock", "" ]
I have the following SQL Query ``` UPDATE ea SET ea.isholiday = 1 FROM employee_attendance ea JOIN setup_holiday h ON h.day = DATEPART(dd,ea.timestamp) AND h.month = DATEPART(mm,ea.timestamp) WHERE ea.isactive = 1 ``` I need to add other filter that is: ``` AND h.year = DATEPART(yyyy, ea.timestamp) ...
You use a case statement and a trick -- when you have the predicate you want to ignore you just put the right hand side (which will always be true) otherwise your predicate. Like this: ``` UPDATE ea SET ea.isholiday = 1 FROM employee_attendance ea JOIN setup_holiday h ON h.day = DATEPART(dd,ea.timestamp) AND h....
Just add the condition using `or`: ``` UPDATE ea SET ea.isholiday = 1 FROM employee_attendance ea JOIN setup_holiday h ON h.day = DATEPART(dd,ea.timestamp) AND h.month = DATEPART(mm,ea.timestamp) AND (h.year = DATEPART(yyyy, ea.timestamp) or h.year = 0) WHERE ea.isacti...
SQL conditional join or where statement
[ "", "sql", "sql-server", "" ]
I have a Data table in my Sql Database and I want to update some entries in that table on 1 day(regular) interval. How can I do it
You can try this with `Event Scheduler` in `SQL` ``` CREATE EVENT myevent ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR DO UPDATE myschema.mytable SET mycol = mycol + 1; ``` I hope this may be useful for you... Since i dont know your scenario..
If this job is in regular basis, try using [Scheduler Events](http://www.sitepoint.com/how-to-create-mysql-events/)
How To Update a Sql Table On Regular Interval
[ "", "mysql", "sql", "" ]
Regarding the example data below, it is `ORDER BY Type` but each resulting group is `ORDER BY MIN(Valu)` without any aggregation. ``` Type Valu ---- ---- B 12 B 88 B 200 B 200 A 56 A 100 A 100 C 70 C 70 ``` So all records of Type B are listed first because ...
Get All Types an their min values in a subquery and rejoin to table. Then you can order of Type-groups min Value. ``` SELECT table.Type, table.value FROM ( SELECT Type, min(value) AS minValue FROM table GROUP BY Type ) AS sub INNER JOIN table ON table.Type = sub.Type ORDER BY s...
You can try using *analytic functions* if your DBMS *supports* them (Oracle, MS SQL, Postgres...) ``` select Type, Valu from MyTable order by Min(Valu) over (partition by Type), Type, Valu ```
SQL ORDER BY but also by MIN of different col (aka threading)?
[ "", "mysql", "sql", "sorting", "sql-order-by", "" ]
> #1109 - Unknown table 'cal\_events\_' in field list I have a database groupofficecom, and I have two tables in it `cf_cal_events` and `cal_events_`: The primary key of `cal_events_` is the column `id` which is auto incremented The primary key of `cf_cal_events` is the column `model_id` which is **NOT** auto increm...
``` REPLACE INTO `cf_cal_events`(`model_id`) SELECT `id` FROM `cal_events_` ```
Remove table name `cal_events_` from fieldName and add `cal_events_` to `FROM` clause like this ``` REPLACE INTO `cf_cal_events`(`model_id`) SELECT `id` FROM `cal_events_`; ```
#1109 - Unknown table '...' in field list
[ "", "mysql", "sql", "" ]
I have finished all my changes to a database table in sql server management studio 2012, but now I have a large gap between some values due to editing. **Is there a way to keep my data, but re-assign all the ID's from 1 up to my last value?** I would like this cleaned up as I populate dropdownlists with these values a...
Yes, there are any number of ways to "close the gaps" in an auto generated sequence. You say you're new to SQL so I'll assume you're also new to relational concepts. Here is my advice to you: don't do it. The ID field is a surrogate key. There are several aspects of surrogates one must be mindful of when using them, b...
**You should refactor the code for your dropdown list and not the PK of the table.** If you do not agree, you can do one of the following: 1. Insert another column holding the dropdown's "order of appearance", make a unique index on it and fill this by hand (or programmatically). 2. Replace the SERIAL with an INT wou...
rebuild/refresh my table's PK list - gap in numbers
[ "", "sql", "sql-server", "primary-key", "" ]
I have the following query: ``` SELECT top 2500 * FROM table a LEFT JOIN table b ON a.employee_id = b.employee_id WHERE left(a.employee_rc,6) IN ( SELECT employeeID, access FROM accesslist WHERE employeeID = '#client.id#' ) ``` T...
Try using `exists` instead: ``` SELECT top 2500 * FROM table a LEFT JOIN table b ON a.employee_id = b.employee_id WHERE EXISTS (Select 1 FROM accesslist WHERE employeeID = '#client.id#' and a.employee_rc like concat(employeeID, '%') ...
Move the subquery to a JOIN: ``` SELECT TOP 2500 * FROM table a LEFT JOIN table b ON a.employee_id = b.employee_id LEFT JOIN accesslist al ON al.access LIKE concat('%', a.employee_id) WHERE al.employeeID = '#client.id#' ``` Like Gordon, I don't quite see how your query worked, so I'm not quite...
can I use a variable for the integer expression in a left sql function
[ "", "sql", "sql-server", "coldfusion", "" ]
I have a SQL Query (simplified from real use): ``` SELECT MIN(cola), colb FROM tbl GROUP BY colb; ``` But actually, I don't need the minimum value- any cola value will do- it's only used to show an example value from the group. At the moment PG has to do the group and then sort each group by cola to find the minimum...
I think using `DISTINCT ON()` with no order by will achieve what you are after: ``` SELECT DISTINCT ON (ColB) ColA, ColB FROM tbl; ``` **[Example on SQL Fiddle](http://sqlfiddle.com/#!15/63fe9/1)** The [docs state](http://www.postgresql.org/docs/9.0/static/sql-select.html) > DISTINCT ON ( expression [, ...] ) keeps...
This statement: > At the moment PG has to do the group and then sort each group by cola > to find the minimum value in the group, but this is slow because > there's a lot of records in each group. May logically describe what Postgres does, but it does not explain what is actually going on. Postgres -- as with any da...
Get ANY(col) instead of MIN(col) from a group
[ "", "sql", "postgresql", "optimization", "psql", "" ]
Hey guys am new to mysql development and am trying to inner join my both tables ..My code ``` SELECT Customers.name, oop.id FROM Customers(SELECT name,id FROM Orders) AS oop INNER JOIN oop ON Customers.name=oop.id ORDER BY Customers.name; ``` When i tried this code it shows me error i know this can be easily done wit...
You are writing a wrong syntax. it would be somthing like this:- ``` SELECT Customers.name, oop.id FROM Customers INNER JOIN (SELECT name,id FROM Orders) AS oop ON Customers.name=oop.id ORDER BY Customers.name; ```
You don't actually need the second select (although you can use it as Ankit Bajpai's answer shows). ``` SELECT Customers.name, oop.id FROM Customers INNER JOIN orders as oop ON Customers.name=oop.id ORDER BY Customers.name; ```
Inner join with mysql not works
[ "", "mysql", "sql", "" ]
I have a SELECT TOP query with an ORDER BY clause that does not return the correct result. Below is a sample query and its output. Any suggestion / workaround / solution ? Query: ``` CREATE TABLE #TestTop ( TopID INT, TopStr VARCHAR(MAX) ) INSERT INTO #TestTop VALUES(1749, ''); INSERT INTO #TestTop VALUES(1...
Try this, it works in sql server ``` SELECT TOP 4 * FROM #TestTop order by ROW_NUMBER() OVER(ORDER BY (CASE WHEN TopStr = '' THEN NULL ELSE TopStr END)) ``` OR ``` SET ROWCOUNT 4 SELECT * FROM #TestTop ORDER BY TopStr ASC SET ROWCOUNT 0 ```
You have not specified complete ordering, so the database (whichever one it is) is entitled to return rows that match on TopStr in any order it wants. Just because your first query happens to give the ordering you want is luck, and that could change based on a database upgrade / load on the system / many other factors....
SQL: SELECT TOP with ORDER BY clause does not return correct result
[ "", "sql", "sql-server", "" ]
There's a big discussion going on at my office on the order of the joined columns in a sql join. I'm finding it hard explaining it so I'll just present the two sql statements. Which one is better taking into account sql best practices? ``` SELECT a.Au_id FROM AUTHORS a INNER JOIN TITLEAUTHOR ta ON...
The best practice here is to choose one and stick with it **within the team**. Personally, I prefer the `FROM a JOIN b ON b.col = a.col` because it seems cleaner to me.
SQL was designed to be readable as usual English text. In a usual text, when we want to specify any mentioned object, we say something like "An object. This object is like that object, this object is related to that object, and this object has those properties." We do not say "That object is like this object, and that ...
Best practices for the order of joined columns in a sql join?
[ "", "sql", "" ]
I have a table of `beats` and for each beat there are multiple rows containing different prices in the `pricing` table. ``` SELECT b.id, b.name, (SELECT p.price FROM pricing as p WHERE p.license = 1 AND p.beat_id = b.id) as price_1, (SELECT p.price FROM pricing as p WHERE p.license = 2 AND p.beat_id = b.id) as price_2...
You can move that condition to a `having` clause. This is a feature of MySQL and not supported by other databases: ``` SELECT b.id, b.name, (SELECT p.price FROM pricing as p WHERE p.license = 1 AND p.beat_id = b.id) as price_1, (SELECT p.price FROM pricing as p WHERE p.license = 2 AND p.beat_id = b.id) a...
You can use a JOIN: ``` SELECT b.id, b.name, p1.price AS price_1, p2.price AS price_2 FROM beats AS b JOIN pricing AS p1 ON p1.beat_id = b.id JOIN pricing AS p2 ON p2.beat_id = b.id WHERE b.added > 0 AND b.active = 1 AND b.deleted = 0 AND p1.license = 1 AND p1.price > 0 AND p2.licence = 2 GROUP BY b.producer ORDER...
Result of nested SQL statements in WHERE clause
[ "", "mysql", "sql", "" ]
I have a stored procedure that searches across multiple columns in a combined table. It works, however, it takes 15 seconds to search for a value in that combined table. The table takes 9 seconds to load so I'm not sure, maybe it's because my table too big? So I'm just wondering if there's a way to make this query ru...
Any use of `like` precludes an index, unless it has a fixed prefix with a wildcard suffix, such as `where foo like 'bar%'`. Your `like` expressions (e.g., `'%xxx%'` ) do not meet that requirement. As a result, while the join criteria may well have a covering index, nothing else does and so a table scan of the join tab...
``` SELECT tblResources_NEW.ResourceID ,tblResources_NEW.ProjectFile ,tblResources_NEW.ResourceFile ,tblResources_NEW.ResourceName ,tblResourcesTranslated_NEW.Culture ,tblResourcesTranslated_NEW.TranslatedFlag ,tblResourcesTranslated_NEW.TranslatedValue ,tblResources_NEW.Comments ,tblRe...
How to make my search for multiple columns procedure more efficient?
[ "", "sql", "sql-server", "performance", "" ]
I have this table: ``` create table teams (team char(1) primary key, players text); insert into teams('A', 'Jhon'); insert into teams('B', 'Mark'); ``` Now, how do I add the player 'Carl' in team 'A'? The column 'players' maybe like a list?
You would do: ``` insert into teams('A', 'Carl'); ``` *after* you remove the primary key constraint. Actually, what you really want is: ``` create table TeamPlayers ( TeamPlayerId int auto_increment, team char(1), players text ); ``` Then you do the inserts that you want. This is a junction table (sort...
You have made team as primary key so you can't duplicate it. create some column id make it the primary key then you can add as many members as you want to team A
Add (not update) fields into column sql using insert
[ "", "mysql", "sql", "" ]
I have query as below: ``` select lower(convert(varchar(10), GETDATE(), 101) + ' '+ substring(convert(varchar(20), GETDATE(), 22),9,Len(GETDATE()))) ``` **In this query i am getting result as:** ``` 06/27/2014 6:23:57 pm ``` I just want to remove seconds (i.e. 57) from above. My intentded result is: ``` 0...
Try the below ``` SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/' +CAST(DATEPART(MM,GETDATE()) AS VARCHAR) +'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR) +' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR) +':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR) ``` also look at this [Custom Date/Time formatting in SQL Server](http...
Try this! ``` select lower(convert(varchar(10), GETDATE(), 101) + ' '+ LEFT((substring(convert(varchar(20), GETDATE(), 22),9,Len(GETDATE())+1)), 6) + (RIGHT(substring(convert(varchar(20), GETDATE(), 22),9,Len(GETDATE())+1),2))) ```
Remove seconds from datetime
[ "", "sql", "database", "sql-server-2008-r2", "" ]
I know I should try to avoid while loop in sql but I could not get it done, can someone please suggest a better way to achieve same result without using while loop. Here is my code - ``` begin transaction declare @count int; set @count = 1; declare @Id bigint; set @Id = 3781543256; while @count <=35000 begin INSE...
``` INSERT INTO [Table_name] ( [Column1] ,[Column2] ,[Column3] ,[Column4] ,[Column5] ) SELECT TOP 35000 7 ,@Id + ROW_NUMBER() OVER (ORDER BY objects1.object_id) ,'20130909 16:42:43.157' ,0 ,NEWID() FROM sys.objects AS objects1 CROSS JOIN sys.objects AS objects2 ```
You need a numbers table. It is handy to have around anyway. Assuming you have it, you can generate the set of rows you want to insert and do it in one go: ``` INSERT ... SELECT 7, Numbers.ID - 1 + 3781543256, ..., NEWID() FROM Numbers WHERE Numbers.ID BETWEEN 1 AND @count ``` Shorter, less error prone and faster. De...
How to avoid While Loop in Sql
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am a newbie for Oracle database programming and I wish to INSERT date (also display) in 'DD MON YYYY' format. (PS: This only involves INSERT event). Which data type (DATE or TIMESTAMP) is the most suitable option for me in order to accomplish this format? How was I supposed to do that? Thanks.
A `DATE` column does not have any format. So the format that you use when inserting or updating data is irrelevant for displaying that data (that's one of the reasons why you should never store a date in a `VARCHAR` column). Any formatted output you see for a `DATE` column in your SQL tool (e.g. SQL\*Plus) is applied...
To **insert** a record, ``` INSERT INTO TABLE_NAME (DATE_FIELD) VALUES (TO_DATE ('27-JUN-2014', 'DD-MON-YYYY'); ``` It is advisable to use DATE data-type until and unless you need the date's accuracy to be till milli seconds. In your case, go with DATE datatype and TIMESTAMP is not necessary To **select** a record, ...
How do I display DATE in 'DD MON YYYY' format?
[ "", "sql", "oracle", "" ]
I have a list of items which have states within date ranges, and some counts are coming up wrong (technically correct, but wrong in intent). I'm wondering if there's some examples of the date ranges not matching up closely on the datetimes I'm checking, or if the datetimes I'm querying on happen to fall into holes in ...
The other answer have some useful information, but here are some other thing to consider also: * If you're using a `datetime` type, then the values are *always* going to be rounded to increments of .000, .003, or .007, because that's it's precision. This is [in the documentation](http://msdn.microsoft.com/en-us/librar...
> I'd like a query to discover whether there is any overlap. At any given time, an item can only be in one state at a time, but I'd like to check whether there are some points where items have multiple states You could try something like the following to capture when the start/stop date of a status lands between the s...
How can I discover and compensate for possible flaws in the method of date storage?
[ "", "sql", "sql-server", "date", "datetime", "" ]
I'm trying to extract a number that follows an cardinal "#" from a String in sql server. Also I want to ignore all numbers that aren't attached to the "#" simbol. For that purpose I created something like this: ``` DECLARE @val nvarchar(50) SET @val = '#5777 some text' PRINT SUBSTRING(@val, PATINDEX('%#[0-9]%', @val...
A bit hacky, but it works for both of your scenarios (following text, no following text): ``` DECLARE @val nvarchar(50) SET @val = '#5777 some text' PRINT SUBSTRING(@val, PATINDEX('%#[0-9]%', @val) + 1, ISNULL(NULLIF((PATINDEX('%[^0-9]%', SUBSTRING(@val, PATINDEX('%#[0-9]%', @val) + 1, LEN(@val))) - 1),-1),100))...
``` DECLARE @val nvarchar(50) SET @val = '#5777 some text' PRINT REPLACE(@val, SUBSTRING(@val, PATINDEX('%[^a-zA-Z0-9 ]%', @val), 1), '') ```
Extract int from String on SQL Server
[ "", "sql", "sql-server", "" ]
I have this users: **NAME** **\_\_\_\_\_** **ROLE**\_\_\_\_\_\_\_\_\_**STATUS** user1 -------- role1 ---------------- true user2 -------- role2 ---------------- true user3 -------- role2 ---------------- false user4 -------- role3 ---------------- false user5 -------- role4 ---------------- true I have this quer...
What's wrong with the query is the lack of parentheses around the 'OR groups' ``` User.where("(role = ? OR role = ? OR role = ?) AND status = ?", "role1", "role2", "role3", true) ``` However, as already stated in another answer, it can be done in an easier way like this. ``` User.where(status: true).where(role: %w{r...
try this : ``` User.where(status: true).where(role: ["role1", "role2", "role3"]) ```
Rails MySQL query using where statement
[ "", "mysql", "sql", "ruby-on-rails", "" ]
I am using the following script to count the number of ShopId for one year. I need also to breakdown the result by month for a year. So end result should be ``` MONTH 1 SHOPID 5 100 SHOPID 4 90 MONTH 2 SHOPID 1 150 SHOPID 4 80 ``` --- ``` SELECT ShopId, Count(ShopId) as Interest ...
You can use **[DatePart](http://msdn.microsoft.com/en-us/library/ms174420.aspx)**. Try like this ``` SELECT DatePart(mm,datecreated) 'Month',ShopId, Count(ShopId) as Interest FROM dbo.Analytics WHERE year(DateCreated) = '2015' GROUP BY Datepart(mm,datecreated),ShopId ORDER BY Interest DESC ``` ...
Try this ``` SELECT datepart(mm,datecreated) 'Month',ShopId, Count(ShopId) as Interest FROM dbo.Analytics WHERE year(DateCreated) = '2014' GROUP BY datepart(mm,datecreated),ShopId ORDER BY Interest DESC ```
How to use GROUP with DATEPART?
[ "", "sql", "sql-server", "" ]
I have tables like following: **post:** ``` id status 1 0 2 1 3 1 ``` **comment:** ``` id post_id 1 2 2 1 3 3 4 2 ``` I want select posts where status=0 or post have comments. I made this query: ``` SELECT t.*, COUNT(cmt.id) as commentsCount FROM `post` `t` LEFT JOIN comment cmt ON (cmt....
You need to put this condition in a `having` clause: ``` SELECT t.*, COUNT(cmt.id) as commentsCount FROM `post` `t` LEFT JOIN comment cmt ON (cmt.post_id = t.id) WHERE t.status = '0' GROUP BY t.id HAVING commentsCount > 0; ``` EDIT: For the `or` logic, you can move both conditions to the `having` claus...
There is also more straightforward way to translate your query from English to SQL: ``` SELECT * FROM post WHERE status='0' or (select count(1) from comment where post_id = post.id) > 0 ``` I recommend you to check which query has better plan on your data (with join or with subquery). Anyway special field for filte...
COUNT of joined records in WHERE statement
[ "", "sql", "join", "count", "where-clause", "" ]
I am trying to convert a long date stored as text to a short date via MS Access SQL. For example I have a table which parsed information from a website and one of the field is Tuesday, June 17, 2014. I want to run an update query in another table which takes this value and converts it to 17/06/2014. Any help on what ...
Building on @VBlades' example, but allowing the year to be different from 2014, assuming that other years might appear in the source data. This will only work if the dates you wish to parse are formated consistently. Paste this function into a vba module and call it from your query. ``` Function dateParser(datestr A...
For date strings like "Tuesday, June 17, 2014" a VBA function like this ``` Option Compare Database Option Explicit Public Function ParseDateString(DateString As Variant) As Variant If IsNull(DateString) Then ParseDateString = Null Else ParseDateString = CDate(Split(DateString, ", ", 2)(1)) ...
Convert long date stored as text to short date Access SQL
[ "", "sql", "date", "ms-access", "" ]
I am facing a problem. I am not able to make a query which is a bit complicated but crucial for my work. I have a view which looks like this : ``` dpt | status 94 | OK 94 | Average 94 | Average 94 | Average 95 | OK 95 | NOK 95 | OK 96 | OK 96 | OK 96 | OK ``` I want a rule like: * If AT LEAST ...
You can do this with conditional aggregation. For your rules, this would look like: ``` select dpt, (case when sum(case when status = 'NOK' then 1 else 0 end) then 'NOK' when sum(case when status = 'Average' then 1 else 0 end) then 'Average' else 'OK' end) as Status from myview...
This is one way that you can get the result ``` SELECT DISTINCT ok.dpt, COALESCE(nok.status,avgTable.status,ok.status) AS Status FROM myTable AS ok LEFT JOIN (SELECT dpt,status FROM myTable WHERE status='Average' GROUP BY dpt,status HAVING COUNT(*)>=2) AS avgTable ON ok...
SQL Server Query with case
[ "", "sql", "sql-server", "case", "" ]
I am reading someone else sql and his code was like this There is view called `user_v` with column `path` as Array ``` select * from user_v where 'USER_TYPE'=path[2] ``` can't i use `path[2] = 'USER_TYPE'`
This is a precaution taken by some programmers in languages where assignment and comparison can be easily confused, such as C or PHP, where the following statement looks innocent: ``` if ( $foo = 1 ) ``` but it is actually *assigning* `1` to `$foo`, and the `if` will always evaluate to `true` (in PHP, at least, wher...
There is no difference at all.
What is the difference between keeping column on left of = in sql
[ "", "sql", "postgresql", "" ]
I am trying to get my head around using GROUP\_CONCAT within MYSQL. Basically I have the following table, table1: id, field1, field2, active I want to bring back 5 rows within the table but in random order. So I'm using this: ``` SELECT GROUP_CONCAT(id ORDER BY rand()) FROM table1 WHERE active=1 ``` This behaves a...
I think this is what you are looking for. This will bring back 5 random active rows. ``` SELECT * FROM table1 WHERE active=1 ORDER BY RAND() LIMIT 5; ```
why not use this : ``` SELECT *, GROUP_CONCAT(id ORDER BY rand()) as randoms FROM table1 WHERE active=1 ```
Using MYSQL GROUP_CONCAT with sub query
[ "", "mysql", "sql", "group-concat", "" ]
I have a SQL table that contains the following ``` ID AccountNumber Name 1 12345 Tony 2 123456 Mike 3 123458 Mike 4 45689 Tom 5 666999 Tim 6 6669997 Lisa 7 44455 Tim 8 78901 Matt 9...
The cases that you mention satisfy that the longer starts with the shorter. Here is a query that will get the shortest match for each account number: ``` select AccountNumber from (select a.*, count(*) over (partition by ShortestAN) as numAN from (select a.*, (select top 1 a2.AccountNumber ...
``` select a1.ID, a1.AccountNumber, a1.Name, a2.ID, a2.AccountNumber, a2.Name from Accounts a1 join Accounts a2 on LEN(a1.name) <= LEN(a2.name) and SUBSTRING(a2.name, 1, LEN(a1.name)) = a1.name where /*are not same rows*/ a1.ID <> a2.ID ```
Get values and like values in SQL
[ "", "sql", "sql-server-2008", "" ]
There are two tables Inspector(Parent) and InspectorOfficeAccess(Child), i need to give inspectors from country (73,74) to have access of offices (1,20,24,31,44). There are many inspectors (over 100) in Inspector table with country 73 and 74. Is this possible to insert all inspectors with officeid in InspectorOfficeAc...
If you have to pick Office Id's from other table then another way for doing this would be : ``` Insert into InspectorOfficeAccess Select I.InspectorID,O.OfficeId from Inspector I Cross Join Office O where I.CountryId in (73,74) and O.OfficeId in (1,20,24,31,44); ``` You can check [Demo here.](http://rextester.com/S...
Try this ``` Insert into InspectorOfficeAcess Select InspectorOfficeAccessiD,i.InspectorID,oficeid from Inspector i cross apply(Select 1 union Select 20 union Select 24 union Select 31 union Select 44) d where countryid in (73,74) ```
insert multiple rows (one to many) based on other table
[ "", "sql", "sql-server-2008", "" ]
I have two tables for Bill & Payment. I have show the balance sheet from these two tables. The Data in the tables are: **tblBill** ![enter image description here](https://i.stack.imgur.com/8zWUi.png) **tblPayment** ![enter image description here](https://i.stack.imgur.com/cunLh.png) My current output is: ![enter...
There you go: Assuming there is only one transaction in a day.... ``` With Tb1 as (select Date,Particulars,BillAmount,0'PaidAmount' from tblBill union select Date,Particulars,0'BillAmount',PaidAmount from tblPayment ) SELECT T1.Particulars,T1.[Date],T1.[BillAmount],T1.[PaidAmount],(Sum(T2.BillAmount) - Sum(T2.PaidAmo...
You will need to JOIN the two tables. First, there must be a link between the two tables (say customerid existing to show which customer is involved). Then, you can do. ``` CREATE VIEW vwTransactionHistory as SELECT customerid, Particulars, [DATE], BillAmount, PaidAmount, (SELECT SUM(BillAmount) FROM tblBill x ...
Cumulative sum across two tables
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Ive got a question which I am completely stumped on. It reads as follows: *Write a import stored procedure that take information from a table (source) and write it into another table (target).* Im guessing it would look something like the following: ``` create procedure add_data(@name, @surname) AS BEGIN SELECT nam...
You are almost there. Since you are directly copying from one table to another, you can use the `INSERT INTO ... SELECT ...` idiom, like so: ``` create procedure add_data @name varchar(100) @surname varchar(100) AS BEGIN INSERT INTO new_table(name,surname) SELECT name, surname FROM cardholder END ``` Note th...
It is not correct. try dis ``` create procedure add_data ( @name varchar(100), @surname varchar(100) ) AS BEGIN INSERT INTO target SELECT name, surname FROM cardholder end ```
procedure to take information from one table and write to another table
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a SQL table, that contains a column named `Foo`. I know how to get a row with the highest Foo value, with some SQL like this: ``` SELECT MAX(Foo) AS HighestFoo FROM Foos; ``` How can I get all the rows with the highest Foo?
Use a subquery: ``` SELECT * FROM Foos WHERE Foo = (SELECT MAX(Foo) AS HighestFoo FROM Foos) ``` The subquery (on the last line) selects out the highest value, and then uses that value to modify the WHERE clause.
``` With CTE As ( SELECT MAX(Foo) AS HighestFoo FROM Foos ) Select * From Foos Where Foo = ( Select HighestFoo From CTE) ```
How to get a group of the highest Foo's in a SQL table
[ "", "sql", "" ]
I am currently working in a project on a Oracle database. I have observed in the application code that dates are almost never used directly. Instead, they are always used in conjunction with the trunc function (TRUNC(SYSDATE), TRUNC(event\_date), etc.) Can anyone explain the reason behind using the trunc function inst...
A `DATE` in Oracle has not only a date part, but also a time part. This can lead to surprising results when querying data, e.g. the query ``` with v_data(pk, dt) as ( select 1, to_date('2014-06-25 09:00:00', 'YYYY-MM-DD hh24:mi:ss') from dual union all select 2, to_date('2014-06-26 09:00:00', 'YYYY-MM-DD hh24:mi:s...
You use the `trunc()` function to remove the time component of the date. By default, the `date` data type in Oracle stores both dates and times. The `trunc()` function also takes a format argument, so you can remove other components of the dates, not just the time. For instance, you can trunc to the nearest hour. Howe...
Reason for using trunc function on dates in Oracle
[ "", "sql", "oracle", "" ]
I have this column ``` NAME John Stephenson James Martin Anna Corelia ``` How I can select this column to this? ``` NAME Stephenson, John Martin, James Corelia, Anna ```
One way ``` ;with test(name) as ( select 'John Stephenson' union all select 'James Martin' union all select 'Anna J. Corelia' union all select 'BOBBYTABLES' ) select case when charindex(' ', name) = 0 then name else right(name, charindex(' ', reverse(name)) - 1) + ', ' + substring(name, 1, len(name) ...
Your question has nothing to do with `TRIM()` function. Probably you are trying to get something like below using `LEFT()` and `RIGHT()` function of `SQL Server` and concatanating them with `,` ``` select right('John Stephenson',(len('John Stephenson')-charindex(' ','John Stephenson'))) + ', ' + left('John Stephenson'...
How do I split and comma-delimit names?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I've imported about 600 pages into my WordPress database and most (not all) of them have the word "park" at the end of their new URL's ``` domain.com/awesome-park/ ``` I would like to bulk remove the word (and its previous dash - )change them via SQL query or other recommended method. Any advice for a safe way to cha...
The slug is stored in `wp_posts.post_name`. So the following should work (this from the first answer above): ``` UPDATE wp_posts SET post_name = REPLACE(post_name, '-park', '') WHERE post_name REGEXP '-park$'; ``` I do recommend backing up your WordPress database before running this query!
If you know the table and column where this url has been defined you could run next query: ``` UPDATE 'table_name' SET 'url_column' = REPLACE('url_column', '-page', ''); ```
Bulk remove a word from all WordPress URLs
[ "", "sql", "wordpress", "url", "" ]
Having 174 is there a way to convert it to show the complete date? example: 174 should be 06/23/2014, it is the 174th day of the year. my data looks like this 2014174. is there a SQL function for this? Thank you
You can use the dateadd function like below, to accomplish what you are looking for. ``` declare @inputNumber int set @inputNumber = 174 select dateadd(day,(@inputNumber-1),'1/1/'+cast (year(getdate())as varchar(10))) ```
``` DECLARE @DATEINT INT SET @DATEINT = 2014174 select DATEADD(YEAR, @DATEINT/1000-1900,DATEADD(day, @DATEINT%1000 - 1, 0)) ```
convert the number of the calendar day to date in SQL
[ "", "sql", "sql-server", "" ]
On SQL server 2008 R2, I would like to select one value of a column for each distinct value of another column. e.g. ``` name id_num Tom 53 Tom 60 Tom 27 Jane 16 Jane 16 Bill 97 Bill 83 ``` I need to get one id\_num for each distinct name, such as ``` name id_num Tom ...
``` SELECT name,MIN(id_num) FROM YourTable GROUP BY name ``` **UPDATE:** If you want pick id\_num randomly, you may try this ``` WITH cte AS ( SELECT name, id_num,rn = ROW_NUMBER() OVER (PARTITION BY name ORDER BY newid()) FROM YourTable ) SELECT * FROM cte WHERE rn = 1 ``` [SQL Fiddle Demo](http://sqlfid...
You could grab the max id like this: ``` SELECT name, MAX(id_num) FROM tablename GROUP BY name ``` That would get you one id for each distinct name.
SQL server 2008 R2, select one value of a column for each distinct value of another column
[ "", "sql", "sql-server", "sql-server-2008", "windows-7", "" ]
I'm currently working on a table in Oracle database where there are time values stored in AM/PM format. By default, the times are a VARCHAR2 datatype so I have been converting them using the to\_date function. What I'm doing is comparing two different times within the table and running a query which should return the ...
The biggest problem here is that as you add more data things will get slower and slower. It's difficult for an index to be efficiently used when you are calling a function on the field itself. It will have to scan the entire table to satisfy the query. There are three ways to avoid this: * Don't store dates or times a...
Not really. You'll need to add some logic for detecting a "loop" in your between criteria. If there is a loop (endRange < startRange), then the criteria should be: ``` to_char(to_date(TIME,'HH:MI:SS PM'),'HH24:MI:SS') >= '08:00:00' // endRange OR to_char(to_date(TIME,'HH:MI:SS PM'),'HH24:MI:SS') <= '04:00:00' // ...
Comparing clock times in SQL (Oracle)
[ "", "sql", "oracle", "date", "time", "" ]
Consider a data structure such as the below where the user has a small number of fixed settings. ### User ``` [Id] INT IDENTITY NOT NULL, [Name] NVARCHAR(MAX) NOT NULL, [Email] VNARCHAR(2034) NOT NULL ``` ### UserSettings ``` [SettingA], [SettingB], [SettingC] ``` Is it considered correct to move the user's settin...
You would normally split tables into two or more 1:1 related tables when the table gets very wide (i.e. has many columns). It is hard for programmers to have to deal with tables with too many columns. For big companies such tables can easily have more than 100 columns. So imagine a product table. There is a selling pr...
You're all wrong :) Just kidding. **On a high load, high volume, heavily updated system splitting a table by 1:1 helps optimize I/O.** For example, this way you can place heavily read columns *onto separate physical hard-drives* to speed-up parallel reads (the 1-1 tables have to be in different "filegroups" for this)...
SQL one to one relationship vs. single table
[ "", "sql", "database-design", "rdbms", "" ]
I have this table: ``` create table Student(name varchar(20), surname varchar(20), age int); ``` First, insert into table this fields: ``` insert into Student values ("Jhon", "Smith", null); insert into Student values ("Mark", "William", null); ``` Now, how do I insert age=28 where name = 'Jhon'??
You have to use [UPDATE](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAA&url=http%3A%2F%2Fdev.mysql.com%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&ei=uuirU8KPObPL0AWe5oGICA&usg=AFQjCNGVsZPXuo2367dgxMLfQjgy7VivQw&sig2=bvQnqF9s7LV2on5RzstNKg&bvm=bv.69837884,d.d2k) as below : ```...
`UPDATE Student SET age = 28 WHERE name = 'Jhon'` But please take care of your referetial integrity! Those data structure without any unique ID is not a safe way to store a great amount of data.
Command to insert into with select
[ "", "mysql", "sql", "" ]
I have one base table(id table) and multiple tables(data table) which have the data related to the id's and each table has different type data. I want to filter id's by multiple condition from these different table. I created query as follows, but this is too slow like 3 minutes. I checked explain information but stil...
Try this: Convert your left joins to a bunch of `WHERE EXISTS` sub-queries and drop the `GROUP BY`, because (that's my suspicion here) that's what you really wanted to express. ``` select jj.id, jj.imgtitle, jj.alias from jjtable jj -- you could drop this join, you don't do anything with jjtable_catg ...
One big improvement would be to use multiple conditions at joins instead of get a huge set and then put the condition at the end. I mean, if you put the condition at the same time you join your set will be smaller and your response time better: ``` select jj.id, jj.imgtitle, jj.alias from jjtable jj inner joi...
Very slow mysql query: left join multiple table and where clause for each table
[ "", "mysql", "sql", "" ]
I have an insert query I'm currently using in a stored procedure that works as it should. It is as follows: ``` insert into tblAgentRank (AgtID, RankType, Rank, TimeFrame, RankValue) select AgtID, 8, RANK() OVER (order by SUM(ColPrem*ModeValue) DESC) as Rank, 'Y', SUM(ColPrem*ModeValue) from tblAppsInfo where CompanyI...
I think this `select` statement does the calculation that you want: ``` select AgtID, 8, RANK() OVER (order by SUM(case when PolicyTypeID = 4 then ColPrem*ModeValue * 0.07 else ColPrem*ModeValue + ExcessPrem * 0.07 end) as RANK2, SU...
You just need to use a case statement inside the sum. ``` CASE WHEN PolicyTypeID = 4 THEN SUM(ColPrem*ModeValue) * 0.07 ELSE SUM((ColPrem*ModeValue) + (ExcessPrem * 0.07)) END ```
SQL RANK() Calculation
[ "", "sql", "sql-server-2005", "" ]
I am learning to use regular expressions and I'm using them to limit the results of a search query by using the REGEXP\_LIKE in Oracle 11. Placing an example of the data available, I have the following: ``` Plan navegación 200 MB Plan navegación 1 GB Plan navegación 1 GB Plan de navegacion 3G Plan de navegacion 4G Pla...
You could simply use LIKE, as below: ``` select * from mytable where PLAN_GSM LIKE 'Plan de navegacion _G%'; ``` or use REGEXP\_LIKE, as below: ``` select * from mytable where REGEXP_LIKE(PLAN_GSM, '^Plan de navegacion (3|4|5)G(*)'); ``` `SQL Fiddle demo` **Reference**: [Oracle/PLSQL: REGEXP\_LIKE Condition on Te...
You can use this: ``` SELECT * FROM mytable WHERE REGEXP_LIKE(mycolumn, '\APlan de navegacion \dG.*\z', 'c'); ``` * `\d` represents a digit * `\A` is the beginning of the string * `.*` greedily matches any characters * `\z` is the end of the string
Regular expression Oracle
[ "", "sql", "regex", "oracle", "" ]
I have two tables that look like: ``` table A: ID, target_date, target_ID table B: ID, target_ID, begin_date, end_date ``` Table B may have multiple records for the same target\_ID but different date ranges. I am interested in a SQL query that is able to return target\_dates that are not within the begin\_date and e...
There is a trick to this. Look for the ones that match, using a `left join`, and then choose the ones that don't match: ``` select a.* from tablea a left join tableb b on a.target_id = b.target_id and a.target_date between b.begin_date and b.end_date where b.target_id is null; ``` You can express th...
``` SELECT A.target_date FROM A LEFT OUTER JOIN B ON (A.target_ID=B.target_ID AND A.target_date>=B.begin_date AND A.target_date<=B.end_date) WHERE B.begin_date IS NULL ```
SQL: Selecting between dates
[ "", "sql", "database", "" ]
Im having issues making this query work. Can anyone help. I have two set of queries that I want to merge together. the first one is ``` SELECT 'Total Calls Hitting the Office' as "Report" ,Call_date as "Date" ,SUM([Calls) as "Total" ,'Calls' as "Units" FROM Call GROUP BY Call_date ``` and this query is g...
``` WITH TotalCallsHittingTheOffice AS ( SELECT Call_date as "Date" ,SUM(Calls) as "Total" FROM Call GROUP BY Call_date ) ,TotalCallsComingThroughTheCallCentre AS ( SELECT Interval_Start_date as "Date" SUM(MyCS.Incoming + MyCA.Abandoned)/4 as "Total" FROM call_callsummary as M...
Most databases have `minus` or `except` to subtract two queries. This sample works for example on Oracle (using `minus`): ``` SELECT Call_date as "Date" , SUM([Calls) as "Total" , 'Calls' as "Units" FROM Call GROUP BY Call_date except select Interval_Start_date as "Date" , sum(MyCS.Incoming + MyCA...
sql for subtracting two queries
[ "", "sql", "sql-server", "" ]
I have two tables:- student table ``` std_ID|std_Name ------+-------- 1 | Jhon 2 | Peter 3 | Mic 4 | James ``` studentBatch Table ``` B_std_ID|B_Batch_ID --------+------------- 1 | 3 2 | 6 3 | 7 ``` i want students those who are not enrolled in a batch, i want this ``` std...
This should do what you need: ``` SELECT std_ID, std_Name FROM student WHERE std_ID not in (select B_std_ID from studentBatch ) ```
``` select std_id from student where std_id not in (select B_std_ID from studentbatch) ```
SQL, SELECT WHERE NOT EQUAL
[ "", "mysql", "sql", "" ]
I want to get SQL *LOAD\_FILE* function to work and have read every single question/answer + documentation about this, but here is what's been happening. When I want to *LOAD\_FILE* from my home directory: ``` mysql> SELECT LOAD_FILE('/home/myuser/somefile.txt'); +----------------------------+ | LOAD_FILE('/home/myus...
I found out that it has to do with AppArmor. I disabled AppArmor for MySQL and it worked. For people having the same problem, please read here: <http://www.cyberciti.biz/faq/ubuntu-linux-howto-disable-apparmor-commands/>
Per [Documentation](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_load-file) > To use this function, the file must be located on the server host. > > You must specify the full path name to the file. > > You must have the FILE privilege. > > The file must be readable by all > > File size should ...
MySQL LOAD_FILE returns NULL
[ "", "mysql", "sql", "chmod", "chown", "mysql-loadfile", "" ]
Im trying to build replace statements but I'm getting this error: The replace function requires 3 argument(s). Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicol...
``` SELECT ccc.*, REPLACE( REPLACE( REPLACE( REPLACE( REPLACE(bbb.Text, '[Change]', CONVERT(varchar, CAST(COALESCE(ccc.change, 0) AS decimal(10, 2)))), '[CurrentAmount]', '$' + CONVERT(varchar, CAST(COALESCE(ccc.currentamount, 0) AS money), 1)), ...
There are three places like this: `)))) + '%'` Move that last parenthesis over: `))) + '%')`
Replace statement
[ "", "sql", "sql-server", "replace", "" ]