Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have two tables: ``` Membership mID StartingDate Name Address Gender EndingDate ``` And ``` Circulation Info ISBN mID DateOfBorrow DateOfReturn DateOfLoss ``` I am attempting to find the activity level of each genders, but as of right now I am not having ver much luck. Here is wha...
In addition to the issue about the table aliases (when you alias a table, you must then use that alias rather than the table name to qualify the field names), I think you want a `Count()` function to give you "activity level". Also note Access generally complains about any field expression in the `SELECT` clause which...
The reason is that you have set an alias for tables, but then use table name prefixing column names instead of alias. Try this: ``` SELECT m.Gender, c.mID, m.mID FROM [Circulation Info] AS c INNER JOIN Membership AS m ON c.mID = m.mID GROUP BY m.mID HAVING m.Gender='F'; ```
Finding Activity level of gender
[ "", "sql", "ms-access", "" ]
I'm looking to create three separate check constraints for my SQL Server database to ensure that a password field constrains a minimum of one number, one uppercase character and one special character. I consider the best way to approach is by creating separate check constrains for example I have created the following ...
You can do this with one constraint, something like: ``` check password like '%[0-9]%' and password like '%[A-Z]%' and password like '%[!@#$%a^&*()-_+=.,;:'"`~]%' and len(password) >= 8 ``` Just a note about the upper case comparison: this requires that the collation being used be case sensitive. You may need to spec...
I did not know answer for your question directly, but after some research i found this methods: 1) Check if given string contains uppercase character ``` SELECT CASE WHEN BINARY_CHECKSUM([password]) = BINARY_CHECKSUM(LOWER([password])) THEN 0 ELSE 1 END AS DoesContainUpperCase GO ``` source: <http://www.sqlservercen...
Check Constraint- Check password contains atleast one number/special Character/uppercase
[ "", "sql", "sql-server", "check-constraint", "" ]
I've been working with tsql for quite a while now but I've never seen binary anding or oring in WHERE clause. Now I'm developing new application that would benefit from applying a bitmask. Lets say I have 16 product grades. Each grade is representrd by a bit position in a bit[] column. So grade A109 would be 0000000000...
I did some more research and the best solution is to compare masks with bitwise AND operator like this ``` WHERE mask1 & mask2 <> 0 ``` This is easy, simple and cohesive.
First time for me too. Interesting. ``` declare @A109 int = 1; declare @B704 int = 512; declare @V64 int = 16384; declare @Xx int = 32; declare @mask int = 16897; --@A109+@B704+@V64 create table #MyData ( name char(2), value int); insert #MyData values ('a', @A109), ('b1', @B704), ('b2',@B704), ('c', @Xx...
comparing bit array to bit mask in tsql
[ "", "sql", "sql-server", "t-sql", "" ]
``` SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["techconn"].ToString()); SqlCommand com = new SqlCommand("select * from hs where ac between'" + TextBox1.Text + "'and '" + TextBox2.Text + "' and em='" + DropDownList1.SelectedItem.Text.ToString() + "'", con); Dat...
In short, the answer is no. You need to always use parameters in your queries. ``` SqlCommand com = new SqlCommand("select * from hs where ac between @ac1 and @ac2 and em=@em", con); ``` You then add the parameters to your SqlCommand object (com).
Yes your code is quite prone to issues, not only sql injection attacks. Try the following: ``` public DataTable GetData(string textbox1, string textbox2, string dropdown) { DataTable result = null; string connString = null; if (ConfigurationManager.ConnectionStrings["techconn"] != null...
Safety from SQL injection
[ "", "sql", "sql-server", "c#-4.0", "sql-injection", "" ]
I have two tables with ``` table 1 col1 date 1 13/4/2014 2 15/4/2014 3 17/4/2014 5 19/4/2014 table 2 col1 date 1 13/4/2014 3 16/4/2014 6 18/4/2014 joining the two tables i should get col1 date col2 date 1 13/4/2014 1 13/4/2014 2 15/4/2014 3 17/4/2014 3 16/4/2014 ...
``` select n.col1 , n.date1 , m.col2 , m.date2 from t1 n full join t2 m on n.date1 = m.date2 and n.col1 = (select max(col1) from t1 where date1 = m.date2 ) and n.col1 is not null where n.date1 is not null or m.date2 is not null order by coalesce(n.date1, m.date2) , c...
[SQL Fiddle](http://sqlfiddle.com/#!15/3d2c4/2) ``` select col1, date1, col2, date2 from t1 full outer join t2 on col1 = col2 order by coalesce(date1, date2), date2; ```
SQL joins with order by
[ "", "sql", "postgresql", "join", "postgresql-9.1", "" ]
I have the following tables: ``` sh_feeds => id => feed_id sh_subscriptions => id => user_id => feed_id ``` The query I'm trying to produce is: > Select all from `sh_feeds` where `feed_id` matches a `feed_id` in > `sh_subscriptions` which corresponds to a `user_id` that matches > `$user_id`. Sl...
Should be fairly easy, like this: The inner join ensures that only rows are included for which the feed\_id also occurs in sh\_subscriptions. ``` SELECT f.* FROM sh_feeds f INNER JOIN sh_subscriptions s ON f.feed_id = s.feed_id WHERE s.user_id = $user_id; ```
Try this ``` SELECT * FROM sh_feeds F INNER JOIN sh_subscriptions S ON F.feed_id = S.feed_id WHERE S.user_id = $user_id; ```
How would I express this MySQL JOINs query?
[ "", "mysql", "sql", "join", "" ]
should be simple one but i am currently really confused i have a db query : ``` public double markingAvg(Marking id) { System.out.println("In MarkingAvg"); System.out.println("id = " + id); System.out.println("id = " + id.getId()); Query m = em.createQuery("SELECT m.markSectionOne, ...
You could use inline conditional check for this: ``` total += Double.parseDouble((String) ((mark==null) ? 0 : mark))); ```
You could also handle this in your query: E.g.: ``` ij> CREATE TABLE T(I INT); ij> INSERT INTO T VALUES 1, 2, 3, NULL; 4 rows inserted/updated/deleted ij> SELECT * FROM T; I ----------- 1 2 3 NULL 4 rows selected ij> SELECT (CASE WHEN I IS NULL THEN 0 ELSE I END) FROM T;...
How to deal with null values - JPA/SQL/JPQL
[ "", "sql", "jpa", "derby", "jpql", "" ]
I'm creating a database for a hypothetical video rental store. All I need to do is a procedure that check the availabilty of a specific movie (obviously the movie can have several copies). So I have to check if there is a copy available for the rent, and take the number of the copy (because it'll affect other trigger l...
You can try this - ``` WITH film as ( SELECT idCopia, titolo FROM COPIA_FILM WHERE titolo='Pulp Fiction' ), copy_info as ( select N.idNoleggio, I.dataNoleggio , I.dataRestituito , I.idCopia FROM NOLEGGIO N JOIN INCLUDE I ON N.idNoleggio=I.idNoleggio ), avl as ( select film.titolo, copy_info.idNoleggio, c...
You should think in terms of sets, rather than records. If you find the set of all the films that are out, you can exclude them from your stock, and the rest is rentable. ``` select copiafilm.* from @f copiafilm left join ( select idCopia from @r Noleggio inner join @i include on Noleggio.idNoleggio = includ...
SQL Queries instead of Cursors
[ "", "sql", "database", "oracle", "cursor", "" ]
I need to display some data in an SSRS 2008r2 report and the colors have to match a Windows VB app that saves it's colors as integers (e.g.16744703 is a pinkish color). I believe this is ARGB format. I'm not concerned about the alpha value, as the application does not allow the user to modify it. I'm stuck on the SQL ...
Figured it out. Here's a function that returs either RGB() or Hex ``` -- Description: Converts ARGB to RGB(RR,GG,BB) -- e.g. 16744703 returns RGB(255,128,255) or #FF80FF CREATE FUNCTION [dbo].[ARGB2RGB] ( @ARGB AS BIGINT ,@ColorType AS VARCHAR(1) -- 'H' = Hex, 'R' = RG...
``` create FUNCTION [dbo].[ConvertRGB] ( @ARGB AS float ) RETURNS @ReturnValue TABLE ( R TINYINT,B TINYINT, G TINYINT ) as BEGIN DECLARE @testvarbinary binary(4) DECLARE @strRBG nvarchar(MAX) set @testvarbinary = CONVERT(binary(4),@ARGB) set @strRBG=( SELECT substring(sys.fn_varbintohexstr(@test...
Getting RGB(R,G,B) from ARGB integer (SQL)
[ "", "sql", "hex", "argb", "" ]
I'm trying to write a query that returns true if the same idx exists in another table. Here is what I want to do. Two Tables: ``` User (user_idx, name) Group (group_idx, user_idx) ``` Pseudo Query: ``` SELECT user_idx, name, (True(1)/False(0) value) as has_joined_group FROM User WHERE (Check if user_idx exists in ...
``` SELECT u.user_idx, u.name, g.user_idx IS NOT NULL AS has_joined_group FROM User AS u LEFT JOIN Group AS g ON g.user_idx = u.user_idx AND g.group_idx = 3 ```
``` SELECT u.user_idx, u.name, CASE WHEN g.user_idx IS NOT NULL AND g.group_idx = 3 THEN 1 ELSE 0 END AS has_joined_group FROM user u JOIN LEFT group g ON u.user_idx = g.user_idx ```
Mysql Return true if idx exists in another table
[ "", "mysql", "sql", "" ]
Using a university relation (students are advised by instructors in different departments, only one advisor per student but advisors can have zero to many advisees), I'm attempting to write a function that computes the total number of students being advised in a given department. Here are the tables and columns for re...
``` SELECT i.dept_name, COUNT(a.s_id) FROM Instructor i LEFT JOIN advisor a ON i.id = a.i_id GROUP BY i.dept_name; ``` This will include zeros for departments with no advisees.
If you are interested in the number of advised students per *student* department then: ``` SELECT s.dept_name, COUNT(a.s_id) FROM student s LEFT JOIN advisor a ON a.s_id=s.id GROUP BY s.dept_name ``` OTOH, if you are interested in the number of advised students per *instructor* department then: ``` SELECT i.dep...
SQL Am I using this join correctly?
[ "", "mysql", "sql", "" ]
Guys I have three tables in SQL database. `tblTicketDetail`, `tblEngineer` and `tblTicket_Engineer` (a junction table for many-to-many relationship). What happens in my app is, when I generate a new ticket, the ticket is assigned to either one, two or three (max) engineers (thus the many-to-many relationship). Followi...
You need to create a join on your sub-query to get the ticket status and the sub-query should look like below: ``` SELECT COUNT(*) total FROM tblTicket_Engineer INNER JOIN tblTicketDetail ON tblTicketDetail.TicketID = tblTicket_Engineer.TicketID AND tblTicketDetail.Status = 1 WHERE tblTicket...
I think below code will help you ``` SELECT Count(*) FROM tblTicket inner join tblTicket_Engineer on (tblTicket.TicketID= tblTicket_Engineer.TicketID) WHERE tblTicket.Status = '1' AND tblTicket_Engineer.EngineerID = '1' ```
How to use COUNT on two tables with WHERE clause
[ "", "sql", "count", "" ]
``` if(isset($_POST['update_page'])) { if($_POST['agent_name']=="" and $_POST['company_name']=="" and $_POST['email']=="") { $response = asort_form_error("All agent detail fields should be filled"); extract($_POST); } else { $sql = "UPDATE ".TBL_AGENT." SET agent_name = '$_PO...
This should work: ``` "UPDATE ".TBL_AGENT." JOIN ".TBL_SUBSCRIPTION." ON ".TBL_AGENT.".agent_id = ".TBL_SUBSCRIPTION.".agent_id SET ".TBL_AGENT.".agent_name = '$_POST[agent_name]' , ".TBL_AGENT.".company_name = '$_POST[company_name]' , ".TBL_AGENT.".email = '$_POST[email]', ".TBL_SUBSCRIPTION.".renewal_date = ( UNI...
Use a `JOIN` ``` UPDATE tbl_agent AS a JOIN tbl_subsription AS s ON a.agent_id = s.agent_id SET a.agent_name = '$_POST[agent_name]', s.renewal_date = ( UNIX_TIMESTAMP() + ( '$_POST[subscription_renewal]' * 86400 ) ) WHERE a.agent_d = '{$_GET['id']}' ```
update records of multiple tables using same id
[ "", "mysql", "sql", "join", "insert-update", "" ]
I have a table like ``` Name Description EID Basecode ----- ----------- ---- --------- name1 ssdad 1001 S2378797 name2 gfd 1002 S1164478 name3 gfdsffsdf 1003 R1165778 name4 ssdad 100...
You can use Left and In as another approach, for example: ``` SELECT t.Name, t.Description, t.EID, t.Basecode FROM TheTable AS t WHERE Not IsNumeric(Left(t.Basecode,1)) AND Left(t.Basecode,1) Not In ("W","N") ```
For a query run from within the Access application itself you could use something like this: ``` SELECT * FROM YourTableName WHERE Basecode LIKE '[a-m]*' OR Basecode LIKE '[o-v]*' OR Basecode LIKE '[x-z]*' ``` Edit: As HansUp points out, the above can be condensed to ``` SELECT * FROM YourTableName WHERE Basecode L...
How to find whether a column values are starting with letter access sql
[ "", "sql", "ms-access", "" ]
I am getting an error: ORA-01789: query block has incorrect number of result columns when trying to create a table from data in 2 other tables. Please help, is this just a syntax error or am I combining the tables in the wrong way? ``` CREATE TABLE EMPDATA(ID, NAME, SALARY, DEPTNAME) AS SELECT e.employee_id, (e.fi...
I think you want `JOIN` instead of `UNION`: ``` CREATE TABLE EMPDATA(ID, NAME, SALARY, DEPTNAME) AS SELECT e.employee_id, (e.first_name || e.last_name), e.salary, d.department_name FROM employees e JOIN departments d on(d.department_id = e.department_id); ```
The number of coumns while using UNION should be same in the SELECT statement
Create table error oracle
[ "", "sql", "oracle", "" ]
I have prepared a [sqlfiddle](http://sqlfiddle.com/#!3/844e0) workspace which you can see the question and solve it easily. There is a table include ID, DAT, AMN, FLWC, FLWD, TYP. I would like to sort table by DAT and ID (DAT is first keyword in sort) then update FLWC and FLWD from previous record depend on TYP. for ex...
Complicated question but easy answer! (it shows that the start point is very important to thinking about a question) ``` declare @sumc decimal declare @sumd decimal set @sumc=0 set @sumd=0 update myTable set @sumc+= case typ when 'c' then amn else 0 end, flwc=@sumc, @sumd+= case typ when 'd' then amn else 0 ...
You should add two more column with bit values i.e. C and D. Value of C is one if typ is c and 0 if typ is d and in reverse for d. ``` for over i { flwc(i)=flwc(i-1)+amn*C(i) flwd(i)=flwd(i-1)+amn*D(i) } ``` ---------------------------------- Edit --------------------------------- This is pseudo-code of what...
SQL Update records to sum of previous records with condition
[ "", "sql", "sql-server", "stored-procedures", "sql-update", "" ]
I have this SQL line ``` SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code], Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] WHERE [Item Category Code] = '5104' GROUP BY No_ ``` But i got this error for my script. ``` Column 'dbo.3S Company A_S$Sales In...
TRY THIS ``` SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code], Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] WHERE [Item Category Code] = '5104' GROUP BY No_,[Shipment Date], [ItemCategoryCode], Description,[Description 2] ``` IN SQL IF YOU ...
If you use `GROUP BY` in your query, only the columns used in your grouping clause and any aggregate functions like `SUM` are allowed in the select list. In your case, you specify `GROUP BY No_`, so that is the only column you can select without using an aggregate function. If you want to get the remaining columns, yo...
Error in SQL sum()
[ "", "sql", "sql-server", "" ]
I have a large table containns 20,000 records. I want to find similar records(duplicate records on those BNO and BNO-CSCcode columns) ``` CSCcode Description BNO BNO-CSCcode EID 05078 blah1 5430 5430-05078 1098 05026 blah2 5431 5431-05026 1077 ...
``` select t1.* from table_name t1 inner join (select BNO,BNO-CSCcode from table_name group BNO,BNO-CSCcode having count(1)>1) as t2 on t1.BNO=t2.BNO and t1.BNO-CSCcode=t2.BNO-CSCcode ```
You will have to use `EXISTS` command in your query. This will give the desired resuilt: ``` SELECT * FROM TableName t0 WHERE EXISTS ( SELECT 1 FROM TableName t1 WHERE t0.BNO = t1.BNO AND t0.BNOCSC = t1.BNOCSC GROUP BY BNO, BNOCSC HAVING count(*) > 1 ) ``` `EXISTS` is used for comparison betw...
How to find duplicates in two columns access sql
[ "", "sql", "ms-access", "" ]
I have the following table test ``` iD Name ParentId GroupID DisplayingOrder --------------------------------------------- 1 1 1 Null 2 1 1 Null 3 1 1 Null 4 7 2 Null 5 7 2 Null...
You can do the both UPDATES in one query you dont need to break it down in two statements. see below : ``` ; WITH CTE AS ( SELECT iDName, ParentId, GroupID,DisplayingOrder ,DENSE_RANK() OVER (ORDER BY ParentId ASC) RN1 ,ROW_NUMBER() OVER (PARTITION BY ParentId ORDER BY ParentId) RN2 FROM TEST ) ...
This isn't an exact duplicate of the earlier question. But a very similar approach can work: ``` WITH toupdate AS (SELECT iDName, ParentId, GroupID, row_number() over (partition by groupid order by idName) as newDisplayingOrder FROM test t ) UPDATE toupdate SET DisplayingOrder = ne...
Modify a column in a table
[ "", "sql", "" ]
I have two tables as shown below. First Table `tblCategory` ![enter image description here](https://i.stack.imgur.com/723mn.png) Second Table `tblWord` ![enter image description here](https://i.stack.imgur.com/qi9Nd.png) `Required Output` ![enter image description here](https://i.stack.imgur.com/yi8OO.png) On ou...
To get exact output with total count ``` SELECT t.categoryID, t.name, COUNT(*) as TotalCount, SUM(isplayed) as Played FROM tblCategory t INNER JOIN tblWord tw ON t.categoryID = tw.categoryID GROUP BY t.categoryID, t.name ``` To get count for isPlayed = 1 only ``` SELECT t.categoryID, t.name, COUNT(*) a...
try this ``` SELECT tw.Category_ID, tc.NAME, COUNT(*) AS TotalCount, SUM(tw.IsPlayed=1) AS Played ,SUM(tw.IsPlayed=0) AS NonPlayed FROM Table_Category tc INNER JOIN Table_Word tw ON tc.Category_ID = tw.Category_ID -- WHERE tw.IsPlayed=1 GROUP BY tc.Category_ID, tc.NAME ``` here `SUM(tw.IsPlayed=1) AS Played...
SQL : Count(*) and groupby with different table
[ "", "sql", "sqlite", "" ]
I have a following tables: `sensors:` ``` id name key code 1 s1 abc 123 2 s2 def 456 3 s3 ghi 789 ``` `measurements:` ``` id value sensor_id generated_at 1 1.0 1 2013-12-30 06:00:00 2 1.0 1 2013-12-30 06:01:00 3 1.0 1 2013-12-30 06:02:00 4 3.0 2 2...
I don't think that `LEFT JOIN` is really necessary here (only in case when there more or less `sensors.id` than in `measurements.sensor_id`). **SQL** query is below : ``` SELECT s.id, s.name, s.key, s.code, m.first_value_generated_at, m.last_value_generated_at FROM sensors s JOIN (SELECT ...
I hope this should work for you, ``` select * ,(select min(generated_at) from measurements as a where a.sensor_id =s.id) as first_value_generated_at ,(select max(generated_at) from measurements as b where b.sensor_id =s.id) as last_value_generated_at from sensors as s ```
MySQL LEFT JOIN dates with order
[ "", "mysql", "sql", "date", "join", "left-join", "" ]
could someone please have a quick look at the query i am writing below. A synopsis of what this query is suppose to be doing is to put the two characters "xx" in the field "Query04priorityselect" for all records where priority = "high". It seems that all is working other than the second to last line. The error message ...
I think you need to quote the word *high* in the `WHERE` clause. Single quotes are fine in Access SQL statements. ``` HighPriority = "UPDATE tblsearchengine01" & vbCrLf & _ "SET Query04priorityselect = 'xx' WHERE Priority <> 'high'" Debug.Print HighPriority CurrentDb.Execute HighPriority ``` If the query still t...
``` Dim HighPriority HighPriority = "UPDATE tblsearchengine01 SET Query04priorityselect ='xx' WHERE Priority<>high " CurrentDb.Execute HighPriority ```
Update query with SQL
[ "", "sql", "ms-access", "vba", "ms-access-2013", "" ]
Table: ``` +-------------+ | izvajalecID | +-------------+ | 20 | | 21 | | 21 | | 20 | | 21 | +-------------+ ``` I would like to count all the unique ID's and print their values. For example: Unique ID's: **2** Values: **20, 21** I tried with the following query. Count...
``` SELECT izvajalecID FROM servis GROUP BY izvajalecID UNION SELECT COUNT(DISTINCT izvajalecID) FROM servis ``` [**Fiddle**](http://www.sqlfiddle.com/#!2/5f1c3/1) The last value in the set is for COUNT of unique values. You can also change them places and it will be the first value, just a...
Try this: ``` SELECT izvajalecID, COUNT(DISTINCT izvajalecID) as COUNT FROM servis GROUP BY izvajalecID ``` Result: ``` IZVAJALECID COUNT 20 1 21 1 ``` See result in [**SQL Fiddle**](http://www.sqlfiddle.com/#!2/e5fa9/2).
MySQL: Print counted values
[ "", "mysql", "sql", "" ]
My previous question is very confusing. I am so sorry for my carelessness. Here, I posted my question again with more information. My table A and table B has same column names(name,id,age,date,class,...) but different number of rows. Table B is a duplicate table of table A and has fewer rows. What I want to know is ho...
Since you want to check for all columns writing a where clause for it might be tedious so you can use `information_schema.columns` to get the column names for that table and then using a dynamic query you can check for column differences. The following might be the solution to your problem. ``` --Simulate your table ...
You can use strcmp() function to compare the string. <http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#function_strcmp> for example you want to compare name and age from both table then your query should be like below: ``` select * from (select A.*,B.*,strcmp(concat(A.name,',',A.age),concat(B.n...
How to get the records back from two tables with same primary key if any of the other column fields are changed
[ "", "sql", "sql-server", "database", "" ]
Please see the code below: ``` SELECT mp_asin.CATEGORY_CODE AS Category_id ,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY ,mp_asin.PARENT_ASIN ,mp_asin.PARENT_ASIN_NAME ,mp_asin.COLOR_NAME AS Color_Name ,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD ,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN ,mp_asin.BRA...
Try this - ``` SELECT * FROM ( SELECT mp_asin.CATEGORY_CODE AS Category_id ,mp_asin.SUBCATEGORY_CODE AS SUBCATEGORY ,mp_asin.PARENT_ASIN ,mp_asin.PARENT_ASIN_NAME ,mp_asin.COLOR_NAME AS Color_Name ,mp_asin.PRODUCT_SITE_LAUNCH_DAY AS PSLD ,mp_asin.PARENT_ASIN_NAME || ', ' || mp_asin.COLOR_NAME as TEEN ,mp_asin.BR...
> **ORA-00904** can simply be avoided by using the valid column name in > create or alter statement. Also for DML statements ORA-00904 can be > avoided by making a valid reference to the column name or the alias. Try this ``` SELECT * FROM ( SELECT mp_asin.CATEGORY_CODE AS Category_id ,mp_asin.SUBCATEGORY_CODE AS SU...
Partition by and invalid identifier
[ "", "sql", "oracle", "" ]
Here is the schema Employee (name,sex,salary,deptName) and name is the primary key ``` SELECT deptname FROM employee WHERE sex=m GROUP BY deptName HAVING avg(salary) > (SELECT avg(salary) FROM employee) ``` I want to understand the part `having avg(salary)` what does that part actually do? since we dont include ...
`WHERE` filters records *before* they are grouped; whereas `HAVING` filters the results *after* they have been grouped. Expressions, using functions or operators, can be used in either clause (although aggregate functions like `AVG()` cannot be used in the `WHERE` clause as the records would not have been grouped when ...
``` SELECT AVG(salary) FROM employee ``` By above query first you will get avg salary of all employees. Now you are getting only department whose avg salary is greater than avg salary of all employees.
having clause works with where in mysql
[ "", "mysql", "sql", "group-by", "where-clause", "having", "" ]
``` SELECT contents.*, (SELECT COUNT(*) FROM comments WHERE comments.scrap_id = contents.org_scrap_id) AS comment_count FROM contents ORDER BY comment_count ``` this is my intention. but it makes very long waits. how can i increase the performance of this query?
You can increase the performance by creating an index on `comments(scrap_id)`: ``` create index comments_scrap_id on comments(scrap_id); ``` You could also try phrasing this as a `join` and `group by`: ``` SELECT co.*, count(com.scrap_id) as comment_count FROM contents co left outer join comments com on co...
You can rewrite your query using join,but for performance an explain plan is needed,you are using a correlated subquery which will run for each row in contents table and can reduce the performance of query, for below query you need an index for `scrap_id` from comments table and `org_scrap_id` from contents table if it...
how can i increase the performance of SQL?(sub query is used)
[ "", "mysql", "sql", "database-performance", "" ]
I am trying to find the difference between the current row and the previous row. However, I am getting the following error message: > The multi-part identifier "tableName" could not be bound. Not sure how to fix the error. Thanks! Output should look like the following: ``` columnOfNumbers Difference 1 ...
See [sqlFiddle](http://sqlfiddle.com/#!3/ad6e5/1) ``` ;WITH tblDifference AS ( SELECT ROW_NUMBER() OVER(ORDER BY id) AS RowNumber, columnOfNumbers FROM tableName ) SELECT cur.columnOfNumbers, cur.columnOfNumbers - previous.columnOfNumbers FROM tblDifference cur LEFT OUTER JOIN tblDifference previous ON cur.R...
If you in SQL Server 2012+ You can use LAG. ``` SELECT columnOfNumbers ,columnOfNumbers - LAG(columnOfNumbers, 1) OVER (ORDER BY columnOfNumbers) FROM tableName ``` Note: The optional third parameter of LAG is: > default > > The value to return when scalar\_expression at offset is NULL. > If a default val...
SQL Find difference between previous and current row
[ "", "sql", "sql-server", "" ]
I need to count the number of rows in a table with a single SQL query. That query should not contain any aggregate function like `COUNT`.
Easy way: ``` DECLARE @i INT = 0 SELECT @i = @i + 1 FROM <WHAT EVER> SELECT @i AS RC ``` Fast, effective and no need for all sorts of sub queries as it requires only one run through the data :)
I'm a little surprised nobody has mentioned this yet: ``` EXEC sp_spaceused @objname = N'MyTable', @updateusage = 'TRUE' ``` This will, among other things return the current count of records in the table. This would also work in most cases: ``` SELECT rows FROM sys.partitions WHERE index_id IN (1,0) AND obje...
Count number of rows without using any aggregate functions
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I want to make an addition of the sum of two queries (please see my queries below, these examples works). My problem is when one of the queries return a null result like ``` select (select sum(60+3+25+2))+(select sum(0)) as montant ``` the result of the addition is automatically NULL. But when the 2 queries have re...
You need to add something that will turn your `NULL` in to a `0`. ``` select COALESCE(sum(lfh.montant), 0) ```
You want something like this. t-sql ``` select (select 1 value) + isnull((select null value),0); ``` mysql ``` select (select 1 value) + ifnull((select null value),0); ```
sql addition of 2 queries return NULL
[ "", "sql", "" ]
i am creating a dynamic query in stored procedure. my stored procedure is as follows: ``` CREATE PROCEDURE `test1`(IN tab_name VARCHAR(40),IN w_team VARCHAR(40)) BEGIN SET @t1 =CONCAT("SELECT * FROM ",tab_name," where team=",w_team); PREPARE stmt3 FROM @t1; EXECUTE stmt3; DEALLOCATE PREPARE stmt3; END ``` when i t...
You missed to enclose the parameter `w_team` in `WHERE` clause. Try like this: ``` SET @t1 =CONCAT("SELECT * FROM ",tab_name," where team='",w_team,"'"); ``` **Explanation**: Query from your code would be like: ``` SELECT * FROM Test where team=SPA ``` It will try find a column `SPA` which is not available, hence...
> Error Code: 1054. Unknown column 'SPA' in 'where clause' This happens when you do not enclose input string within quotes, and SQL engine tries to identify it as a column in the table being queried. But it fails as it can't find it. But what happens when it finds such column? It fetches results when it finds some ...
mysql dynamic query in stored procedure
[ "", "mysql", "sql", "stored-procedures", "" ]
I am trying to convert a varchar field to a number, however, there is a set of common characters inside that field that need to be removed in order for me to successfully convert it to numeric. the name of the field is UKSellPrice1 I need to remove the following strings from UKSellPrice1 BEFORE converting it to numer...
I can think of two approaches. The first is to use a bunch of nested `replace()` statements: ``` select replace(replace(replace(col, '$', ''), '£', ''), 'n/a', '') ``` and so on. The second is to find the first digit and try converting from there. This requires complicated logic with `patindex()`. Here is an exampl...
You could do this. Create a function to strip a way the unwanted chars like this: ``` CREATE FUNCTION [dbo].[fnRemovePatternFromString](@BUFFER VARCHAR(MAX), @PATTERN VARCHAR(128)) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @POS INT = PATINDEX(@PATTERN, @BUFFER) WHILE @POS > 0 BEGIN SET @BUFFER = STUFF(@BUF...
replace multiple values at the same time - in order to convert a string to a number
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have this table: ``` +----+---------+----------+-------+ | id | user_id | other_id | score | +----+---------+----------+-------+ | 1 | 1 | 1 | 80 | | 2 | 1 | 2 | 40 | | 3 | 1 | 3 | 60 | | 4 | 2 | 2 | 70 | | 5 | 2 | 4 | 50 | | 6 | 2...
This can be easily done by using a subselect,comparing the count with same table ``` SELECT * FROM Table1 t WHERE ( SELECT COUNT(*) FROM Table1 t1 WHERE t1.user_id = t.user_id AND t1.score >= t.score ) <= 2 ORDER BY t.user_id ASC,t.score D...
Try this: ``` SELECT id, user_id, other_id, score FROM yourtable WHERE score = (SELECT MAX(score) FROM yourtable a WHERE a.user_id = yourtable.user_id AND a.other_id= yourtable.other_id); ```
Is there a way to select a certain number of row for a certain column?
[ "", "mysql", "sql", "" ]
I'm trying to insert data from excel sheet to sql database. The query is stored in a text file as follows: ``` insert into [demo].[dbo].[relative] select * from openrowset('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\relative.xls','select * from [sheet1$]'); ``` When I am executing the following command: ``` ...
Try using the sql server import vizard to create a new table from the xls file and then insert that data to the existing table from there. The problem you are having is maybe due to the non-compatibility between 64bit sql instance and 32 bit excel. Or try using `bcp` ``` bcp demo.dbo.relative in "D:\relative.xls" -c ...
You can create a shell script which will automatically read the insert commands from the .csv file and then write it to the database. If you want I can help you up with it. What you just need to do is to write all the insert statements in the .csv file. ``` #!/bin/ksh sqlplus -silent /nolog << EOF > /dev/null usernam...
sql insert query through text file
[ "", "sql", "sql-server", "" ]
I am trying to query a list of meetings from the most recent semester, where semester is determined by two fields (year, semester). Here's a basic outline of the schema: ``` Otherfields Year Semester meeting1 2014 1 meeting2 2014 1 meeting3 2013 2 ... etc ... ``` As the max should be ...
Using a window function: ``` SELECT Year, Semester, RANK() OVER(ORDER BY Year DESC, Semester DESC) R FROM your_table; ``` `R` will be a column containing the "rank" of the couple (Year, Semester). You can then use this column as a filter, for instance : ``` WITH TT AS ( SELECT Year, Semester, RANK() OVER(ORDER BY ...
I wouldn't be surprised if there's a more effecient way to do this (and avoid the duplicate subquery), but this will get you the answer you want: ``` SELECT * FROM table WHERE Year = (SELECT MAX(Year) FROM table) AND Semester = (SELECT MAX(Semester) FROM table WHERE Year = (SELECT MAX(Year) FROM table...
Find max over multiple columns
[ "", "sql", "oracle11g", "" ]
I have three tables: ``` pindex_photos: pindex_names: pindex_link: | id | filename | | id | name | | photo_id | name_id | |-----|-----------| |----|-------| |----------|---------| | 1 | DSC1.jpg | | 1 | Leo | | 1 | 3 | | 2 | DSC2.jpg | | 2 | Liz | | 1 |...
``` select p.filename, group_concat(n.name) from pindex_photos p left join pindex_link l on l.photo_id = p.id left join pindex_names n on l.name_id = n.id group by p.filename ``` and ``` select n.name, group_concat(p.filename) from pindex_photos p left join pindex_link l on l.photo_id = p.id left join pindex_names n ...
**Report on Images:** ``` SELECT p.id,COUNT(pn.name) as Count,group_concat(pn.name) FROM pindex_link pl LEFT JOIN pindex_photos p on p.id=pl.photo_id INNER JOIN pindex_names pn on pn.id=pl.name_id GROUP BY p.id ``` Result: ``` ID COUNT GROUP_CONCAT(PN.NAME) 1 2 Liz,Tom 2 1 Leo 3 1 Leo ``` ...
How to create a report from joined sql tables?
[ "", "mysql", "sql", "join", "report", "" ]
I am learning SQL Server and am confused as to whether I should put `City`, `State` and `Country` in one table or should I create 3 different tables with foreign keys? ![enter image description here](https://i.stack.imgur.com/o6rDg.png)![enter image description here](https://i.stack.imgur.com/yH21g.png) Please sugges...
The second one is better, as rule of thumb, always say if I need to rename a 'country' name how many records should be updated, if your answer is 1 then your design is good. (In first design the number of records that should be updated is as much as number of cities in that contry)
The second, normalized one, is better, of course. But you don't need CountryId in City table, if city is dependant on state and only indirectly on country.
SQL Server database design, which one is better design
[ "", "sql", "sql-server", "" ]
Every 15 minutes we read 250 XML files. Each XML file is an *element*. Each element (xml file) is composed of 5 sub-elements and each sub-element has 400 counters. All those counters will be used for formulas and aggregations. What's the most efficient way of storing this data into tables, in this case t-sql tables? ...
The maximum number of columns in a regular table is 1024 (see [here](http://technet.microsoft.com/en-us/library/ms143432.aspx)), so you can't put 2,000 columns in one table. That basically leaves two options: 1. Store each sub-element separately, with 400 columns (along with other identifing infromation, such as elem...
Looks like you can use an integer I would just read and write a row at time ``` element int subelement tinyint counterID smallint counterValue smallint ``` If you need to limit counterID to 1-400 you could do that with a trigger or a FK ``` select element, subelement, count(*) as count, min(counterValue ), max(co...
Saving 400 counters into table(s)?
[ "", "sql", "t-sql", "database-design", "data-warehouse", "business-intelligence", "" ]
I can't seem to figure this one out. I have a table of transactions (lots of them), with date, customer ID etc. I want to select, for a specific day, the datetime for only the first AND the last transaction for each customer on that day, like so: ``` custID FirstT LastT 318 08:05 18:35 968 03:21 13:54 488 ...
``` SELECT custID, MIN(transaction_date) AS FirstT, MAX(transaction_date) AS LastT FROM yourTable WHERE transaction_date >= '2014-04-01' AND transaction_date < '2014-04-02' GROUP BY custID ```
Try this: ``` SELECT custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date)) Date, MIN(date) FirstT, MAX(date) LastT FROM transactions GROUP BY custid, DATEADD(dd, 0, DATEDIFF(dd, 0, date)) ```
SQL: How can I select the first and last date for each customer?
[ "", "sql", "t-sql", "" ]
There is table with maker, model and type. I should select all makers that have more than 1 model, but all are the same type my attempt is ``` select maker, type from product where ((select count(model) from product) = (select count(model) from product where type='Printer')) or ((select count(model) from product) = (...
The following query will probably get you the desired result: ``` SELECT DISTINCT product.maker, product.type FROM product INNER JOIN (SELECT maker, count(distinct model) model_count, count(distinct type) type_count FROM product GROUP BY maker HAVING count(distinct model) > 1 AND count(distinct type) = 1 ) selected_ma...
Try this: ``` SELECT maker FROM PRODUCT GROUP BY type, maker HAVING COUNT(model)>1; ``` Also, this is the sql fiddle file <http://sqlfiddle.com/#!4/5f09a/1>
Select from table under circumstances
[ "", "sql", "select", "" ]
I have a sql query, the exact code of which is generated in C#, and passed through ADO.Net as a text-based SqlCommand. The query looks something like this: ``` SELECT TOP (@n) a.ID, a.Event_Type_ID as EventType, a.Date_Created, a.Meta_Data FROM net.Activity a LEFT JOIN net.vu_Network_...
If you want to remove a specific plan from the cache then it is really a two step process: first obtain the plan handle for that specific plan; and then use DBCC FREEPROCCACHE to remove that plan from the cache. To get the plan handle, you need to look in the execution plan cache. The T-SQL below is an example of how ...
There are many ways to [delete/invalidate a query plan](http://sqlhint.com/sqlserver/query-plan/delete-or-invalidate-query-plan): ``` DBCC FREEPROCCACHE(plan_handle) ``` or ``` EXEC sp_recompile 'net.Activity' ``` or adding `OPTION (RECOMPILE)` query hint at the end of your query or using `optimize for ad hoc wo...
Parameter Sniffing causing slowdown for text-base query, how to remove execution plan?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "stored-procedures", "" ]
I have a requirement to show a listing of data associated with a given widget, however I can only aggregate on the widget while it's in sequence (essentially breaking the running total when the widget changes). Here's a bit of a break down of what I mean... Example data: ``` ID WIDGET PART 1 A000 B22 ...
Does this work for you? ``` ;with x as ( select *, lag(widget) over(order by id) as lg from #t ), y as ( select *, sum(case when widget<>lg then 1 else 0 end) over(order by id) as grp from x ) select widget, min(part), count(*) from y group by widget, grp ```
@dean solution is neat but a pure SQLServer 2008 solution is possible, the idea is the same, the ranker formula ``` sum(case when widget<>lg then 1 else 0 end) over(order by id) as grp ``` can be faked by a running total, for the record the full query is ``` WITH part AS ( SELECT a.id, a.widget, a.part , breake...
Grouping by an aggregate column
[ "", "sql", "sql-server-2008", "t-sql", "aggregate-functions", "aggregate", "" ]
I have a table "projectdetails" in which `parent_id` is the foreign key of column `project_id` in the same table.. From this below records I want only those rows whose `parent_id` does rows, does not have 'recycle\_bin` value as 1 and also should display record for creater\_id = 7923 ; I have record like this: ``` m...
something like this? [FIDDLE](http://sqlfiddle.com/#!2/ceae3/4) for reference ``` SELECT project_id,project_name,parent_id,recycle_bin,creater_id FROM projectdetails AS pd1 JOIN( SELECT parent_id FROM projectdetails as pd WHERE pd.parent_id > 0 AND pd.recycle_bin > 1 ) AS t ON t.parent_id = pd1.project_id ``` ...
Try this query, ``` SELECT project_id,project_name,parent_id,recycle_bin,creater_id FROM projectdetails WHERE recycle_bin not in (select recycle_bin from projectdetails where recycle_bin = 1 ) AND creater_id = 7923; ``` Else try this as @SamD suggested, ``` SELECT project_id,project_name,parent_id,recycle_bin,cre...
SQL : loop through same table
[ "", "mysql", "sql", "" ]
I need to fetch usernames for my system, but if they exist in the table punishement\_banned, it won't fetch that username. I have made a query which should do that work, but for some reason, the query returns 0 values. I have 1 row in punishement\_banned with 1 name, total 2 names in the players table, so it must dis...
I have created sqlfiddle: <http://www.sqlfiddle.com/#!2/fd650/4/0> ``` SELECT username FROM players WHERE NOT EXISTS ( SELECT username FROM punishement_banned WHERE players.username = punishement_banned.username ) ```
This should do the job: ``` SELECT username FROM players WHERE players.username NOT IN (SELECT username FROM punishement_banned) ``` The problem is, you join the tables on the usernames being equal, and then exclude the usernames equal to each other.
MySQL select username only if username doesn't exist in other table
[ "", "mysql", "sql", "" ]
I am trying to calculate an average based on values from 2 table columns in `MySQL`. Lets say I have this table structure: ``` id | user_id | first_score | last_score 1 | 1 | 10 | 60 2 | 1 | 70 | 10 3 | 1 | 100 | NULL ``` What I am trying to achieve here, is calculating...
You solve this with the GREATEST function. Unfortunately it results in NULL when one or both values are NULL. So: ``` select avg( greatest( coalesce(first_score,last_score) , coalesce(last_score,first_score) ) ) from mytable; ```
``` select avg(GREATEST(first_score , last_score)) from the_table ```
Calculating average from 2 database table columns
[ "", "mysql", "sql", "" ]
I have a a room booking system where, a user can choose a room, and then book timeslots for that given room. I wan't to extend my system a bit, with the option to have a top 10 list of the most booked rooms. You can see my database, and it's foreign keys here: ![enter image description here](https://i.stack.imgur.co...
``` SELECT COUNT(*) as bCount, room_id FROM `bookings` GROUP BY room_id ORDER BY bCount LIMIT 10 ```
I think you should use GROUP BY Clause ``` SELECT Count(*) as Count , room_id FROM bookings GROUP BY room_id ORDER BY Count ```
What can I use if I want't to display a top 10 list of records
[ "", "mysql", "sql", "" ]
I am trying to use if in an Oracle query . I need something like this , But cant figure the syntax , if i can get help ``` select process from workstep where workstep_name = 'Manager' and (performer != 'Test' if end_time =null). <----- this line ``` This means if endtime = null And performer ='Test' then ...
You can't use IF in SQL with Oracle, but this is possible with simple BOOLEAN logic. You just need to negate two conditions at the same time: ``` select process from workstep where workstep_name = 'Manager' and not ( performer = 'Test' and end_time is null ) ```
You can do it this way ``` and (end_time is not null or (end_time is null and performer <> 'Test')) ``` If we have datas like this (left is performer, right is end\_time) ``` 'test' - notnulldate 'test' - nulldate 'tttt' - notnulldate 'tttt' - nulldate this will return all lines except 'test'-nulldate ``` mayb...
Conditional results based on two interconnected columns
[ "", "sql", "oracle", "" ]
If I want to delete some event I need to query something like `"DROP EVENT IF EXISTS eventname"` But I can't find the command of deleting all the events at one time,must delete event one by one. Is there some SQL of deleting all events at one time? ``` "DROP EVENT IF EXISTS (SELECT EVENT_NAME FROM information_schema....
sample one: ``` DELETE FROM mysql.event WHERE db = 'myschema' AND definer = 'jon@ghidora' AND name = 'e_insert'; ``` **<https://dev.mysql.com/doc/refman/5.1/en/events-privileges.html>** if you can delete the event with `DROP EVENT IF EXISTS` and re-add it with the new scheduled time. To permanently ...
To construct a drop events query, you can do something like this: ``` select concat('drop event if exists ', event_name, ';') from information_schema.events; ```
How to delete all events in MySQL
[ "", "mysql", "sql", "database", "" ]
I have the following query: ``` SELECT DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE()) ``` Which displays: ``` 2014-04-19 10:47:46.790 ``` How can I modify the query so it displays `04/19/2014` or `04-19-2014`
`SELECT CONVERT(VARCHAR, DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE()), 101)` **Outputs** `04/19/2014` And `SELECT CONVERT(VARCHAR, DATEADD(DAY, 0 - (DATEPART(weekday, GETDATE()) % 7), GETDATE()), 110)` **Outputs** `04-19-2014` Alternately, you could format this in the consuming application (in...
for 04/22/2014 ``` select convert(varchar(10), getdate(), 101) ``` for 04-22-2014 ``` select convert(varchar(10), getdate(), 110) ```
How to format date to a certain way in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I've a basic SQL table with a simple heirarchial connection between each rows. That is there is a ParentID for Every rows and using that its connecting with another row. Its as follows ``` AccountID | AccountName | ParentID --------------------------------------- 1 Mathew 0 2 P...
If I've got it right and you need to output whole table except 4 and all of it's descendants then try this recursive query: ``` WITH CT AS ( SELECT * FROM T WHERE AccountID=4 UNION ALL SELECT T.* FROM T JOIN CT ON T.ParentID = CT.AccountId ) SELECT * FROM T WHERE AccountID NOT IN (SELECT ...
Try this: ``` ;with cte as (select accountid,parentid, 0 as level from tbl where parentid = 0 union all select t.accountid,t.parentid,(level+1) from cte c inner join tbl t on c.accountid= t.parentid ) select * from cte where level < (select level from cte where accountid = @accountid) ``` When you pass in the pa...
Query to List all hierarchical parents and siblings and their childrens, but not list own childrens
[ "", "sql", "sql-server", "" ]
I know this question has been asked and answered. I understand the problem and I understand the underlying cause and I understand the solution. What I DON'T understand is how to implement the solution. I'll try to be detailed.... **Background:** Each material is being grouped on `WellID` (I work in oil and gas) and `...
# Querying and Joining Aggregation Data through an MS Access Database I noticed your concern for pointers on how to implement some of the theory behind your aggregation queries. While SQL queries are good power-tools to get to the core of a difficult analysis problem, it might also be useful to show some of the steps ...
I would simplify it excluding L\_WELL and L\_SAND. If you are just interestend in IDs, then they really shouldn't be necessary joins. If all the other 3 tables have the WellID and SandID columns, then pick the one that is sure to have all combos. Supposing it's the Design table, then: ``` SELECT WellID_DES AS WellI...
Access 2010 doubling the sum in query
[ "", "sql", "database", "join", "ms-access-2010", "" ]
``` SELECT *, DATEDIFF(CURDATE(),tarikhmohon) AS hari FROM mohon a INNER JOIN tblstatus_tak_lengkap b on a.noMyKid=b.nomykid WHERE noMyKid=130902100437 ``` I have tried that SQL but I got an error. > #1052 - Column 'noMyKid' in where clause is ambiguous. I can't find the problem.
Column `noMyKid` is present is both tables. You should tell the server on what table the column you want to filter, eg ``` WHERE a.noMyKid = 130902100437 ``` or ``` WHERE b.noMyKid = 130902100437 ``` Whatever you use, it doesn't matter since you are using `INNER JOIN`.
I think you have the column "noMyKid" in both tables. Prefix it like this : a.noMyKid
#1052 - Column 'noMyKid' in where clause is ambiguous
[ "", "sql", "database", "mysql-error-1052", "" ]
If I do: ``` ALTER TABLE testtable MODIFY mycolumn NEWDATATYPE; ``` I loose other definitions like NOT NULL, COMMENTS, DEFAULT values... Is there a way to do it? [In PostgreSQL I used](http://www.postgresql.org/docs/9.3/static/ddl-alter.html#AEN2790): ``` ALTER TABLE testtable ALTER COLUMN mycolumn NEWDATATYPE; ```...
As it's stated in [manual page](http://dev.mysql.com/doc/refman/5.0/en/alter-table.html), `ALTER TABLE` requires all new type attributes to be defined. However, there is a way to overcome this. You may use [`INFORMATION_SCHEMA` meta-data](https://dev.mysql.com/doc/refman/5.0/en/information-schema.html) to reconstruct ...
``` ALTER TABLE tableName MODIFY COLUMN columnName datatype ```
Change column data type in MySQL without losing other metadata (DEFAULT, NOTNULL...)
[ "", "mysql", "sql", "" ]
I've been replacing a set of CLR stored procedures with straight SQL but I've been stuck on this one report. The system makes entries into a stats table when an event occurs. If a particular event doesn't occur, there is no entry in the HourlyStats table. ``` Table HourlyStats UserID TimeStamp EventID Dur...
Here you go: ``` SELECT u.Name, c.[Description], hs.Duration FROM Users u CROSS JOIN Categories c LEFT OUTER JOIN HourlyStats hs ON u.UserID = hs.UserID AND c.EventID = hs.EventID ```
What you need is `CROSS JOIN` to get every possible combination of `USERS` and `EVENTS` and than `LEFT` join to `HourlyStats` code will be like this ``` ;WITH base AS ( SELECT u.UserID ,u.name ,c.EventId ,c.Description ...
SQL Query needs to return rows even when results are null
[ "", "sql", "sql-server-2008", "join", "" ]
Can we set isolation level for plain SQL statements in a stored procedure in SQL Server 2005/2008? Case 1: (This will work fine) ``` CREATE PROCEDURE MySP AS BEGIN SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED BEGIN TRAN SELECT * FROM MyTable COMMIT TRAN END ``` Case 2: (does this isolation stu...
If you use `SET TRANSACTION ISOLATION LEVEL` in a stored procedure, this transaction isolation level is used for the duration of the stored proc. According to [MSDN](http://technet.microsoft.com/en-us/library/ms173763.aspx): > If you issue SET TRANSACTION ISOLATION LEVEL in a stored procedure or trigger, when the obje...
Yes it will work for multiple select statements. If you are worried about the lack if a transaction in the second stored procedure you should know that the query is executed under an implicit transaction as opposed to an explicit transaction that you have in the first stored procedure.
Transaction isolation for sql statements
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a database table in the format: ``` DataA | DataB | DataC | TimeStamp | UniqueID ``` Data may look like: ``` 5 | 4 | 11 | 1/1/2014 | 1 5 | 4 | 2 | 2/1/2014 | 2 5 | 4 | 11 | 3/1/2014 | 3 3 | 6 | 7 | 4/1/2014 | 4 ``` The problem is that I have duplicate entries where DataA-C are all the same (rows 1 and 3), ...
``` DELETE FROM the_table WHERE id IN (the select to return duplicated records' ids) ``` The select should be similar to this one ``` SELECT id FROM the_table T JOIN ( SELECT MIN(id) AS id FROM the_table GROUP BY all your fields here ) sub ON T.id= SUB.id ```
``` DELETE FROM test WHERE UniqueId NOT IN (SELECT UniqueId FROM (SELECT * FROM test ORDER BY TimeStamp) T1 GROUP BY DataA, DataB, DataC) ``` **[Fiddle](http://sqlfiddle.com/#!2/884ab2/12)**
MySQL Query Remove Duplicate Row
[ "", "mysql", "sql", "database", "duplicates", "" ]
I have a table with a Comments field and I want to capitalize the first letter of the string in each record eg change 'duplicate' into 'Duplicate'. Some records will already have a capital at the start, and some may even be a number. I tried this ``` SELECT UPPER(LEFT(Comments,1))+SUBSTRING(Comments,2,LEN(Comments)) ...
Cast your ntext to nvarchar(max) and do the upper and left operations. Sample below. ``` SELECT UPPER(LEFT(cast(Comments as nvarchar(max)),1)) + LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2, LEN(cast(Comments as nvarchar(max))))) FROM dbo.Template_Survey; ``` Following should work for update. ``` Update dbo.T...
Cast you column to nvarchar(max) here is the working example <http://sqlfiddle.com/#!3/5dd26/3> To update records you can use: ``` Update dbo.Template_Survey set Comments = UPPER(LEFT(cast(Comments as nvarchar(max)),1)) + LOWER(SUBSTRING(cast(Comments as nvarchar(max)),2, LEN(cast(Comments as nvarchar(max))))) ```
How to capitalize the first letter of a record in SQL
[ "", "sql", "sql-server-2008", "" ]
I have a table1 contains 4 columns ``` AssociateId, chk1, chk2, chk3 ``` and another table(table2) contains same 4 columns. ``` chk1, chk2, chk3 ``` 1. Columns will have the values 'yes/no/null' 2. If table1 contains 3 records and 2 records contains the value 'yes' for all chk1,chk2,chk3 columns, then both records ...
if i have unterstand your question right, i think this could work for you: for the insert in table1 you can run this sql statement: insert into table2 chk1,chk2, chk3 values (select chk1,chk2, chk3 from table 1 where chk1='yes' and chk2='yes' and chk3='yes') and the you delete the records in table1 delete from tabl...
You can use a transaction. First insert your records in table2 like ``` Insert into table2 (column1,column2,column3) select column1, column2,column3 from table1 where column1 ='YES' and column2 ='YES' and column3 ='YES'; ``` you can then delete your records from table1 based on same condition & commit your transacti...
How to copy records to another table based on a condition?
[ "", "sql", "sql-server", "sql-server-2008", "triggers", "" ]
``` CREATE TABLE IF NOT EXISTS test (col1 INT, col2 INT); ALTER TABLE test ADD INDEX idx_col1(col1); ALTER TABLE test ADD INDEX idx_col2(col2); EXPLAIN SELECT * FROM test WHERE col1>=0 AND col2<=2; ``` Result: ``` id select_type table type possible_keys key key_len ref 1 SIMPLE test range idx_col2,idx...
This is a classic problem concerning selects which involve ranges. The result of an index lookup is one or more rows in a table. When SQL decides how to process your select, it has to decide what index to use first. In your case it was idx\_col2. As a result it will know all rows which satisfy (col2<=2). From these r...
I think, if you use both it need to be sort twice, it sort by col2, thus the remain lines are check line by line for col1, Maybe this is because your rows are too small, if there are many rows, it might do sort twice, thus use 2 index. I am not sure, just wondering.
Why not use two indexes in the following sql
[ "", "mysql", "sql", "" ]
i want to select a column but with diferent order : i have 2 table : table\_name: ``` +------+-----------+ | id | name | +------+-----------+ | 1 | Sindra | | 2 | Auli | | 3 | Brian | | 4 | Bina | | 5 | zian | | 6 | Bri | | 7 | Andre | +------+-----------+ ...
Now, I tried so many times, and I could find queries that displays result exactly same as you needed. But work has to be done in two steps with an assumption that `id`s can't be negative. Step-1: Create a valuable: ``` mysql> SET @max_id = (SELECT MAX(id) FROM table_name) * 2; Query OK, 0 rows affected (0.00 sec) ```...
**AFTER EDIT 1:** You can proceed to [this\_way](https://stackoverflow.com/users/3146681/walk-this-way) ``` SELECT tgejala.id_gejala,tgejala.nama_gejala FROM tgejala LEFT JOIN ttemp ON tgejala.id_gejala= ttemp.idtemp_gejala ORDER BY CASE WHEN ttemp.id_temp is NULL THEN 1 ELSE 0 END ``` **EDIT 2:** Ok then see th...
SQL : Select statement order by other table
[ "", "mysql", "sql", "" ]
Suppose I have a parameter @UserID, it can be 0 (no userid assigned) or id itself. The structure of query is as follows ``` if @UserID > 0 select ... where UserID=@UserID ... else if @UserID = 0 select ... where ... ``` What I want is the following structure ``` select ... where if @UserID >0 then UserID = @Us...
set null as parameter value instead of 0 (zero) ``` declare @id int set @id = null select * from users where (id = @id) or (@id is null) ```
Use a case statement as: ``` WHERE 1 = CASE WHEN @UserID >0 and UserID = @UserID THEN 1 ELSE 0 END ```
Not taking into account condition
[ "", "sql", "sql-server", "" ]
Morning- I am having a bit of a problem today getting a NOT filter to work in SQL 2012. I have a list of 6030 records, and am filtering by a field called mat\_ref. There are particular names that I do not want to have in the resulting dataset. So I filtered as follows: ``` SELECT mat_ref AS [Client Name], ccod...
Do the filtering using `not in`: ``` SELECT mat_ref AS [Client Name], ccode FROM lntmu11.matter WHERE mat_ref NOT IN ('McAdams', 'Thompson'); ```
This is Boolean logic rather than anything else. You're searching for rows where ``` mat_ref is NOT EQUAL to McAdams OR mat_ref is EQUAL to Thompson ``` This will return every row as McAdams is not equal to Thompson. I think you wanted to use AND and a not equals. ``` WHERE mat_ref <> 'McAdams' AND mat_ref <> 'Th...
Does the NOT function in SQL only allow one possible factor?
[ "", "sql", "t-sql", "" ]
i am trying to do an ``` INSERT INTO MYTBL VALUES (CAST(SPACE(7997) + 'abcd' as nvarchar(max)) ``` and it does not go over 8000 bytes not sure what it is i am doing wrong MYTBL only has one column (Col1 (nvarchar(max))
based on your code you are missing last ")" modify your code to this: ``` INSERT INTO MYTBL VALUES (CAST(SPACE(7997) + 'abcd' as nvarchar(max))) ``` additionaly just like @datagod said you need to convert/cast your strings as `NVARCHAR(max)` before concatenation. you can use this ``` INSERT INTO MYTBL VALUES (...
Try casting each of your strings as nvarchar(max) first, then concatenate them. I have found that string functions such as replicate() return regular varchar results which get truncated after 8000 chars.
SQL: trying to insert large string into varchar(max)
[ "", "sql", "sql-server", "t-sql", "" ]
I have a database table as follows: ``` ProductDetails ----------------- ProductDetailsID int ProductIdentifier VARCHAR (20) ProductID int ProductFile VARCHAR(255) ProductAvailability char(2) RightsCountry varchar(MAX) Deleted bit ``` There was a bug in the platform recently that allowed a large number of duplicates ...
This works and is a cheeky way of abusing the partitioned window functions: ``` declare @ProductDetails table( ProductDetailsID int not null, ProductIdentifier VARCHAR(20) not null, ProductID int not null, ProductFile VARCHAR(255) null, ProductAvailability char(2) not null, RightsCountry varchar(MAX) not null, Deleted...
``` create view rows_to_delete as select * from ( select *, row_number() over(partition by ProductIdentifier order by ProductFile desc, ProductDetailsID) as rn from t ) x where rn > 1 and ProductFile is null ```
T-SQL Select duplicate rows where at least 1 column has a value
[ "", "sql", "sql-server", "t-sql", "" ]
This is a rather unique problem and I don;t know if there is an answer. Im trying to input a variable amount of records to insert into a table depending on the value of another table. This is what I have tried ``` insert into TABLE1 select TOP cast((select Value from TABLE3 WHERE column_name = 'blah') as int) * from T...
OP doesn't specify the database they are using, but SQL Server allows a variable. try it out: ``` declare @YourTable table (RowID int identity(1,1), ColA char(4)) INSERT INTO @YourTable values ('a');INSERT INTO @YourTable values ('aa');INSERT INTO @YourTable values ('aaa'); INSERT INTO @YourTable values ('b');INSERT I...
~~TOP x cannot be specified in a variable.~~It actually can, see KM's answer (which is definitely better than mine). An option here would be a dynamic query ``` DECLARE @topx AS integer; SET @topx = (select Value from TABLE3 WHERE column_name = 'blah') DECLARE @query AS varchar(max); SET @query = 'INSERT INTO table1...
Select TOP x From table
[ "", "sql", "select", "" ]
I need to remove duplicates from my table (user\_info). I always want to remove the row with the id column that is lower of the two rows being returned from my select/having query below. Any ideas on how to write the delete statement to remove the duplicates (lower user\_info.id column) from the results of my select/ha...
Start with this to show you only the duplicates ``` Select user_id, count(*) NumRows, Min(Id) SmallestId, Max(Id) LargestId From user_info Group by user_id HAVING count(*) > 1 ``` This will show you the min and max for each `user_id` (with the same value for SmallestId and LargestId if there are no duplicates. ``` S...
You can use the following query: ``` DELETE FROM user_info WHERE id NOT IN (SELECT MAX(id) FROM user_info GROUP BY user_id); ``` This query will delete all the duplicate rows except the `user_id` row with maximum `id`. Here's a **[SQL Fiddle](http://www.sqlfiddle.com/#!4/bbad4/1)** which demonstrates th...
Remove Duplicate Row Data
[ "", "sql", "oracle", "" ]
This feels simple, but I can't find an answer anywhere. I'm trying to run a query by time of day for each hour. So I'm doing a `Group By` on the hour part, but not all hours have data, so there are some gaps. I'd like to display every hour, regardless of whether or not there's data. Here's a sample query: ``` SELEC...
You can use a recursive query to build up a table of whatever numbers you want. Here we stop at 24. Then left join that to your comments to ensure every hour is represented. You can turn these into times easily if you wanted. I also changed your use of `hour` as a column name as it is a keyword. ``` ;with dayHours as ...
You can use a table value constructor: ``` with hours as ( SELECT hr FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) AS b(hr) ) etc.. ``` You can also use a permanent auxilliary numbers table. <http://dataeducation.com/you-require-a-numbers-table/>
Select Consecutive Numbers in SQL
[ "", "sql", "sql-server", "common-table-expression", "recursive-query", "" ]
I am having some difficulties with probably a not so difficult SQL task.. I have two queries that I'd like to combine together. Both of them work fine separately, but when I try to combine them together I get different errors such as: *Error 116: Only one expression can be specified in the select list when the subque...
To get the second result list limited to bills you also find in the first query, you will have to Combine them either with IN or with EXISTS. I don't know why this didn't work for you. Maybe just a typo? The following should work. It simply combines the two statements with IN. So in the inner query I only select BC.ID ...
``` SELECT * FROM ( SELECT C.Id, C.Name, BC.Id AS BCID FROM Customers AS C RIGHT JOIN Bills AS Bc ON C.Id = BC.Bills_Customer RIGHT JOIN Months AS M ON Bc.Month_Bills = M.Id WHERE C.Argument = 'KP' AND YEAR(bm.Datum) = YEAR(CURRENT_TIMESTAMP) AND MONTH(bm.Datum) = MONTH(CURRENT_TIMESTAMP) ) as T...
Combine two separate SQL queries into one
[ "", "mysql", "sql", "" ]
I have a table for a issue tracking web app that maps issues to ticket numbers. A given issue can have (hypothetically) an infinite amount of tickets mapped to it. I want to do a SQL Query that will get an issue that might possibly have multiple tickets attached to it. For example: ``` issue_id | ticket_id ----------...
Your `tickets` table should presumably be a [Junction Table](http://en.wikipedia.org/wiki/Junction_table). However... ``` select distinct issue_id from tickets t where exists (select 1 from tickets where ticket_id = 100 and issue_id = t.issue_id) and exists (select 1 from tickets where ticket_id = 101 and issue_id...
``` select issue_id from tickets where ticket_id in (101,102) group by issue_id having count(distinct ticket_id) = 2 ```
Query for Many-To-One With AND
[ "", "sql", "sql-server", "" ]
I'm having trouble with a SQL query. My schema describes a many to many relationship between articles in the `articles` table and categories in the `categories` table - with the intermediate table `article_category` which has an `id`, `article_id` and `category_id` field. I want to select all articles which only have ...
Assuming you want more than just the article's id: ``` SELECT a.id ,a.other_stuff FROM articles a JOIN article_category ac ON ac.article_id = a.id GROUP BY a.id HAVING GROUP_CONCAT(DISTINCT ac.category_id ORDER BY ac.category_id SEPARATOR ',') = '1,2' ``` If all you want is the article's id then try thi...
You can left join `category_id` on `category.id` and then [GROUP\_CONCAT](http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/) to get all categories, like you wrote in explanation (1st table) and than using `HAVING` match with any set you like ( '1,2' from example) also with that approach you ...
MySQL Select Where In Many to Many
[ "", "mysql", "sql", "many-to-many", "" ]
These are my tables: **Table\_Bill\_Summary** `| Date | PersonId | BillNo |` **Table\_Bill\_Items** `| BillNo | ItemId | Quantity |` **Item\_MasterTable** `| ItemId | ItemName | ItemRate |` I am going to specify a PersonId. This is what I want to print: ``` SELECT * FROM Table_Bill_Summary WHERE PersonId=@X ...
``` select FLD1,FLD2,FLD3 from ( SELECT CAST(Date as varchar(10)) as FLD1 ,CAST(PersonId as varchar(10)) as FLD2, cast(BillNo as varchar(10)) as FLD3,1 as FLD4, Billno as fld5 FROM Table_Bill_Summary WHERE PersonId =@X union SELECT CAST(IM.ItemName as varchar(10)) as FLD1 ,CAST(BI.Quantity as varchar(10)) as F...
You can't do this in SQL. Instead, perform the operation in your application by fetching the joined results (bills and items) sorted by bill and keeping track of the last seen bill when iterating through the resultset: ``` string stm = @" SELECT BillNo, Date, ItemName, Quantity, ItemRate FROM Table_Bill_Summ...
Parent Select SQL Query generating Child Select
[ "", "mysql", "sql", "sql-server", "select", "" ]
I am new to Regular Expressions and any help is highly appreciated. * Pattern like W00000,W00001,W00002,W00004 * Must begin with W * Each string before comma must be six characters * String can only be repeated four times * Comma in between * Must not begin or end with comma I tried below pattern and some others, lik...
My understanding is that the OP is saying the match should *fail* if the string begins or ends with a comma, not just that the preceding or trailing commas shouldn't match, so anchors are needed. Also, based on the regex he attempted, I infer that a single group, such as `W00000`, should match. So, I think the regex sh...
Well in that case, you can do this: ``` (W[^,]{5},){3}W[^,]{5} ```
Write regex for pattern like W00001
[ "", "sql", "regex", "oracle", "" ]
I need exclude text from the **"<==#"** to the end (like %) ``` "TestDescription <==# info "dynamic text" ==>" ``` I tried use Replace with % but it does not work ``` select replace ( testfield, '<==# %', '') from table ```
The following will do what you want: ``` select left(testfield, charindex('<==#', testfield) - 1) ``` There is no reason to use wildcards for this. You only want the left part of the string before that substring.
If you want to replace `<==#` to `%`, then use ``` replace(testfield,'<==#','%') as ColName ```
How to use Replace with %
[ "", "sql", "sql-server-2008", "" ]
I am trying to complete an sql query to show how many GCSEs a student has on record.] ``` *STUDENT *SUBJECT *SCHOOL ABB13778 | English | Social Care & Early Years ABB13778 | Information and Communication Technology | Social Ca...
After grouping the data by school and student, you need to then run it through a `PIVOT` on the count of Students with each number of subjects, to get the histogram 'bins': ``` SELECT [School], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11] FROM ( SELECT School, Student, COUNT([Subject]) AS Subjects ...
`Group by` should solve this, Something like following: ``` select SCHOOL, subject, count(*) as NUM_STUDENTS from records group by STUDENT, SCHOOL; ```
SQL Count. How can I count how many distinct values are in a table when an other two columns are matching?
[ "", "sql", "sql-server", "count", "distinct", "multiple-columns", "" ]
I am facing a problem with `SUM` statement. This query returns `MY_ID = 1` and `QTY = 7` ``` select my_id, sum(qty) qty from ( select 1 my_id ,2 qty from dual union select 1 my_id, 5 qty from dual ) group by my_id; ``` But this one returns `MY_ID = 1` and `QTY = 5` instead of `QTY = 10`. ``` select my_id, ...
Use union all: ``` select my_id, sum(qty) qty from ( select 1 my_id ,5 qty from dual union all select 1 my_id, 5 qty from dual ) group by my_id; ```
Try using union all: The below works: ``` select my_id, sum(qty) qty from ( select 1 my_id ,5 qty from dual union all select 1 my_id, 5 qty from dual ) group by my_id; ``` this is because 5 union 5 is always 5. if you do union all it includes everything irrespective of it being the same!
Oracle SUM returns false summary with identicals values returing from an SELECT UNION
[ "", "sql", "database", "oracle", "sum", "" ]
I have the following "Unit" table ``` Description ------------- PERCENTAGE KG * KILOMETRE KG * METRE KG * MILE KG * YARD POUND * KILOMETRE POUND * METRE POUND * MILE POUND * YARD TON * KILOMETRE TON * METRE TON * MILE TON * YARD TONNE * KILOMETRE TON...
``` DECLARE @textToDisplay varchar(50) DECLARE CurrencyCursor CURSOR FOR SELECT Patientid FROM Patient; OPEN CurrencyCursor FETCH NEXT FROM CurrencyCursor into @textToDisplay; WHILE @@FETCH_STATUS = 0 Begin SET @textToDisplay = CASE @textToDisplay --line 1 ...
Why not simply use nested replace? ``` SELECT REPLACE(REPLACE(Description, '*', '/'), 'PERCENTAGE', '%') ```
Cursors in SQL Server not functioning
[ "", "sql", "sql-server", "cursor", "" ]
I'm pretty stuck at the moment due to by lack of SQL knowledge! I have two tables with the following criteria: ``` Table1 UPC Country Table2 UPC Country ``` I need to see all of the rows in Table 1 with the corresponding UPC from Table two and where a country is missing from table 2. So for example: ``` UPC...
Use an outer join. The following statement gives you all records of table 1 and the matches of table 2. If no match is found, you get NULL values: ``` select * from CPRSLRScheduled cprs left outer join R2LRDig r2 on cprs.UPC = r2.upc and cprs.country_iso_code = r2.country_id ```
``` select t1.upc,t1.country,t2.upc,t2.country from table1 t1 inner join table2 t2 on t1.upc=t2.upc where t2.country IS NULL ```
Joining two tables and need to return results which have same ID but different criteria
[ "", "sql", "" ]
I'm trying to list all the Products that have had no sales. I'm really close but I'm trying to use the NOT EXISTS statement to display all the ProductID's that are in the Product table, but not in the Orderline table; and hence have no sales. My code is as follows; ``` SELECT product.productid FROM product JOIN orderl...
You can avoid the Subselect by simply doing a `LEFT JOIN`: ``` SELECT product.productid FROM product LEFT JOIN orderline USING (productid) WHERE orderline.productid IS NULL ORDER BY product.productid ``` `LEFT JOIN` will list *all* rows in `product` even when there is no JOIN partner in `orderline`. In that case all ...
If you must use `not exists`, try this: ``` SELECT * FROM product p WHERE NOT EXISTS ( SELECT 1 FROM orderline o WHERE p.productid = o.productid ) ORDER BY p.productid ```
SQL - Products with No Sales
[ "", "mysql", "sql", "" ]
I have this table ``` f_id | user_id | sent ============================== 1 | 1 | 0 1 | 2 | 1397820533 1 | 3 | 0 1 | 4 | 1397820533 2 | 1 | 1397820533 2 | 2 | 1397820533 2 | 3 | 1397820533 3 | 1 | 1397820533 3 | 2 | 1...
You are close, but you want to move the condition to the `having` clause: ``` SELECT f_id FROM table GROUP BY f_id HAVING SUM(sent = 0) = 0; ``` The `having` clause counts the number of rows with `sent = 0`. The `= 0` means there are none of them.
``` SELECT Distinct f_id FROM table WHERE sent >= 0 ```
Get ids where all values of a field have a certain value
[ "", "mysql", "sql", "" ]
I have a FK inside my table but i want to modify the parent table for the FK . so is there an alter command that can achieve this ? or i need to remove the FK and create a new one ? Thanks
Add this to your PK and it will automatically update all FKs for you: ``` ON UPDATE CASCADE ``` For full details, you can read [this article](http://technet.microsoft.com/en-us/library/aa933119%28v=sql.80%29.aspx). **EDIT** Based on your comment, if you want to change the PK data type, it depends on the change: * I...
Looks like you are looking for `alter` statement but since you didn't mention exactly what you are looking to modify; I assume that you want to change column data type size. You can do something like this (an example; say you want to change size from 10 to 15) ``` alter table sample3 alter column name varchar(15) ```...
How i can modify the Parent table for my Sql server 2008 r2 FK
[ "", "sql", "sql-server-2008-r2", "" ]
I have a user table (id,group) and need to select 1 if a user is not a member of a group. A Member can be a member of multiple groups so there may be more than one record for each ID(not unique) I can only return one(pass/fail) value and I need to basically check all of the records to see if the user is a member of 'a...
You can use `group by` and then check whether the admin group is in the list in the `having` clause: ``` select user from grp group by user having sum(case when group = 'ADMIN' then 1 else 0 end) = 0; ``` The above returns all users. You can add the `where` clause for a particular user if you like. If you want a fla...
``` SELECT 1 AS COL FROM GRP WHERE USER = 'name' AND GROUP NOT IN ('ADMIN') UNION ALL SELECT 0 AS COL FROM GRP WHERE USER = 'name' AND EXISTS ( SELECT 1 FROM GRP WHERE USER = 'name' AND GROUP NOT IN ('ADMIN') ) ```
Selecting only one result from a set
[ "", "sql", "select", "" ]
I'm trying to update a field based on a field of another table. Here is the code: ``` UPDATE h SET h.strength = c.strength FROM hesters AS h INNER JOIN campers AS c ON h.camper_id = c.id ``` Getting "#1064 - You have an error in your SQL syntax;" I'm basing my code off this answer [here](https://stackoverflow.co...
I don't know why the code from the previous linked answer didn't work, but here is what I ended up going with, from the mysql documentation on [UPDATE](http://dev.mysql.com/doc/refman/5.0/en/update.html) (search for "join"). ``` UPDATE hesters AS h,campers AS c SET h.strength = c.strength WHERE h.camper_id = c.id ``...
Try doing something like: ``` UPDATE hesters AS h INNER JOIN campers AS c ON h.camper_id = c.id SET h.strength = c.strength ``` --- ***update*** This works on [sqlfiddle](http://www.sqlfiddle.com/#!2/ff5ed3/1).
mysql update column inner join another table
[ "", "mysql", "sql", "" ]
I receive reports in which the data is `ETL` to the DB automatically. I extract and transform some of that data to load it somewhere else. One thing I need to do is a `DATEDIFF` but the year needs to be exact (i.e., 4.6 years instead of rounding up to five years. The following is my script: ``` select *, DATEDIFF (yy...
Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years. Edit: This SQL query contains several approaches to calculate the date difference: ``` SELECT CONVERT(date, GetDate() - 912) AS calcDate ,DATEDIFF(DAY, GetDate() - 912,...
All `datediff()` does is compute the number of period boundaries crossed between two dates. For instance ``` datediff(yy,'31 Dec 2013','1 Jan 2014') ``` returns 1. You'll get a more accurate result if you compute the difference between the two dates in days and divide by the mean length of a calendar year in days ov...
Calculate exact date difference in years using SQL
[ "", "sql", "sql-server", "datediff", "" ]
I created an Access front end for a SQL DB on my PC for use throughout my company. I am using a file ODBC connection and putting both the ODBC file and the Access file on a shared network drive. When I load the access file, for some reason it seems to default to using my windows login credentials and pulls in the data...
Well, I was able to narrow the issue a bit. Access for some reason keeps trying to use Windows Credentials instead of the username in my ODBC file. I can't find a way around it, but I was able to resolve the issue by creating logins on my SQL Server for the windows users that need access. I am not incredibly happy abo...
i assume you didn't install the ODBC correctly on each users PC. you should create the ODBC-definition. You can create the relevant statements directly in the registry, see this branch HKEY\_LOCAL\_MACHINE\SOFTWARE\ODBC\ODBC.INI if you give the same name as on your developer machine, then it works. that's how i ...
Access ODBC Issue: ODBC--Call failed
[ "", "sql", "ms-access", "odbc", "ms-office", "" ]
I'm trying to determine whether a product exists in the product table already. When I run this bit of tsql, it should return 1 and exit out of the proc, because the product id 7777 does not exist in the product table, but it's returning 0. If I run it without the if statement and just execute the select statement, it s...
In SQL Server, use `IS NULL` to check for a null value rather than `= null`. ``` if(@ProdID IS NULL) begin raiserror('The product does not exist',16,1) return 1 end return 0 ```
Use IS NULL operator. Also, there is no reason to write code after RAISERROR, it is not executed. ``` IF @ProdID IS NULL RAISERROR('The product does not exist',16,1) ```
Checking if a column has a null value tsql
[ "", "sql", "sql-server", "t-sql", "" ]
I was using a query in which it has both "and" and "or" logic.Here is my query, ``` select * from products_event where products_event.active > 0 and is_event_activated > 0 and is_user_activated > 0 and quantity > 0 and products_event.name like '%" . $search_keyword . "%' or prod...
You need to add brackets. Try this: ``` select * from products_event where products_event.active > 0 and is_event_activated > 0 and is_user_activated > 0 and quantity > 0 and (products_event.name like '%" . $search_keyword . "%' or products_event.short_desc like '%" . $se...
You need to respect the precedence of logical operators. `and` has precedence over `or`, as in multiplication has precedence over addition in math. Brackets make sure that your `or` condition is satisfied first. Your first query is also syntatically correct, so it is only natural that you don't see any errors. ``` se...
Did "AND" and "OR" will work in same query?
[ "", "mysql", "sql", "" ]
I have the following table `test` ``` Id Code ParentId 1 R O 2 Y O 3 P O 4 O NULL ``` I need to update `test` like that : ``` Id Code ParentId 1 R 4 2 Y 4 3 P 4 4 ...
With updates and deletes it is usually safer to first test the select: ``` select t1.*, case when t1.parentid is null then t1.id else (select top 1 t2.Id from #t t2 where t1.ParentId = t2.Code) end as new_parentid from #t t1 ``` and then do the actual update using CTE: ``` with x as ( select t1....
A direct fix is: - Put the sub-query in `()` - Make sure to specify `[test]` in that sub-query *(I've had to guess whether `ParentID` or `[code]` come from `[test]`.)* ``` update [dbo].[test] set [ParentId] = CASE WHEN [ParentId]='' THEN [Id] else (select top 1 [Id] from [dbo].[PNL] where ParentId=[test].[Code])...
Update table using case when
[ "", "sql", "sql-server", "" ]
I have a table of users eg: ``` create table "user" ( id serial primary key, name text not null, superuser boolean not null default false ); ``` and a table with jobs: ``` create table job ( id serial primary key, description text ); ``` the jobs can be assigned to users, but only for superusers...
This would work for INSERTS: ``` create or replace function is_superuser(int) returns boolean as $$ select superuser from "user" where id = $1; $$ language sql; ``` And then a check constraint on the user\_has\_job table: ``` create table user_has_job ( user_id integer references "user"(id), job_id integer r...
The only way I can think of is to add a unique constraint on `(id, superuser)` to the `users` table and reference that from the `user_has_job` table by "duplicating" the `superuser` flag there: ``` create table users ( id serial primary key, name text not null, superuser boolean not null default false ); ...
PostgreSQL check constraint for foreign key condition
[ "", "sql", "postgresql", "foreign-keys", "check-constraints", "" ]
I have a simple data set in SQL Server that appears like this ``` **ROW Start End** 0 1 2 1 3 5 2 4 6 3 8 9 ``` Graphically, the data would appear like this ![enter image description here](https://i.stack.imgur.com/c2sQK.png) What I would like to achieve is t...
Here's the **[SQL Fiddle](http://www.sqlfiddle.com/#!6/96614/2)** for another alternative. First, all the limits are sorted by order. Then the "duplicate" limits within an overlapping range are removed (because a Start is followed by another Start or an End is followed by another End). Now, that the ranges are collaps...
The key to doing this is to assign a "grouping" value to overlapping segments. You can then aggregate by this column to get the information you want. A segment starts a group when it doesn't overlap with an earlier segment. ``` with starts as ( select t.*, (case when exists (select 1 from table t2 w...
SQL - Consolidate Overlapping Data
[ "", "sql", "sql-server", "aggregate", "overlap", "" ]
I have a view called "v\_documents" where a i have a field "document\_type\_name" that is based on some fields. However the field is a string with a name. Now i want all documents where the type name is contained in another table. But... This work: ``` SELECT * FROM v_documents WHERE document_type_name IN ('PREVENTI...
This is only half an answer, but too long for a comment. I would begin by using the following query to directly compare what is in each table... ``` SELECT * FROM ( SELECT CONCAT('[', document_type_name, ']') AS document_type_name FROM v_documents GROUP BY document_type_name ) AS documents FULL ...
Try this: ``` SELECT * FROM v_documents WHERE UPPER(trim(document_type_name)) IN ( SELECT UPPER(trim(TYPE)) FROM t_types WHERE type IS NOT NULL); ```
MySQL IN() with subquery stopped working?
[ "", "mysql", "sql", "" ]
I Have 4 tables: `Position` Table: ``` | Position | PositionId | | driver | 1 | | clerk | 2 | ``` `position Skill` table: ``` | SkillId | skill | PositionId | | 1 | driving | 1 | | 2 | drifting | 1 | `...
Sorry if am wrong. What I got to know from your question is you want the workers list satisfying all the skills of the position you pass. If this is what you want you may try this: ``` var workerWithallSkill = (from u in db.workerList join x in db.workerSkillList on u.WorkerId equals x.WorkerId where ((from y in...
``` var PositionsWithSkills = (from a in Positions select new { PositionID = a.PositionId, RequiredSkills = (from b in PositionSkills where b.PositionId == a.PositionId select b.skillId).ToList() }).ToList(); var WorkersWithSkills = (from x in Workers select new { Name = x.Name, Skills = ...
how to compare string linq with sub query with another linq with sub query
[ "", "sql", "asp.net-mvc", "linq", "linq-to-sql", "" ]
When I test this request: ``` SELECT *, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb FROM (SELECT DISTINCT tab1.test1, tab2.test2 FROM TB_tab1 tab1 JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3 JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4 WHERE tab3.test5 != 'test') AS sub WH...
Why: You cannot access the aliased lineNumb column in the where clause of your select--it isn't defined in the context. How to correct: Use what you have as a subquery or CTE and select from that using your where. ``` SELECT * FROM (<you existing query without the where>) WHERE lineNumb <= 5 ```
``` SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY test1) AS lineNumb FROM ( SELECT DISTINCT tab1.test1, tab2.test2 FROM TB_tab1 tab1 JOIN TB_tab2 tab2 ON tab2.test3 = tab1.test3 JOIN TB_tab3 tab3 ON tab3.test4 = tab1.test4 WHERE tab3.test5 !='test') as sub ) as sub2 WHERE lineNumb BETWEEN 1 AND 5 ```
ROW_NUMBER and multiple JOIN
[ "", "sql", "sql-server", "" ]
I have trouble building a query which I think is actually quite easy... I have a simple table where I do a simple count, and when I'm filtering the result with a date, I would like to have zeros where there's no rows instead of no result. For example: ``` select APP_ID as APPLI, count(ID) as NB from ARCHIVE where ...
In order to make this work, you need a (distinct) list of **all** ids first. In situations like this, a subquery is preferred: ``` SELECT Archive_List.app_id, COALESCE(COUNT(), 0) as NB FROM (SELECT DISTINCT app_id FROM Archive) Archive_List LEFT JOIN Archive ON Archive.app_id = Archive_List.app_id ...
Try this: ``` select A1.APP_ID as APPLI, NVL(count(A2.ID),0) as NB from ARCHIVE A1 LEFT JOIN ARCHIVE A2 on A1.APP_ID=A2.APP_ID where A1.GROUP_ID = 'Sample' and A1.TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy') GROUP BY A1.APP_ID ```
Return zero if there are no results
[ "", "sql", "oracle", "" ]
I need an SQL function to calculate age. It has to be accurate and cover all corner cases. It is for hospital ward for babies, so age of 30 minuets is a common case. I have a looked on other answers but could not find one that deals with all cases. For example: * Baby born in 2014-04-29 12:59:00.000. * And now is ...
We can use `DATEDIFF` to get the Year, Month, and Day differences, and then simple division for the Seconds, Minutes, and Hours differences. I've used `@CurrentDate` to recreate the original request, but `@CurrentDate = GETDATE()` will return the age at time of execution. ``` DECLARE @BirthDate DATETIME DECLARE @Curr...
This query will give you date diff in minutes, ``` select datediff(mi, '2014-04-23 05:23:59.660',getdate()) ``` Then you can simply calc the `minutes/60` for `hours` and `minutes mod 60` for `minutes` ``` select datediff(mi, '2014-04-23 05:23:59.660',getdate())/60 as [Hours], select datediff(mi, '2014-04-23 05:23:59...
MS SQL Server : calculate age with accuracy of hours and minuets
[ "", "sql", "sql-server", "datetime", "datediff", "" ]
I have a view in SQL Server which uses dates to determine which tables to access data from. The problem is it only seems to work when given the date as a `varchar` like `'20120423'`. So I am trying to dynamically create this date with `GETDATE()` instead of having to use the typed out version. When I run the top `SELE...
You're getting thrown off by the quote marks, just remove them they are unnecessary. ``` SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) = '20120423' BEGIN PRINT 'VALUES ARE THE SAME' END ELSE BEGIN PRINT 'VALUES ARE NOT THE SAME' END ```
Delete the first two `'`. Try this. You are comparing `'20120423'=20120423` ``` SELECT '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'' IF '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'' = '20120423' BEGIN PRINT 'VALUES ARE THE SAME' END ELSE BEGIN PRINT 'VALUES ARE NOT THE SAME' END ``...
Convert datetime to string/varchar in SQL Server
[ "", "sql", "sql-server", "date", "" ]
I have the below data. ``` 0:00:00 0:30:00 1:00:00 1:30:00 2:00:00 2:30:00 3:00:00 3:30:00 4:00:00 4:30:00 5:00:00 5:30:00 6:00:00 6:30:00 ``` I can extract the hour the using `EXTRACT(HOUR FROM TIMESTAMP)` but this will give me 24 hours. But now I need to some different calculation where I can get numbers from `1-4...
Simply use formula **`1 + extract(hour from 2 * tm)`** - it gives your expected result exactly - obligatory [**SQLFiddle**](http://sqlfiddle.com/#!15/a193d/1).
This will give you a `double precision` result, that you can round to whatever you want: ``` 2 * (EXTRACT(HOUR FROM t) + EXTRACT(MINUTE FROM t) / 60) + 1 ``` **EDIT**: Or, as @CraigRinger suggested: ``` EXTRACT(EPOCH FROM t) / 1800 + 1 ``` For the later, `t` needs to be `TIME`, **not** `TIMESTAMP`. Use cast if nee...
Extract hours as 1 - 48 from half hour interval times
[ "", "sql", "database", "postgresql", "date-arithmetic", "" ]
I have two databases in the same server and I need to: ``` Select from table1 (in database1) the id field Where notific1=1 ``` But only the `user_id` list ``` Where in table2 (in database2) the enabled field=1 ``` Being the user\_id field in the two tables the same. I tried: ``` SELECT table1.id FROM [databa...
You can not have 2 where as you did ( since you tagged your question with Mysql) ``` WHERE users.notific1=1 AND WHERE subs.enabled=1 ``` It should be ``` WHERE users.notific1=1 AND subs.enabled=1 ``` Also while JOINING the 2 databases the syntax is ``` select * from proj1.users as y inner join project2.users f ...
For mysql, the `square brackets []` are not used for object names. Use back ticks instead ``` SELECT table1.id FROM `database1`.`table1` as users INNER JOIN `database2`.`table2` as subs ON users.user_id=subs.user_id WHERE users.notific1=1 AND subs.enabled=1 ```
Query two databases in the same server
[ "", "mysql", "sql", "" ]
Here is my query: ``` SELECT dateTime, AVG([timeTaken]) as avgtime, MAX([timeTaken]) as maxtime, COUNT(*) totalcalls FROM [Logs] WHERE csUriStem = '/REST/Issues/Issues.svc/' AND [dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND (csUserAgent != 'Fiddler' OR csUserAgent IS NULL) ``` I g...
Okay, so aggregate functions like `AVG`, `MAX`, and `COUNT` will require some sort of `GROUP BY` if there are other fields in the `SELECT` list. This is how they know what *subset* to operate on. So what you would need to do, to get this to *run*, is something like this: ``` SELECT dateTime, AVG([timeTaken]) as av...
You need to include it in a group by clause Something like this. ``` SELECT dateTime, AVG([timeTaken]) as avgtime, MAX([timeTaken]) as maxtime, COUNT(*) totalcalls FROM [Logs] WHERE csUriStem = '/REST/Issues/Issues.svc/' AND [dateTime] > DATEADD(MINUTE, -15, GETUTCDATE()) AND ...
How do I add a column into a aggregate function
[ "", "sql", "aggregate", "" ]
I'm a bit of a noobie when it come to SQL, I'm using Access 2013 and I'm trying to update a date field in one table, using id numbers from a different table to only update specific ones. The query I have is: ``` UPDATE Leadsavailable SET First_Usage_Date = '23/04/2014' from leadsavailable r inner join WorkingTable_GO...
Try this sorry im in a mobile: ``` UPDATE Leadsavailable A INNER JOIN WorkingTable_GOSH B ON A.[lead number] = B.[Lead number] Set A.[First_Usage_Date] = '23/04/2014' Where B.Type = 'GOSH'; ```
Assuming my understanding of your requirement is correct, and you want to update all records in `Leadsavailable` that have a matching record in `WorkingTable_GOSH` with `Type = 'GOSH'` then this will give you the results you're after: ``` UPDATE Leadsavailable SET First_Usage_Date = '23/04/2014' WHERE [lead number] i...
Syntax error when updating
[ "", "sql", "ms-access-2013", "" ]
I'm having trouble filling my database with plenty of records to do a speed test. Can anybody tell me which query should be faster when dealing with millions of records? I like Tomas' query the most, but won't the DISTINCT be slowing it down a lot when dealing with a bigger table? I am surprised to see that my subquer...
Is there a reason why couldn't you just add it to the WHERE conditions, without all the subquery stuff? It seems to return the same data... ``` SELECT ... FROM ... LEFT JOIN [planning] p2 ON p2.[workerId] = [worker].[intId] AND p2.[companyId] = [worker].[companyId] WHERE [worker].[companyId] = 2 AND ( [plann...
I'm not exactly familiar with T-SQL syntax, but something like the following should work: ``` SELECT [planning].[id] as planningId, [planning].[type] as planningType, [planning].[from] as planningFrom, [planning].[till] as planningTill, [planning].[busyMon] as busyMon, [planning].[busyTue] as b...
SQL - To subquery or not to subquery?
[ "", "sql", "t-sql", "" ]