Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need to select one row only which has the highest count. How do I do that? This is my current code: ``` select firstname, lastname, count(*) as total from trans join work on trans.workid = work.workid join artist on work.artistid = artist.artistid where datesold is not null group by firstname, lastname; `...
In Oracle 12, you can do: ``` select firstname, lastname, count(*) as total from trans join work on trans.workid = work.workid join artist on work.artistid = artist.artistid where datesold is not null group by firstname, lastname order by count(*) desc fetch first 1 row only; ``` In old...
You can add `order by total desc` and `fetch first 1 row only` (*since Oracle 12c r1 only*, otherwise you should use your result as temp table and `select` from it to use `rownum = 1` limitation in the `where` clause) , in case you `total` can't be the same for different groups. The other way is to add this `having` cl...
select only one row that has the highest count in sql
[ "", "sql", "oracle", "select", "" ]
What are NLS Strings in Oracle SQL which is shown as a difference between char and nchar as well as varchar2 and nvarchar2 data types ? Thank you
Every Oracle database instance has 2 available character set configurations: 1. The default character set (used by char, varchar2, clob etc. types) 2. The national character set (used by nchar, nvarchar2, nclob, etc. types) Because the default character set could be configured to be a character set that doesn't suppo...
AFAIK, `NLS` stands for `National Language Support` which supports local languages (In other words supporting Localization). From [Oracle Documentation](http://docs.oracle.com/html/B13531_01/ap_b.htm) > National Language Support (NLS) is a technology enabling Oracle > applications to interact with users in their nativ...
What are NLS Strings in Oracle SQL?
[ "", "sql", "database", "oracle", "" ]
I want to write a query that lists the programs we offer at my university. A program consists of at least a major, and possibly an "option", a "specialty", and a "subspecialty". Each of these four elements are detailed with an code which relates them back to the major. One major can have zero or more options, one opti...
I can't find simpler than this : ``` /* Replace @Programs with the name of your table */ SELECT majors.program_name, options.program_name, specs.program_name, subspecs.program_name, majors.code FROM @Programs majors LEFT JOIN @Programs options ON majors.code = options.code AND options.program_level = 'Optio...
Use sub queries to build up what you want. CODE: ``` SELECT(SELECT m.program_name FROM yourtable m WHERE m.program_level = 'Major' AND y.program_name = m.program_name) AS major_name, (SELECT o.program_name FROM yourtable o WHERE o.program_level = 'Option' AND y.program_name = o.program_name) AS Option_name, ...
Splitting SQL Columns into Multiple Columns Based on Specific Column Value
[ "", "sql", "hana", "" ]
This is a select I have: ``` select s.productid, s.fromsscc, l.receiptid from logstock s left join log l on l.id = s.logid where l.receiptid=1760 ``` with the following results: ``` |Productid |SSCC |RECEIPTID |363 |22849 |1760 |364 |22849 |1760 |1468 |22849 |1760 |1837 |22849 |1760 |384...
You have to group and count. You can use a common table expression to help simplify the query. ``` with types (sscc, type) as ( select s.sscc, case when count(s.productid) > 1 then 1 else 2 end as type from stock s where s.receiptid = 1760 group by s.sscc ) select (select count(*) from types where type =...
This should work: ``` select SUM(CASE WHEN l.cnt > 1 THEN 1 ELSE 0 END) AS type1, SUM(CASE WHEN l.cnt = 1 THEN 1 ELSE 0 END) AS type2 from ( select sum(COUNT(*)) over (partition by sscc) as cnt, sscc from logstock group by sscc ) l ``` [fiddle](http://sqlfiddle.com/#!3/860bd/1/0) This part of th...
SQL count and group items by two columns
[ "", "sql", "sql-server", "" ]
I'm not an expert with MySQL and I've problems with this Stored Procedure. I'm trying to do the SP with conditions but I don't know what is wrong here, I have a mistake: > Error Code: 1064. You have an error in your SQL syntax; check the > manual that corresponds to your MySQL server version for the right > syntax to ...
I fix my SP We have to check the declaration order 1.- variables 2.- conditions 3.- cursors 4.- handlers ``` delimiter $$ create procedure getListPrsn(IN idEquipo INT, IN tipo CHAR, IN Puesto INT) begin declare varJefe int; declare eqpSupJefe int; declare done int default 0; case tipo when "jefe" then begi...
Problem is in the part as pointed below, where you are trying to declare a local variable inside `IF .. ELSE` block. You can set the variable inside `if .. else` block but you should declare them in the beginning ``` if varJefe=1 then declare done int default 0; <-- Here ``` You should declare ...
Error 1064 in stored procedure
[ "", "mysql", "sql", "stored-procedures", "" ]
I know that I can declare a **`varchar2`** using the number of the characters that it should be able to contain. However, in an `Oracle` database on which I am working, I found that a field (named PDF) is defined as follows: ``` VARCHAR2(1 BYTE) ``` What does this mean? How many characters can it contain? Another, ...
You can declare columns/variables as varchar2(n CHAR) and varchar2(n byte). n CHAR means the variable will hold n characters. In multi byte character sets you don't always know how many bytes you want to store, but you do want to garantee the storage of a certain amount of characters. n bytes means simply the number ...
The `VARCHAR` [datatype](https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1822) is synonymous with the `VARCHAR2` datatype. To avoid possible changes in behavior, always use the `VARCHAR2` datatype to store variable-length character strings. If your database runs on a single-byte character set ...
What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?
[ "", "sql", "oracle", "varchar", "sqldatatypes", "" ]
I have a BIGINT column that I want to do a partial match on. e.g. `@search = 1` should return all records where the first number is 1 (1, 11, 100 etc). Basically the same as a varchar LIKE. I have tried: ``` DECLARE @search VARCHAR SET @search = '1' ``` and ``` SET @search = '1%' ``` And used: ``` SELECT id ...
Try this instead: ``` DECLARE @search VARCHAR(10) SET @search = '1' SELECT id FROM table WHERE CAST(id AS VARCHAR(10)) LIKE @search + '%' ``` When casting to `VARCHAR`, you should always specify the length. If you don't define a length, SQL-Server will assign one for you. Sometimes it will be `1` others it will be `...
Instead of using the `LIKE` operator try using the [LEFT](https://msdn.microsoft.com/en-us/library/ms177601.aspx) function. This will return the left part of a character string with the specified number of characters. ``` SELECT id FROM table WHERE LEFT(CAST(id AS varchar), 1) = '1' ``` I'm not certain, but I've got...
SQL Like/Contains on BIGINT Column
[ "", "sql", "sql-server", "t-sql", "" ]
I have a defined an array field in postgresql 9.4 database: ``` character varying(64)[] ``` Can I have an empty array e.g. {} for default value of that field? What will be the syntax for setting so? I'm getting following error in case of setting just brackets {}: ``` SQL error: ERROR: syntax error at or near "{" ...
You need to use the explicit `array` initializer and cast that to the correct type: ``` ALTER TABLE public.accounts ALTER COLUMN pwd_history SET DEFAULT array[]::varchar[]; ```
I tested both the accepted answer and the one from the comments. They both work. I'll graduate the comments to an answer as it's my preferred syntax. ``` ALTER TABLE public.accounts ALTER COLUMN pwd_history SET DEFAULT '{}'; ```
Empty array as PostgreSQL array column default value
[ "", "sql", "postgresql", "" ]
So if I have a table like this ``` id | value | detail ------------------- 12 | 20 | orange 12 | 30 | orange 13 | 16 | purple 14 | 50 | red 12 | 60 | blue ``` How can I get it to return this? ``` 12 | 20 | orange 13 | 16 | purple 14 | 50 | red ``` If I group by id and detail it returns both 12 | 20 |...
[SQL Fiddle](http://sqlfiddle.com/#!15/9a275/6) **PostgreSQL 9.3 Schema Setup**: ``` CREATE TABLE TEST( id INT, value INT, detail VARCHAR ); INSERT INTO TEST VALUES ( 12, 20, 'orange' ); INSERT INTO TEST VALUES ( 12, 30, 'orange' ); INSERT INTO TEST VALUES ( 13, 16, 'purple' ); INSERT INTO TEST VALUES ( 14, 50, 'red'...
This is an easy task for a Windowed Aggregate Function, ROW\_NUMBER: ``` select * from ( select t.*, row_number() over (partition by id -- for each id order by value) as rn -- row with the minimum value from t ) as dt where rn = 1 ```
In PostgreSQL how can I return the entire row that corresponds with the min of a value?
[ "", "sql", "postgresql", "min", "amazon-redshift", "" ]
``` UPDATE `productData`.`productList` SET `dateLastUpdated` = CURDATE(), `totalReviews` = 100 WHERE `productList`.`name` = 'FirstchefproUltraSharpDualJuliennePeelerVegetablePeelerStainless'; ``` This query takes 2.93 seconds and only affects a single row. The table is ~75k rows long. I don't have ...
1. Either create an index on the `name` column (as written in some comments), or 2. use an indexed column in the `WHERE` statement, e.g. the product ID if your table contains something like that.
For this query: ``` UPDATE `productData`.`productList` SET `dateLastUpdated` = CURDATE(), `totalReviews` = 100 WHERE `productList`.`name` = 'FirstchefproUltraSharpDualJuliennePeelerVegetablePeelerStainless'; ``` You want an index on `productList(name)`: ``` create index idx_productData_productList...
Single row UPDATE query in SQL takes more than 3 seconds
[ "", "mysql", "sql", "performance", "ubuntu", "" ]
I have the following SQL query: ``` SELECT ( SELECT SUM(c1) FROM t2 WHERE t1.c1 = t2.c1 AND t2.c3 = 'NEW' AND t2.c4 = TRUNC(SYSDATE) AND t2.c5 = 'N' ) SUM, ( SELECT sum(c2) FROM t2 WHERE t1.c1 = t2.c1 AND t2.c3 = 'OLD' AND t2.c4 = TRUNC(SYSDATE) ) SUM2 FROM t1 WHERE t1.c2 IN...
You could have several `sum` calls over `case` expression in `t2`, and then join that to `t1`: ``` SELECT sum1, sum2 FROM t1 JOIN (SELECT c1, SUM(CASE WHEN c3 = 'NEW' AND c4 = TRUNC(SYSDATE) AND c5 = 'N' THEN c1 EL...
You can try this: ``` SELECT SUM1.val, SUM2.val FROM (SELECT * FROM t1 WHERE t1.c2 IN ('DUMMY', 'DUMMY2')) as t1 INNER JOIN ( SELECT SUM(c1) as val FROM t2 WHERE t2.c3 = 'NEW' AND t2.c4 = TRUNC(SYSDATE) AND t2.c5 = 'N' ) SUM1 ON t1.c1 = SUM1.c1 INNER JOIN ( SELECT SUM(c2) as val ...
SQL Optimization: query table with different where clauses
[ "", "sql", "oracle", "select", "sql-optimization", "" ]
In a database table, I have two column storing date and time in this format: ``` D30DAT D30TIM 140224 75700 ``` I need update a new field where store date in the format ``` 2014-02-24 07:57:00.000 ``` How I can use a SQL query to do it?
For Postgres and Oracle (assuming those columns are varchar): ``` select to_timestamp(dt, 'yymmdd hh24miss') from ( select d30dat||' '||case when length(d30tim) = 5 then '0'||d30tim else d30tim end as dt from x ) t; ``` The `case` expression adds a leading `0` if the time part only consists of 5 digits so that th...
Try this function. Its not particularly fast or great, but converts the fields you specified. ``` CREATE FUNCTION GetDateTimeFromINT ( @Date INT, @Time INT ) RETURNS DATETIME AS BEGIN DECLARE @YearNo VARCHAR(4) DECLARE @MonthNo VARCHAR(3) DECLARE @DayNo VARCHAR(2) DECLARE @HourNo VARCHAR(2) DECLARE @MinNo VARC...
Sql Datetime convert
[ "", "sql", "date", "" ]
Say I have records like this: ``` user_id user_data_field created ------- --------------- ------- 1 some data date_a 2 some data date_b 1 some data date_c 1 some data date_d 2 some data date_e ``` What should I do to get all the user records wi...
*@khan: you solution is almost working, but the flaw is described in the comment to your answer.* The code below solves this particular issue (but still relies on the fact that the would not be duplicate `created` values for the same `user_id`): ``` subq = ( session .query(MyTable.user_id, func.max(MyTable.cr...
It sounds to me that the SQL query you're looking for would be something like: ``` SELECT user_id, MAX(created) FROM Table WHERE user_id IN (1, 2) GROUP BY user_id; ``` So now the deal is to translate it using sqlalchemy, I'm guessing something like that would do: ``` session.query(Table.user_id, func.max(Table.crea...
Get the most recent record for a user
[ "", "sql", "sqlalchemy", "" ]
I have a SQL Server table called `Test` with this sample data: ``` LineNo BaseJanuary BaseFebruary BudgetJanuary BudgetFebruary 1 10000 20000 30000 40000 2 70000 80000 90000 100000 ``` I would like to create the below structure in a SQL Server view...
``` select LineNo, 'January' as Month, BaseJanuary as Base, BudgetJanuary as Budget from test union select LineNo, 'February' as Month, BaseFebruary as Base, BudgetFebruary as Budget from test order by LineNo, Month ```
[`CROSS APPLY`](http://www.sqlservercentral.com/articles/CROSS+APPLY+VALUES+UNPIVOT/91234/) can be used to `UNPIVOT` data: ``` SELECT [LineNo], [Month], Base, Budget FROM test CROSS APPLY(VALUES -- unpivot columns into rows ('January', BaseJanuary, BudgetJanuary) -- generate row for jan , ('February', BaseFebrua...
Single row to multiple columns and rows
[ "", "sql", "sql-server", "unpivot", "" ]
I already wrote this sql statement to get person id, name and price for e.g. plane ticket. ``` SELECT Person.PID, Person.Name, Preis FROM table.flug Flug INNER JOIN table.flughafen Flughafen ON zielflughafen = FHID INNER JOIN table.bucht Buchungen ON Flug.FID = Buchungen.FID INNER JOIN table.person Person ON Buchungen...
Since you're already sorting your lines, just add a `limit` clause: ``` SELECT Person.PID, Person.Name, Preis FROM table.flug Flug INNER JOIN table.flughafen Flughafen ON zielflughafen = FHID INNER JOIN table.bucht Buchungen ON Flug.FID = Buchungen.FID INNER JOIN table.person Person ON Buchungen.PID = Person...
You need to group your result by `Person.PID` and `Person.Name` in order to select these fields in the same query where you're using aggregate function `min()`. ``` SELECT Person.PID, Person.Name, min(Preis) as Preis FROM table.flug Flug .... WHERE Flug.FID = '10' GROUP BY Person.PID, Person.Name ORDER BY 3 ASC; ```
Select MIN() in SQL
[ "", "mysql", "sql", "select", "min", "" ]
**My Question is:** > Germany (population 80 million) has the largest population of the > countries in Europe. Austria (population 8.5 million) has 11% of the > population of Germany. > > Show the name and the population of each country in Europe. Show the > population as a percentage of the population of Germany. **...
The question was incomplete and was taken from [here](http://www.sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial) This is the answer ``` SELECT name, CONCAT(ROUND((population*100)/(SELECT population FROM world WHERE name='Germany'), 0), '%') FROM world WHERE population IN (SELECT...
When using sql server in SQL Zoo, then don't use `CONCAT`: I think SQL Zoo uses a version of SQL Server that doesn't support `CONCAT` and furthermore it looks like you have to do a `CAST`. Instead concatenate with the use of '+'. Also see [this post](https://stackoverflow.com/questions/10550307/how-do-i-use-the-concat...
Sqlzoo SELECT within SELECT Tutorial #5
[ "", "sql", "select", "" ]
I need to update `image_id` in the `user_group` table with the value of `image_id2` in `view_kantech_images` where the names match. My query is returning an error: ``` update user_group set image_id = (select vkm.image_id2 from view_kantech_matched as vkm where vkm.name like user_gro...
You could use the update-join syntax instead: ``` UPDATE ug SET ug.image_id = vkm.image_id2 FROM user_group ug JOIN view_kantech_matched vkm ON vkm.name = ug.name ```
try this ``` UPDATE im SET im.image_id = image_id2 FROM user_group im JOIN view_kantech_matched gm ON im.name = gm.name ```
SQL Server 2008 update query not working
[ "", "sql", "sql-server", "database", "sql-server-2008", "sql-update", "" ]
I have an one to many table, and if there is rows that have same reference id(Paragraph ID) I want to concatenate so LoginName value have many in same row. This query does what I want it to do but there is a problem, It replaces first char. the STUFF function requires a replace value. **My question:** How can I do th...
Here is what you can use: ``` SELECT DISTINCT ParagraphID , STUFF(( SELECT N' | ' + CAST([LoginName] AS VARCHAR(255)) FROM [dbo].[CM_Signature] f2 WHERE f1.ParagraphID = f2.ParagraphID FOR XML PATH ('')), 1, 1, '') AS FileNameString FROM [dbo].[CM_Signa...
You were starting your path at position 2 instead of first ``` SELECT DISTINCT ParagraphID , STUFF(( SELECT N'|' + CAST([LoginName] AS VARCHAR(255)) FROM [dbo].[CM_Signature] f2 WHERE f1.ParagraphID = f2.ParagraphID FOR XML PATH ('')), 1, 1, '') AS File...
many rows into a single column with SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to optimize the following query, According to execution plan, the sort in the inner query has a high cost. could the following query be re-written so that its easy to read and performs well? ``` select CL.col1, CL.col2 FROM CLAIM CL WITH (NOLOCK) INNER JOIN MEMBER MEM WITH (NOLOCK) ON ME...
``` ;WITH CTE AS ( select CL.col1, CL.col2, cl.claimid FROM CLAIM CL WITH (NOLOCK) INNER JOIN MEMBER MEM WITH (NOLOCK) ON MEM.MEMID=CL.MEMID LEFT JOIN PAYVACATION PV WITH (NOLOCK) ON CL.CLAIMID = PV.CLAIMID ), CTE2 AS ( select PAYVACATION.paymentid , PAYVACATION.claimid ,ROW_NUMBER() OVER (PARTIT...
There's a couple of things you'll need to fix before we can properly answer this question. 1. Make sure the query works as it is. The version you've given us will not compile because of `payvoucher.claimid`. We can guess what it should be, but there's no use putting effort into it when it turns out to be something dif...
rewrite query to remove inner query in tsql to optimize
[ "", "sql", "sql-server", "t-sql", "query-optimization", "" ]
I recently came across vba update statements and I have been using `Recordset.Edit` and `Recordset.Update` to not only edit my existing data but to update it. I want to know the difference between the two: `recordset.update` and `Update sql Vba` statement. I think they all do the same but I can't figure which one is m...
Assuming `WHERE columnc = 20` selects 1000+ rows, as you mentioned in a comment, executing that `UPDATE` statement should be noticeably faster than looping through a recordset and updating its rows one at a time. The latter strategy is a RBAR (Row By Agonizing Row) approach. The first strategy, executing a single (val...
The SQL method is usually the fastest for bulk updates, but syntax is often clumsy. The VBA method, however, has the distinct advantages, that code is cleaner, and the recordset can be used before or after the update/edit without requering the data. This can make a huge difference if you have to do long-winded calcula...
Recordset.Edit or Update sql vba statement fastest way to update?
[ "", "sql", "vba", "ms-access", "" ]
I've managed to get the data out and include NULL values by using left outer join. This is my current query: ``` select s.user, a.id, a.datetime as date, a.total_time from steam_accounts s left outer join activity a on a.steam_id = s.id where s.user_id = 1 ``` This returns this: ![enter image description here](ht...
Alas, MySQL doesn't have `OUTER APPLY` or `LATERAL JOIN`, so it will be less efficient, than it could have been. It seems that something like this should produce what you want: ``` SELECT s.id ,s.user ,ActivityIDs.MaxActivityID ,activity.datetime as date ,activity.total_time FROM steam_accounts...
Use `max(coalesce(a.id, 0))` Any aggregation done on results with null will always return null
LEFT OUTER JOIN get max() and include NULL values
[ "", "mysql", "sql", "join", "" ]
This is the last problem I have to deal with in my application and I hope someone will help because I'm clueless, I did my research and cannot find a proper solution. I have an 'University Administration' application. I need to make a report with few tables included. The problem is in SQL Query i have to finish. Quer...
Being impatient, I think this is what you are looking for. You didn't specify which SQL Server version you're using although. ``` DECLARE @topParam INT = 3; -- Default DECLARE @student TABLE (StudentID INT); -- Just for testing purpose DECLARE @examines TABLE (StudentID INT, Grades INT); INSERT INTO @studen...
You should use the `group by` clause for counting average grades (in case `examines.grades` has an integer type, you should `cast` it to the floating-point type) for each `student.ID` and `order by` clause to limit your output to only `top` n with *highest* average grades: ``` select top(@topParam) student.ID , a...
Query including TOP and AVG
[ "", "sql", "sql-server", "average", "" ]
I was writing a mysql filter query which has a primary table and another table which holds multiple records against each record of primary table (I will call this table child). Am trying to write a query which fetches record of primary table based on its values on child table. If the child table condition is one then ...
Indeed, as AsConfused hinted, you need to two joins to TABLE2 using aliases -- `both of these are tested`: ``` -- find t1 where it has 2 and 7 in t2 select t1.* from table1 t1 join table2 ov2 on t1.id=ov2.masterid and ov2.optionValue=2 join table2 ov7 on t1.id=ov7.masterid and ov7.optionValue=7 -- f...
You can try something like this (no performance guarantees, and assumes you only want exact matches): ``` select table1.* from table1 join (select masterid, group_concat(optionvalue order by optionvalue) as opt from table2 group by masterid) table2_group on table1.id=table2_group.masterid where table2_group.opt='2,7'...
Advanced Mysql Query to get master record if two conditions matches on different rows of child records
[ "", "mysql", "sql", "database", "" ]
I have a query like this: ``` SELECT RIGHT(id, 1) id_root FROM user WHERE LENGTH(id) = 3 and LEFT(id, 1) = '0' ``` And how to convert that's query to active record in `codeigniter`. My problem is with syntax `RIGHT( id, 1 )` and also at `LEFT(id,1)='0'`
You can produce your query like this ``` $this->db->from('user'); $this->db->select('RIGHT(id, 1) id_root',false); $this->db->where('LENGTH(id)',3,true); $this->db->where('LEFT(id, 1) =','0',true); $results=$this->db->get()->result(); ``` Remember if you want to use mysql function at your select query which may break...
``` $result_arr = $this->db ->select("RIGHT(id, 1) id_root", FALSE) ->from("user") ->where( array("LENGTH(id)"=> 3, "LEFT(id, 1) =" => 0) )->get() ->result_array(); ``` Or you can simply use `$this->db->query("You SQL");` ``` $query = "SELECT RIGHT(id, 1) id...
How to convert RIGHT LEFT functions to codeigniter active record
[ "", "mysql", "sql", "codeigniter", "activerecord", "" ]
I am trying (and failing) to correctly order my recursive CTE. My table consists of a parent-child structure where one task can relate to another on a variety of different levels. For example I could create a task (this is the parent), then create a sub-task from this and then a sub-task from that sub-task and so fort...
The easiest way would be to pad the keys to a fixed length. e.g. `038,007` will be ordered before `038,012` But the padding length would have to be safe for the largest taskid. Although you could keep your `path` trimmed for readability and create an extra padded field for sorting. A somewhat safer version would be to...
If the topmost CTE (as in the below query) is your table structure then the below code could be the solution. ``` WITH CTE AS ( SELECT 7112 TASKID ,NULL PARENTID UNION ALL SELECT 7120 TASKID ,7112 ParanetID UNION ALL SELECT 7139 TASKID ,7112 ParanetID UNION ALL SELECT 7150 TASKID ,7112 ParanetID UNION ...
T-SQL Ordering a Recursive Query - Parent/Child Structure
[ "", "sql", "t-sql", "recursion", "hierarchy", "" ]
I'm trying to amend the following SQL code into a pivot table. The original data looks like so: ``` PerilCode B C BI EQ 179166451986 27296144046 9067728654 WS 182394050346 28745459712 9148728654 SL 114374574342 12703142574 293860386 TC 18...
You will need first unpivot your data, and then pivot it again: ``` SELECT * FROM (/*your current query here*/) t UNPIVOT(v FOR col IN([B],[C],[BI])) u PIVOT (MAX(v) FOR PerilCode IN([EQ],[WS],[SL],[TC],[WF],[FF],[ST])) p ```
using cross apply also we can achieve ``` declare @t table (Perilcode varchar(2),B BIGINT,C BIGINT,BI BIGINT) insert into @t(Perilcode,B,C,BI)values ('EQ',179166451986,27296144046,9067728654), ('WS',182394050346,28745459712,9148728654),('SL',114374574342,12703142574,293860386), ('TC',182394050346,28745459712,914872865...
SQL Pivot Table with SUM
[ "", "sql", "sql-server", "" ]
I have 2 tables in the same database. I want to merge them based on the common `id` column. Because the tables are too huge I am not sure if there are duplicates. How is it possible to merge these two tables into one based on the `id` and be sure that there are no duplicates? ``` SELECT * FROM table1,table2 JOIN GRO...
I am not sure What exactly do you want but anyway, this is your code ``` SELECT * FROM table1,table2 JOIN GROUP BY id ``` i just edit your query ``` SELECT * FROM table1 JOIN table2 on table2.id = table1.id GROUP BY table1.id // here you have to add table //on which you will be group by at this moment this is t...
What do you mean by merging two tables? Do you want records and columns from both the tables or columns from one and records from both? Either way you will need to change the join clause only. You could do a join on the columns you wish to ``` SELECT DISTINCT * FROM table1 tb1 JOIN table2 tb2 ON table1.id =...
Merge two tables to one and remove duplicates
[ "", "mysql", "sql", "sql-merge", "" ]
I have an Orders table with the Date\_ordered column. I am trying to select the average price of all of the items ordered that were purchased in the month of December. I used ``` select *, avg(price) from orders where monthname(date_ordered) = "december" ``` However it is only coming up with one result, when my tab...
When you put `avg()` into the `select`, you turn the query into an aggregation query. Without a `group by`, SQL *always* returns on row. If you want the average as well as the other data, then use a `join` or subselect: ``` select o.*, oo.avgp from orders o cross join (select avg(price) as avgp from orders where ...
`avg()` in your query is a group function. If there is no `GROUP BY` clause in your query, it causes the group function to be applied on all selected rows. So you are getting average of the four prices in that field. And the average is only one.
Mysql: Searching for data by month only yields one result not all of them
[ "", "mysql", "sql", "" ]
I've a database value that when inserted into a SQL variable, shows with question mark at the end !! can't find a reason?! ``` declare @A varchar(50) = 'R2300529‏' select @A ``` Results: `R2300529?` any explanation? i'm using `SQL server 2012`.
There is unrecognizable character in your string: ![enter image description here](https://i.stack.imgur.com/FTTyY.png) that is giving that `?`. Delete the value and retype, see my screenshot above.
I'm assuming you copy/pasted this value from somewhere. Either that, or you're making some brain teaser here. But copy/pasting the exact script you supplied reveals an additional character: 0x3F, which is a `?` based on the Hex to ASCII conversion. I'd recommend just retyping your script and not copy/pasting.
SQL varchar variable inserts question mark
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I am trying to convert IP addresses from numeric (eg 4183726815 ) to the actual traditional IP display (eg 192.168.1.230) in MS SQL Server. I have found other code (below), however I then get an error. ``` CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS bigint) RETURNS varchar(15) AS BEGIN DECLARE @Octet1 tinyint ...
Change variable declaration from `Tinyint` to `Bigint` as: ``` DECLARE @Octet1 bigint DECLARE @Octet2 bigint DECLARE @Octet3 bigint DECLARE @Octet4 bigint ```
The line: SET @RestOfIP = @IP - (@Octet1 \* 16777216) Is treating the constant 16777216 as an int and then expecting the multiplication result to be int. You need to tell it that it will be bigint. ``` SET @RestOfIP = @IP - (@Octet1 * CONVERT(bigint, 16777216)) ```
Convert IP's in Numeric to traditional IP display
[ "", "sql", "sql-server", "ip", "" ]
TBL\_Transaction type: ``` Credit Debit ``` TBL\_Account Type: ``` 1 Saving Account 2 Loan Account 3 NRI Account ``` TBL\_Transaction: ``` Sr. Name AccType TransType DateOfTransaction Amount 1 mano saving credit 2014/12/01 5000 2 john Loan Debit 2014/1...
try this query ``` SELECT NAME,ACCOUNTTYPENAME WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' OR (TRANSACTIONTYPENAME LIKE 'CREDIT%' and (TRANSACTIONTYPENAME LIKE 'DEBIT%' and DateOfTransaction ='2014/12/01')) GROUP BY NAME,ACCOUNTTYPENAME ```
Try this ``` SELECT NAME,ACCOUNTTYPENAME,........... WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' AND TRANSACTIONTYPENAME NOT LIKE 'DEBIT%' GROUP BY NAME,ACCOUNTTYPENAME ```
How to use like and NOT like for same field in SQL server
[ "", "sql", "sql-server", "" ]
I'm currently working on a report that shows me all postcodes covered by our sales team. Each team covers over 100 postcodes. What I would like to do is create a report that brings back the clients within the postcode. Currently, my code looks like this. ``` SELECT * FROM tbl_ClientFile WHERE CLNTPOST1 LIKE ('B79%')...
``` WITH CTE AS ( SELECT VALUE FROM ( VALUES ('B79'), ('BB1'), ('BB10'), ('BB11'), ('BB12'), ('BB18'), ('BB2'), ('BB3'), ('BB4'), ('BB5'), ('BB6'), ('BB8'), ('BB9'), ('BB94'), ('BD1'), ('BD10'), ('BD11'), ('BD12'), ('BD13'), ('BD14'), ('BD15'), ('BD16'), ('BD17'), ('BD18'), ('BD19'), ('BD2'), ('...
One of possible solutions. Create a table `Prefix(v varchar(4))` where you insert those values. Then a solution would be: ``` SELECT * FROM tbl_ClientFile cf JOIN Prefix p on cf.CLNTPOST1 LIKE p.v + '%' ``` To exclude duplicates if some prefix includes some another prefix like `BB1`, `BB10`, `BB15`...: ``` SELECT D...
SQL Multiple LIKE Statements
[ "", "sql", "sql-server", "t-sql", "variables", "sql-like", "" ]
I am looking for a "better" way to perform a query in which I want to show a single player who he has played previously and the associated win-loss record for each such opponent. Here are the tables involved stripped down to essentials: ``` create table player (player_id int, username text); create table match (winne...
### Query The query is not as simple as it looks at first. The shortest query string does not necessarily yield best performance. This should be **as fast as it gets**, being as short as possible for that: ``` SELECT p.username, COALESCE(w.ct, 0) AS won, COALESCE(l.ct, 0) AS lost FROM ( SELECT loser_id AS player_...
Solution with correlated subquery: ``` SELECT *, (SELECT COUNT(*) FROM match WHERE loser_id = p.player_id), (SELECT COUNT(*) FROM match WHERE winner_id = p.player_id) FROM dbo.player p WHERE player_id <> 1 ``` Solution with `UNION` and conditional aggregation: ``` SELECT t.loser_id , SUM(CASE ...
Add up conditional counts on multiple columns of the same table
[ "", "sql", "postgresql", "join", "aggregate-functions", "" ]
I want to find all the dealers who haven't had an order in 2015 yet. I know this query doesn't work but I thought it might be helpful to understand what I want to do. In this example I want to get just "Bob" as a result. He is the only dealer in this example to not have an order in 2015 yet. ``` SELECT d.`name` FROM ...
``` select d.`name` from z_dealer d where (select count(*) from z_order o WHERE o.promo_code = d.promo_code AND o.date_ordered > '2015-01-01') = 0 ```
``` SELECT d.`name` FROM z_dealer d LEFT JOIN z_order o ON (d.promo_code = o.promo_code) WHERE o.promo_code IS NULL AND o.date_ordered > 2015-01-01 00:00:00 ``` Date value between ' ' is read as a string value not a DateTime. So above code works. And if you want your result "Bob" remove Where cl...
How do I find records in one table that do exist in another but based on a date?
[ "", "mysql", "sql", "" ]
**mytable.timecreated** is a BIGINT column on a SQL Server 2008 R2 database and it contains a unix timestamp. This query: ``` SELECT DATEADD(s,mdl_user_enrolments.timestart,'19700101 02:00') as TheDate FROM mytable ``` gives me the date in this format: ``` 2015-05-30 20:30:05.000 ``` How do I retrieve just the Mon...
How about using `datename()`? ``` select (datename(month, dateadd(second, timecreated, '19700101 02:00')) + datename(year, dateadd(second, timecreated, '19700101 02:00')) ) ``` I'm leaving `02:00` in this because that is how you phrased your question. THe correct conversion, though, would use `00:00`,...
There are some built in `CONVERT` functions you can use. I don't know if there is one for the specific format that you want, but 106 is close enough that can be combined with the `RIGHT` function to get what you want, like this: ``` SELECT RIGHT(CONVERT(VARCHAR(11),mdl_user_enrolments.timestart,106), 8) as MyDate FROM...
Extract Month-Year from a unix timestamp
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I am writing a query to get all players for all teams. Instead of looping in the application, I decided to get the players of all teams in a single query using `array_agg()`. I have written the query as follows: ``` SELECT team_id, array_agg(team_name) AS teamname, array_agg(player_id||'##'||player_name) AS pla...
It was actually a mistake from my part... the answer to my first question lies in that query itself. I just have to enclose the `(array_agg(team_name))[1]`, earlier I tried it without the brackets. ``` SELECT team_id, (array_agg(team_name))[1] AS teamname, array_agg(player_id||'##'||player_name) AS playerdetails ...
Very simply, do not aggregate the `team_name` but `GROUP BY` it: ``` SELECT team_id, team_name, array_agg(player_id||'##'||player_name) AS playerdetails FROM team JOIN players ON team_id = player_team GROUP BY team_id, team_name; ```
Return first element in array_agg()
[ "", "sql", "postgresql", "" ]
I am trying to reference the **a.pointer** inside a subquery but it looks like mysql doesn't allow to reference fields outside a subquery. ``` UPDATE order_items AS a SET a.id_parent = ( SELECT id FROM(( select id from order_items as b where (b.pointer = a.pointer) and (b.id_parent = 0)) )x) WHERE a.id_parent >...
Looks like you are trying to do a self join here; something like ``` UPDATE order_items a JOIN order_items b ON b.pointer = a.pointer AND b.id_parent = 0 SET a.id_parent = b.id WHERE a.id_parent > 9999; ```
Try using a join for this ``` UPDATE order_items as a SET a.id_parent = b.id JOIN(select id from order_items as c where c.id_parent = 0) b ON b.pointer = a.pointer WHERE a.id_parent > 9999 ```
Reference field outside the subgroup (Unknown column in where clause)
[ "", "mysql", "sql", "database", "subquery", "" ]
Here's my current situation: I'm presented with a long list of data, containing names and values, with a corresponding value ID. The number of IDs can be varying for data presented, but is constant for the whole set. (This set will have exactly 2 Values per name). The thing is, the names repeat, but the IDs do not. My...
You can using pivot for this as example. Take a look at this code snippet: ``` SELECT pvt.Name, pvt.[1] as Value1, pvt.[2] as Value2 FROM yourTable PIVTO ( MAX(Value) FOR id IN([1],[2]) ) as pvt ``` You'll just need to add your additional id's to the `IN()` and the `SELECT`. If you need a dynamic pivot, you ...
If you can be sure that the set will only ever have two values and these will always have an `ID` of either 1 or 2, you could do something like the following: ``` CREATE TABLE #Table (Name VARCHAR(5), ID INT, Value INT) INSERT INTO #Table VALUES ('Sam', 1, 15), ('Sam', 2, 6), ('Bob', 1, 9), ('Bob', 2, 11) SELECT t.N...
Microsoft SQL Server: Adding New Column To Row Instead Of Repeated Values
[ "", "sql", "sql-server", "" ]
I have this mysql table structure: ``` ------------------------------------ | item_id | meta_key | meta_value | ------------------------------------ 159 category Bungalow 159 location Lagos 159 price 45000 160 category Bungalow 160 location Abuja 160 p...
If you are looking to find the records matching with both the criteria here is a way of doing it ``` select `item_id` FROM `item_meta` where ( `meta_key` = 'category' and `meta_value` = 'Bungalow' ) or ( `meta_key` = 'location' AND `meta_value` = 'Lagos' ) group by `item_id` having count(*)=2 ```
**Try as below with brackets otherwise you will not get expected result :** ``` SELECT `item_id` FROM `item_meta` WHERE (`meta_key` = 'category' AND `meta_value` = 'Bungalow') OR (`meta_key` = 'location' AND `meta_value` = 'Lagos') ```
MySQL: Select several rows based on several keys on a given column
[ "", "mysql", "sql", "database", "" ]
I have two tables, one an abbreviated calendar: ``` create table dbo.calendar ( [date] datetime ) insert into dbo.calendar values ('20150101 00:00:00 AM') -- 1/1/15 insert into dbo.calendar values ('20150102 00:00:00 AM') -- 1/2/15 insert into dbo.calendar values ('20150103 00:00:00 AM') -- 1/3/15 insert into dbo...
1. Create a table that contains all the possible dates in the range, @alldates 2. Then insert your missing records with something like this: Query ``` INSERT INTO dbo.timeclock SELECT id ,d.punchtime ,'no time entered' FROM ( SELECT DATE ,id FROM @alldates d CROSS JOIN ( SELECT DIS...
I would create a trigger that auto-populates your `dbo.timeclock` table when you insert into `dbo.calendar` with the default value `no time entered`. Then when you update your `dbo.timeclock` table use another trigger to remove this value after the addition of new values to the table. This will automatically handle wh...
How can I create missing date records for each employee based off a limited calendar?
[ "", "mysql", "sql", "t-sql", "" ]
I need to find entries in my SQL table that always and only appear in a certain value. For example: ``` DeviceID Transmission -------- ------------ 000329 Inventory 000980 Inventory 004406 Starting 000980 Stopping 000329 Inventory 004406 Inventory ``` Now I need to find all Device...
You can select all `Transmission = 'Inventory'` ids and filter out those exist in `Transmission in('Starting', 'Stopping')`: ``` select distinct(DeviceID) from YourTable WHERE Transmission = 'Inventory' and DeviceID not in ( select distinct(DeviceID) from YourTable WHERE Transmission in('Starting', 'Stopping') ); ``...
You can use `NOT EXISTS` to exclude DeviceID's that also have Starting or Stopping. ``` select DeviceID from tablename t1 where not exists (select 1 from tablename t2 where t1.DeviceID = t2.DeviceID and t2.Transmission in ('Starting','Stopping')) and t1.Transmission = 'Inventory...
How to get entries from SQL that only appear in certain value?
[ "", "mysql", "sql", "" ]
I want to group `C,C++,C# and VB,VB.NET` as a different single category with summarized result. Do I need to substitute the team name into a unified value `(e.g. replace C,C++,C# into "C related")` and then do the grouping? Which one is better in terms of performance? do i need to use Store procedures? Can someone ple...
I would have another table that maps the language to a language family. That is, Java would map to a value of, say, 1, the C-related to 2, and the VB-related to 3. Then, you can join the two tables and group by the language family. This should perform better than grouping by the strings. If you are interested in improv...
You can use a `group by` query with a `case` statement: ``` select (case when team in ('C', 'C++', 'C#') then 'C related' when team in ('VB', 'VB.NET') then 'VB related' else team end) as team, room, count(*) from table1 group by (case when team in ('C', 'C++', 'C#') then 'C re...
How to group two categories as a one group in SQL
[ "", "sql", "sql-server", "" ]
I have a **query** that gives: ``` itemid deadlineneeded delievrydate quantity 200 15/07/15 14/07/15 5 200 15/07/15 14/07/15 10 200 15/07/15 13/07/15 25 201 15/07/15 14/07/15 30 200 14/07/15 10/07/15 3 201 15/07/15 15/07/15 100 ``` It gives...
``` SELECT itemid, deadlineneeded, sum(quantity) AS total_quantity FROM <your table> WHERE (deadlineneeded - delievrydate)::int >= 1 GROUP BY 1, 2 ORDER BY 1, 2; ``` This uses a "delievrydate" (looks like a typo to me) that is *at least* 1 day before the "deadlineneeded" date, as your sample data is suggesting.
``` select distinct date_trunc('day',deadlineneeded),sum from (select *,sum(quantity) over (partition by deadlineneeded-delievrydate) from tablename) t where deadlineneeded-delievrydate = '1 day'; ```
postgresql complex group by in query
[ "", "sql", "postgresql", "" ]
Consider the following scenario: ``` Area Code Count BP 90-99 10 CL 78-87 10 ``` I need ten records generated for both of these. ``` Area Code BP 90 BP 91 BP 92 BP 93 BP 94 BP 95 BP 96 BP 97 BP 98 and so on. ``` In oracle, this can be easily done...
You need to have a table of numbers. This can be generated as a derived table on-the-fly: ``` select area, (substring_index(code, '-', 1) + n.n - 1) as code from (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all ...
Use number table and try this approach ``` Create table numbers(number int) insert into numbers(number) select 1 union all select 2 union all . . . select 100 select t1.area, left(code,locate('-',code)-1)*1 from table as t1 inner join numbers as t2 on 1=1 where left(code,locate('-',code)-1)*1 +number <=substring(cod...
How to generate multiple records for every record in a table using a column value in MySQL?
[ "", "mysql", "sql", "database", "loops", "iteration", "" ]
I am trying to write a query that would allow me to get a list of companies that were created this month that at least would have one order. I have two tables dbo.Companies and dbo.Orders They are linked by CompanyID I have written a partial script but I cannot figure out how to complete it. ``` SELECT COUNT(*) FROM...
The query is relatively straightforward: ``` SELECT COUNT(*) FROM dbo.Companies WHERE Month(CreatedDateTime) = MONTH(getDate()) AND YEAR(CreatedDateTime) = YEAR(getDate()) AND EXISTS (SELECT 1 FROM dbo.Orders WHERE Orders.CompanyID = Companies.CompanyID) ``` You can also use an Inner Join on Companies and Orders. ...
`EXISTS` solution: ``` SELECT * FROM dbo.Companies c where Month(CreatedDateTime) = MONTH(getDate()) and exists (select 1 from dbo.Orders o where o.CompanyID = c.CompanyID) ``` `JOIN` version: ``` select distinct c.* FROM dbo.Companies c JOIN dbo.Orders o ON o.CompanyID = c.CompanyID WHERE Month(Cr...
SQL Select All Companies that have been created this month with at least one order
[ "", "sql", "sql-server", "select", "" ]
Please look at the below tables and result. Check my query and help me to get the result as below. ``` Table : incident ---------------- incident_id usr_id item_id 10059926 191 61006 Table: act_reg -------------- act_reg_id act_type_id incident_id usr_id act_type_sc 454244 1 1005...
If i understand your requirement you want only rows from table `incident` and an additonal column if there are attchments, which is the case if there is at least one record in table `act_reg` with the same `incident_id` + `usr_id` and `act_type_sc=ADD_ATTCHMNTS`. I would use `CASE WHEN EXISTS`: ``` SELECT incident_id...
Something like this should help ``` SELECT incident.incident_id,incident.usr_id,incident.item_id, 'Yes' Attachemt FROM incident where exists (select * from act_reg where incident.incident_id = act_reg.incident_id and act_reg.act_type_sc = 'ADD_ATTCHMNTS' ...
SQL Join Query Selection
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I know we can simply create a new table and copy the old table by doing ``` select * into tbl2 from tbl1 ``` i would like to check if table tbl2 exists, if it does then copy all the rows, if it doesn't then create a new one without having to specify the column names in tbl2 since I'm copying all the columns from tbl2...
``` IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tbl2')) BEGIN -- tbl2 exists, so just copy rows INSERT INTO tbl2 SELECT * FROM tbl1; END ELSE BEGIN -- tbl2 doesn't exist, so create new table tbl2 and copy rows SELECT * INTO tbl2 FROM tbl1; DROP tbl1; ...
``` If object_id ("tempdb..#tbl2") is null Select * into #tbl2 from tbl1 Else Insert #tbl2 select * from tbl1 ``` If you don't want it to be temp table get rid of # and tempdb
copy table and drop it
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "stored-procedures", "" ]
I have two SQL tables: `users` & `userGroup` with data like: **users**: ``` user | age | gender testUserA, 25, Male testUserB, 30, Female testUserC, 35, Male ``` **userGroup**: ``` user | group testUserA, groupA testUserB, groupA testUserC, groupB ``` How would I phrase a query to ...
All you need is a `join` and a `where` clause to filter `gender` and `group`: ``` select u.user from user u join userGroup ug on u.user = ug.user where u.gender = 'Male' and ug.group = 'groupA' ```
This query would join the two tables together and also filter by gender. ``` SELECT u.User, u.Gender, ug.Group FROM user u INNER JOIN userGroup ug ON u.user = ug.user WHERE u.gender = 'Male' AND ug.Group = 'groupA'; ```
SQL query for matching a column across two tables
[ "", "sql", "" ]
I have the following `Group By` SQL: ``` SELECT s.Login_Name, COUNT(s.s1CIDNumber) FROM [dbSuppHousing].[dbo].[tblSurvey] s group by s.Login_Name ``` I want to know how I can join this result set to another table(`tblUsers`) to add user\_id to the result set (`tblSurvey` and `tblUsers` have 1-1 relationship on L...
You have mistake here `from tblUsers u,a.Login_Name` try to move this piece of code `a.Login_Name` to select ``` Select u.User_Id, a.Login_Name from tblUsers u inner join (SELECT s.Login_Name Login_Name, COUNT(s.s1CIDNumber)as abc FROM [dbSuppHousing].[dbo].[tblSurvey] s group by s.Login_Name) a on u.Login_N...
Your `from` clause is in the wrong place: ``` Select u.User_Id, a.* from tblUsers u inner join (SELECT s.Login_Name, COUNT(s.s1CIDNumber) as abc FROM [dbSuppHousing].[dbo].[tblSurvey] s GROUP BY s.Login_Name ) a ON u.Login_Name = a.Login_Name; ``` 
How to join result of a Group by Query to another table
[ "", "sql", "t-sql", "" ]
I have a `projects` table with the following columns `id`, `project_name`, `remix_of` A project can be a remix of another project and the id of the project being remixed is stored in the `remix_of` column ``` id | project_name | remix_of ---------------------------- 1 | 1st Project | 0 2 | 2nd Project | 0 3 | 3...
You can do this with a `left join` or correlated subquery: ``` select p.project_name, (select count(*) from projects pr where pr.remix_of = p.id) as remixes from projects p order by remixes desc; ```
``` DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,project_name VARCHAR(20) NOT NULL ,remix_of INT NULL ); INSERT INTO my_table VALUES (1,'1st Project',NULL), (2,'2nd Project',NULL), (3,'3rd Project',2), (4,'4th Project',1), (5,'5th Project',2); SELECT x.project_nam...
Order table based on specific column count
[ "", "mysql", "sql", "laravel", "" ]
I have a table that displays hits on a link for a every day a long with an "origin" column ``` hitdate originid hitcount ================================== 2011-01-05 2 25 2011-01-05 3 3 2011-04-06 2 1 2011-04-06 6 11 2011-05-0...
I think a possible source of trouble with using `datepart(qq, ...` as the other answers do is that (1) this doesn't seem to account for the possibility of the date set spanning multiple years, and (2) it makes assumptions about the earliest date in your data set. I've tried to write a solution that will work for any st...
Use DATEPART to break the date into quarters. As your 3 month periods are not standard quarters (Jan-Mar, Apr-June), you can use DATEADD in order to offset your hitdate so that it falls in the appropriate three month period: ``` Select DATEPART(qq,dateadd(mm,1,hitdate)) as QRTR, originid, SUM(hitcount) from tablename ...
How to query data for every x month in SQL?
[ "", "sql", "sql-server", "" ]
I'm new to SQL, so forgive me if I am understanding this incorrectly. I have one table named Employees, where I have columns for: ``` EmployeeID - This is Int Identity (1,1) FirstName LastName ``` I have a second table named Calendar, with the calendar information populated for the next 50 years. Columns are: ``` F...
Better to add ID in you Calender table so your schema should be something like this![enter image description here](https://i.stack.imgur.com/T3y07.png) *Note :* in EmployeeDate table you dont need to add FirstName or LastName because you have EmployeeID which references to Employee table where you can easy get those f...
You need to avoid duplicating data between tables, and instead do a join in your query. The link exists with the employee ID in the Calender table, so you don't need the third table. Roughly speaking, your query would look something like this: ``` select c.fulldate, e.employeeid, e.firstname, e.lastname (other columns...
Newbie to linking SQL tables
[ "", "sql", "sql-server", "" ]
I have two SQL tables (I am using SQLite). ``` Table1 (code TEXT) Table2 (code TEXT, codeTable1 TEXT) ``` How can I fetch all the table1's content which has at least one row in the table 2 with the codeTable1 not null?
I think you want a correlated subquery: ``` select t1.* from Table1 t1 where exists (select 1 from Table2 t2 where t2.code = t1.code and t2.codeTable1 is not null ); ``` This seems like a pretty direct translation of your requirements.
A simple join should do it: Here's the query: ``` select * from table1 join table2 on table1.code = table2.table1_code where table1.code is not null ``` Here's the full example: ``` use example; drop table if exists table1; drop table if exists table2; create table table1 ( code varchar(64) )...
How to select columns in a table which have values not null in another table
[ "", "sql", "sqlite", "" ]
I am trying to retrieve data from one table and then insert it into another table. This is a a sample of the first table in which there is the following data. tb1 is the table which consists of data. The two columns Manager and TeamLeader basically means for example : Josh is managed by Vik and so on. An employee can a...
``` INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee...
You have to do it in two steps. One to create all your ID fields. Then you can join with this table to match up the employee to find the manager and the manager's ID: ``` insert into MyNewTable (Name, ParentID) select Manager, ParentID from tbl1 union select Employee, ParentID from tbl1 update MyNewTable set MyNewTa...
Retrieve data from one table and insert into another table
[ "", "sql", "asp.net", "sql-server", "" ]
I've got a database that contains release versions of software and I want to be able to pull back all versions that are greater than the current version, ordered by version number. However, the releases are sorted in a custom (but standard) way - from alpha version to beta version to main release to patch. So here's an...
Here is my code example. Not the shortest one but it holds many demo input/output and can be further simplified if you understand what I want. ``` CREATE TABLE #versions(version nvarchar(10)) INSERT INTO #versions(version) VALUES(N'100a1'),(N'100a4'),(N'100b1'),(N'100p1'),(N'100'),(N'101'),(N'101p3') -- Just an exam...
As long as you can actually describe how the ordering is supposed to work, sure. The two basic approaches are: * Convert the value into something ordinal. For example, you could use something like `order by left([Version] + '__', 5)`. Making a single integer out of the more complex value also works. * Separate the va...
SQL greater than custom ordering
[ "", "sql", "sql-server", "" ]
How to write query for this result? I need output of `EXP_POINT` value in between with find middle value of this `PKT_NO` wise. Means that near by value find. ![enter image description here](https://i.stack.imgur.com/yIZ1R.jpg) ``` SELECT * FROM TABLE_MAIN T1 CROSS APPLY ( SELECT * FROM TABLE_SUB xT2 WHERE ...
My solution assumes that there can be any number of rows in `TABLE_SUB`. I have assumed that when you specify the middle row, that you mean that the rows are sorted by `EXT_POINT`, if this is not what you need you will have to amend the `ORDER BY` clause of the `PARTITION` statement in the `RowOrderPerPkt CTE`. If the...
``` declare @t table (PKT INT,EXT DECIMAL(10,3)) insert into @t (PKT,EXT)values (1101,0.508),(1102,1.998) declare @tt table (PKT INT,EXT DECIMAL(10,3)) insert into @tt (PKT,EXT)values (1101,0.504),(1101,0.505),(1101,0.510),(1102,1.990),(1102,1.995),(1102,2.005) select * from @t T CROSS APPLY (select ROW_NUMBER()OVER(...
How to write query for this using between in SQL Server 2008?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to do a SQL query for user with certain permission `enabled` flag. I know, I can do this: ``` select u.ID, u.Name, (select p.Value from Permissions p where p.UserID = u.ID AND p.Key = 'CanEdit') as IsPermissionEnabled from Users u ``` But it's not exactly what I need, can I do something like...
Try this query ``` select u.ID, u.Name, case when p.value>0 then 'True' else '' end as IsPermissionEnabled from Users u left join permission p on p.UserID = u.ID and p.key='CanEdit' ```
Surely you should just join to the table to get `p.Value`. Then you can do with it whatever you like: ``` SELECT u.ID, u.Name, p.Value as IsPermissionEnabled FROM Users u LEFT OUTER JOIN Permissions p ON p.UserID = u.ID AND p.Key = 'CanEdit'; ```
SQL Subquery column equals operation
[ "", "sql", "sql-server", "t-sql", "" ]
I am working with two sql queries that I would like to combine as one so the result of the first query would be in the first column and the result of the second one in column two. How can I acheive this? I tried union, but it will put the results in two rows.. thats not what I want... ``` select count(*) as ColumnA f...
You can use combine two sub-queries in one query like this: ``` select (select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='new') as New, (select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='used') as Used ``` What were you trying to achieve with order by statement?
You can obtain both counts at the same time with a little bit different query, which will be slightly more efficient than combining two queries: ``` SELECT SUM(CASE WHEN i.condition = 'new' THEN 1 ELSE 0 END), SUM(CASE WHEN i.condition = 'used' THEN 1 ELSE 0 END) FROM Inventory i JOIN Sale s ON i.vin =...
Combining the results from two separate queries in to two columns
[ "", "sql", "sql-server", "" ]
I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the `SHOP` has one `PRODUCT` and a `PRODUCT` has many `SHOP`s, the problem is that the product is the same but the price is different. Example: ``` 3 shops sells one fork. Shop 1: ...
Ideally what you want is a many-to-many relationship between your `Shop` and `Product` entities: ``` public class Shop { public int ShopId {get; set;} public virtual ICollection<ShopProduct> ShopProducts {get; set;} } public class Product { public int ProductId {get; set;} public string Name {get; set...
I would create 3 tables for that ``` Table Shop - ShopId (PK) - Name - ... Table Product - ProductId (PK) - Name - ... Table Price - ShopId (FK) - ProductId (FK) - Price - Date (optional if you want price history) ``` If you want price history then fields `ShopId, ProductId, Date` have to form unique cons...
Database object with different data
[ "", "sql", "asp.net", "asp.net-mvc", "database", "entity-framework-6", "" ]
I have a query to display the year value from a table and default the current year. ``` select distinct year(startdate) as syear, year(startdate) as eyear, 1 as sOrder from [TTS].[dbo].[Class] where year(startdate) <> year(getdate()) union all select year(getdate()) as syear, year(getdate()) as eyear, 0 as sOr...
SQL Server is correct in what it's doing as you are requesting an additional row to be returned which if ran now 2015-06-22 would return "2016" Your distinct only works on the first select you've done so these are your options: 1) Use cte's with distincts ``` with subq1 (syear, eyear, sOrder) as (select year(getdate(...
Replace your code (where you tried to find the current year) with the below one should work. ``` SELECT YEAR(DATEADD(MM,-4,GETDATE())) + 1 like SELECT DISTINCT year(startdate) AS syear ,year(startdate) AS eyear ,1 AS sOrder FROM [TTS].[dbo].[Class] WHERE year(startdate) <> year(getdate()) UNION ALL SELEC...
Default the year based on month value
[ "", "sql", "sql-server", "" ]
I have found answers regarding searching for duplicates of an entry in one column, but I want to search for duplicates of a combination of entries of two columns. I have the columns 'Area', 'Status', and 'Update Date' as parts of my table. There are 3 different areas and 2 statuses, but there are duplicates among comb...
You can use the `rank` window function to assign a rank per unique combination of `area` and `status`, and then take the first (=earliest) one for each: ``` SELECT _id, area, status, update_date FROM (SELECT _id, area, status, update_date, RANK() OVER (PARTITION BY area, status ...
You can use a subselect for this, as example. ``` SELECT DISTINCT update_dat._id, h.area, h.status, update_dat.update_date FROM history h OUTER APPLY( SELECT TOP 1 _id, update_date FROM history m WHERE m.area = h.area AND m.status = h.status ORDER BY update_date ) as update_dat WHERE h.area in ('a', '...
Can I write an SQL query to filter duplicate entries of a combination of columns?
[ "", "sql", "sql-server", "select", "" ]
I have the following data: ``` Name | Condition Mike | Good Mike | Good Steve | Good Steve | Alright Joe | Good Joe | Bad ``` I want to write an if statement, if `Bad` exists, I want to classify the name as `Bad`. If `Bad` does not exist but `Alright` Exists, then classify as `Alright`. If only `Go...
An Access query would be easy if you first create a table which maps *Condition* to a *rank* number. ``` Condition rank --------- ---- Bad 1 Alright 2 Good 3 ``` Then a `GROUP BY` query would give you the minimum *rank* for each *Name*: ``` SELECT y.Name, Min(c1.rank) AS MinOfrank FROM [You...
You can use a case statement to rank the conditions then max() or min() to summarize the results before returning them back to the user in the same format. Query: ``` SELECT [Name] , case min(case condition when 'bad' then 0 when 'alright' then 1 else 2 end) when 0 then 'bad' when 1 then 'alright' when 2 then 'good' ...
Aggregate Text data using SQL
[ "", "mysql", "sql", "sql-server", "ms-access", "" ]
I'm trying to write a simple "undo"-system for a table with the following structure: ``` id element position start_date end_date 1 1 23 01/01/2015 05/01/2015 2 2 36 01/01/2015 NULL 3 1 17 05/01/2015 NULL ``` So, when a new action i...
That should give you the latest start\_date to every entry which has the same value in element like the defined value in update statement. So you need to change it only at one place. ``` UPDATE [table] t SET t.end_date = NULL WHERE t.element = 1 AND t.start_date = (select max(sub.start_date) from [table] sub where sub...
One method is to use a subquery with `TOP` and `ORDER BY`: ``` update t set end_date = NULL from (select top 1 t.* from table t order by start_date desc ); ``` This will update only one row. If you want all rows with the maximum start date, then use `with ties` in the subquery.
Update where column has highest value
[ "", "sql", "sql-server", "" ]
Can someone help me with a sql query? I'm looking for the most recent date (datum). It has the same OBJID but not the same RADOMGID. ``` BESADR ARSMEDEL METOD DATUM FNR BYGGID OBJID RADOMGID bladv 410 spar 20040930 40014686 1 14778 13640 bladv 340 m 1...
Do a `GROUP BY`, with `MAX` to find each OBJID's max datum: ``` select OBJID, max(DATUM) from tablename group by OBJID ``` If you want the whole row (with max datum), use `NOT EXISTS` to exclude older rows: ``` select * from tablename t1 where not exists (select 1 from tablename t2 where t2.OBJID =...
If you want just the latest, assuming the table is called my\_object\_list ``` select BESADR, ARSMEDEL, METOD, max(DATUM) DATUM, FNR, BYGGID, OBJID, RADOMGID from my_object_list mol Where Objid = '14778' group by BESADR, ARSMEDEL, METOD, FNR, BYGGID, OBJID, RADOMGID having max(datum) = mol.datum; ```
SQL query, MAX date, group by
[ "", "sql", "oracle", "" ]
I'm trying to retrieve the event ID and endDate from a list that includes multiple endDates for the same ID. That step was easy enough using max() and grouping, but where I am struggling is then restricting those results to only those where the max end date has already passed. I believe this requires the use of nested...
Use the having clause instead of where to filter based on aggregate formulas such as max(): ``` SELECT event.ContentID ,max(event.EndDate) AS EndDate FROM event GROUP BY event.ContentID HAVING max(event.EndDate) < getdate() ```
On SQL-Server you could use this: ``` SELECT event.ContentID, max(event.EndDate) as EndDate FROM event GROUP BY event.ContentID HAVING MAX(event.EndDate) <= GETDATE() ``` on MySQL: ``` SELECT event.ContentID, max(event.EndDate) as EndDate FROM event GROUP BY event.ContentID HAVING MAX(event.EndDate) <= CURDATE() ```
SQL nested select, simple issue
[ "", "sql", "" ]
I have two tables ``` Users(user_id, name) Competition(comp_id, user_id, score) ``` I need to select user\_id that occur the most in competition. Can I do it with max(count)? Is there any way to get exception if two users have same most occurances? I tried: ``` SELECT MAX(numberr), USER_ID FROM ( ...
You can get it done with `COUNT`: ``` SELECT * FROM (SELECT USER_ID,COUNT(comp_id) as numberr FROM COMPETITION GROUP BY USER_ID ORDER BY COUNT(comp_id) DESC) T1 WHERE rownum=1; ```
To get *multiple* users with the max count use a RANK: ``` SELECT numberr, USER_ID FROM ( SELECT USER_ID, COUNT(COMP_ID) AS numberr ,RANK() OVER (PARTITION BY USER_ID ORDER BY COUNT(COMP_ID) DESC) rnk FROM COMPETITION GROUP BY USER_ID ) dt WHERE rnk = 1; ```
select id that occur the most
[ "", "sql", "oracle", "count", "max", "" ]
Either get only those userIDs with the specified @Lastname or if @LastName = 'All' then get all userIDs even if they have NULL values as their LastName. ``` SELECT userID INTO #table FROM users WHERE LastName = CASE WHEN @LastName = 'All' THEN LastName ELSE @LastName END ``` The ...
Another shorter form `where @LastName in ('All', LastName);` [SqlFiddle](http://sqlfiddle.com/#!9/d7a58/9)
Change your condition to this instead: ``` where (@LastName = 'All' and 1=1) or (LastName = @LastName) ``` The idea is that when `@LastName` = 'All' then your query should not have any filters. The 1=1 condition will be always true, and together with the other check should return all results. The other path the query...
WHERE If condition is not met get all values including NULL
[ "", "mysql", "sql", "" ]
I am trying to join two tables one is a unique feature the seconds is readings taken on several dates that relate to the unique features. I want all of the records in the first table plus the most recent reading. I was able to get the results I was looking for before adding the shape field. By using the code ``` SELEC...
You can do the aggregation on `Table2` in a CTE, finding the `MAX(DATE)` for each ID, and then join that result to `Table1`: ``` WITH AggregatedTable2(ID, MaxDate) AS ( SELECT ID, MAX(DATE) FROM Table2 GROUP BY ID ) SELECT t1.ID, t1.Name, t1.Shape, t2.MaxDate FROM Table...
Try casting geometry as a varchar. ``` Select Table1.Name, Table1.ID, cast(Table1.Shape as varchar(1)) AS Shape, Max(Table2.DATE) as Date FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = table2.ID Group By Table1.Name, Table1.ID, cast(Table1.Shape as varchar(1)) ```
Joining two sql tables with a one to many relationship, but want the max of the second table
[ "", "sql", "sql-server", "max", "outer-join", "" ]
I have two tables with the same number of columns with no primary keys (I know, this is not my fault). Now I need to delete all rows from table A that exists in table B (they are equal, each one with 30 columns). The most immediate way I thought is to do a `INNER JOIN` and solve my problem. But, write conditions for a...
Try this: ``` DELETE a FROM @A a WHERE EXISTS (SELECT a.* INTERSECT SELECT * FROM @B) ``` Delete from @A where, for each record in @A, there is a match where the record in @A intersects with a record in @B. This is based on Paul White's [blog post](http://web.archive.org/web/20180422151947/http://sqlblog.com:80/blo...
To answer your first question you can delete based on `join`: ``` delete a from @a a join @b b on a.value = b.value and a.username = b.username ``` The second case is really strange. I remember similar case here and many complaints about this behaviour. I will try to fing that question.
DELETE WITH INTERSECT
[ "", "sql", "sql-server", "sql-server-2012", "sql-delete", "intersect", "" ]
I've got a dataset similar to the test data below: ``` create table #colors (mon int, grp varchar(1), color varchar(5)) insert #colors values (201501,'A','Red'), (201502,'A','Red'), (201503,'A','Red'), (201504,'A','Red'), (201505,'A','Red'), (201506,'A','Red'), (201501,'B','Red'), (201502,'B','Red'), (201503,'B','Bl...
I'd take a different approach, and generally I'd avoid "predefining" the number of months in the columns (if possible). Here's a solution that can work for separating months into rows, but it actually then combines the result into the expected output format: ``` WITH nCTE (mon, grp, color, n) AS ( SELECT *, ROW_NUMB...
Using a slightly different approach, with first using the lead window function to determine if the color changed, and only then ranking the rows, based on where the color changed: ``` ;with nextcols as ( select grp, color, mon, lead(color, 1, 'none') over (partition by grp order by mon ) nextcol from #colors ) , ...
Finding max value prior to a change between n categories across a window for m>n changes between categories
[ "", "sql", "sql-server", "group-by", "window-functions", "" ]
I have the query: ``` SELECT substring(Code,1,6) as Code From Table Group by substring(Code,1,6) Order By Code ``` However I'm trying to add a column that is the calculated sum of the rows that have been grouped in this query. Example: ``` Code Number S05080A 20 S05080B 20 S70331A 8 S70331B 4 ``` Would then ...
``` SELECT substring(Code,1,6) as Code, SUM(Number) AS [Sum] -- Add this line From Table Group by substring(Code,1,6) Order By Code ```
You've already done the hard work - simply add `SUM(Number)` as another column and alias it ``` SELECT substring(Code,1,6) as Code, SUM(Number) AS Sum From Table Group by substring(Code,1,6) Order By Code ```
Calculating the sum of rows that have been grouped in SQL
[ "", "sql", "sql-server", "" ]
I hope you will be able to help me out. I just started learning SQL and while applying my knowledge at work, I got stuck.I have SQL Database with multiple tables, which contain various data for properties of the items offered for sale. So far I successfully created a query which pulls most of the information needed. Un...
Move the propertyname filter to the ON clause from the WHERE clause. Then join again for each property: ``` SELECT si.ItemNumber, si.ItemTitle, si.ItemDescription, si.RetailPrice, si.Weight, sl.Quantity, c.CategoryName, style.ProperyValue as style, size.ProperyValue as size FROM StockItem si LEFT OUTER JOIN StockLevel...
To get each value in a column like that, you can first write a subquery for each property, and then `JOIN` them all together, like this: ``` SELECT m1.fkStockItemId, m1.propertyValue AS 'Item Style', m2.propertyValue AS 'Item Size', m3.propertyValue AS 'Item Color' FROM( SELECT fkStockItemId, propertyValue FROM my...
How to create a SQL query for the following operation?
[ "", "mysql", "sql", "database", "qsqlquery", "isqlquery", "" ]
I have the following piece of code that's just to make sure that the temporary table doesn't exist. If the table exist I want to truncate it. ``` CREATE TABLE #LookupLinks( [SyncID] uniqueidentifier, [Name] nvarchar(50), [SQLTable] nvarchar(50) ) --I create this just to test my try-catch B...
This is because SQL Server parses and validates the whole batch. So when parsing the second `CREATE TABLE` statement, it errors out saying: > There is already an object named '#LookupLinks' in the database. See this example: ``` IF 1 = 1 BEGIN CREATE TABLE #temp(col INT) END ELSE BEGIN CREATE TABLE #temp(col...
I think what you really want to achieve is this: ``` IF OBJECT_ID('tempdb..#LookupLinks') IS NOT NULL --Table already exists BEGIN TRUNCATE TABLE #LookupLinks PRINT N'#LookupLinks already existed and was truncated.'; END ELSE BEGIN CREATE TABLE #LookupLinks( [SyncID] uniqueidentifier, [Na...
TRY...CATCH doesn't seem to work
[ "", "sql", "sql-server", "error-handling", "sql-server-2012", "try-catch", "" ]
I am executing a dynamic SQL query. where parameters are passed dynamically. I first wrote similar to following code. ``` DECLARE @Id nvarchar(max); DECLARE @query nvarchar(max); SET @Id ='RMH_108' SET @query ='Select * FROM [A06].[Syn_RMDemand] WHERE RMHierarchyId =' + @Id PRINT @query EXEC...
No need to convert it to NULL just check with your value ``` DECLARE @Id nvarchar(max); DECLARE @query nvarchar(max); SET @Id = '' -- COMMENTED SET @Id ='RMH_108' SET @query ='Select * FROM [A06].[Syn_RMDemand] WHERE RMHierarchyId = '''+@Id+'''' PRINT @query EXEC(@query) ```
You should use `sp_executeSQL` and remove string concatenation like this. I am assuming that if `NULL` is passed you want all the rows to be returned. **Query** ``` DECLARE @Id nvarchar(max); DECLARE @query nvarchar(max); SET @Id ='RMH_108'SET @query ='Select * FROM [A06].[Syn_RMDemand...
Passing Null value parameter to dynamic SQL query. How can this be successfully executed?
[ "", "sql", "sql-server", "" ]
I need filter result of a join query between two tables but I don't have a condition for the "where clause". What I need is to filter based on id\_project like this: 1. if id\_project is equal to 24 *(24 is the default project)* then it should return only rows with id\_project =24. **here rows 1,3...10 will be sel...
Thinking a little more about your request, it burns down to: For every id\_tag give me the ID requested, or 24 if not available. This can be done in one query, where you use a ranking with ROW\_NUMBER, in which you prefer the requested ID over the 24. ``` select * from ( select tp.*, row_number() over(partit...
So depending of whether the user asks for ID 24 or not there are two different queries to execute. Here is the query for ID 24: ``` select * from tag_project where id_project = 24; ``` Here is the query for @OTHERID. We use UNION ALL to combine the 24 records with the @OTHER records. And we use NOT EXISTS in order t...
conditional where clause
[ "", "sql", "sql-server", "inner-join", "" ]
![myTable](https://i.stack.imgur.com/fTfRB.png) Basically I have a table name myTable and inside has Name,Class , I would like to sort them out like the table below with a count of each name and number of 1,2,3s they have.Below is the codes I currently had but it work on small amount of entries, if the table has 20,00...
It is classic conditional aggregation: ``` Select Name, sum(case when Class = 1 then 1 else 0 end), sum(case when Class = 2 then 1 else 0 end), sum(case when Class = 3 then 1 else 0 end) from myTable group by Name ```
Do a `GROUP BY` with conditional counting: ``` select Name, count(case when class = 1 then 1 end), count(case when class = 2 then 1 end), count(case when class = 3 then 1 end) from `myTable` group by Name; ``` **Note:** `DISTINCT` is not a function on a column, it works on the whole selected rows...
mySQL count table efficiently
[ "", "mysql", "sql", "database", "" ]
I'm trying to find similar values from an array -not just one, but a group of them, while the sum of their element-wise differences is to be the lowest possible value EXAMPLE: 0 2 4 6 8 9 11 15 16 19 pick 5 numbers RESULT: 4 6 8 9 11 or 2 4 6 8 9 Where the sum of the element-wise difference of both groups is 7....
[SQL Fiddle](http://sqlfiddle.com/#!15/a3f63/18) **PostgreSQL 9.3 Schema Setup**: A small dataset of random data: ``` CREATE TABLE test ( id INT, population INT ); INSERT INTO TEST VALUES ( 1, 12 ); INSERT INTO TEST VALUES ( 2, 11 ); INSERT INTO TEST VALUES ( 3, 14 ); INSERT INTO TEST VALUES ( 4, 6 ); INSER...
This solution should work. Row\_number() to get the order. self-Join on +1499, then order by the difference of sizes in the pair. ``` DECLARE @cities TABLE ( city VARCHAR(512) ,size INT ,rownum INT ) INSERT INTO @cities SELECT * ,row_number() OVER ( ORDER BY size ) rownum FROM ...
Find group of N similar numbers in group of N+M numbers
[ "", "sql", "algorithm", "" ]
I have following SQL which should throw an error: > Ambiguous column name since `conferencetitle` column is in 2 tables; `course` and `coursesession`. Please note im selecting this column only once. ``` SELECT CourseSessionID, CourseSessionNum, usrCourseSessionNum, CourseSession.ConferenceTitle, ...
> Changing the order by clause fixes this;but i need to find why the > error is not there on other databases even though i run the same query > on them which have same db structure. The behavior has changed between SQL Server 2000 and SQL Server 2005. Read the Microsoft answer to the following connect item for more d...
The problem is in the `ORDER` statement where you don't specify which `ConferenceTitle` to use: ``` ORDER BY PageNumber, ConferenceSortOrder, StartDate, StartTime, LinkedSessionID, Course.ConferenceTitle ```
SQL Server doesn't detect ambiguity
[ "", "sql", "sql-server", "sql-server-2008", "" ]
(SQL Server 2012 being used) I found some topics on query optimization, and comparing EXISTS to COUNT, but I couldn't find this exact problem. I have a query that looks something like this: ``` select * from tblAccount as acc join tblUser as user on acc.AccountId = user.AccountId join tblAddress as addr on acc.Accou...
Did you try running the original query with TOP 1? most likely it will be just as slow. Sometimes when the optimizer thinks that something is very likely and going to return a vast set of data with little effort (i.e. almost all records are going to get returned), it chooses mostly loop joins because it only needs to ...
I've fought this issue as well. The query was 10ms when I ran it on its own but once I put it in the If Exists it went to 4 minutes. No matter what I tried it didn't go back to 10ms. The issue was re-produced on 4 different servers but not on 2 servers. Servers all had the same db backup and same patch level of mssql ...
SQL Server: IF EXISTS massively slowing down a query
[ "", "sql", "sql-server", "sql-server-2012", "query-optimization", "exists", "" ]
I am having Following data in table ``` Country State RequestStatus India MP 0 India MP 1 Usa At 0 Usa At 0 ``` How to get All the Completed, Pending and total request with Country and state wise grouped in MSSql query. ``` 0: Pendint 1: Complete ``` Out put should be someth...
``` SELECT Country,State , COUNT(* ) AS Total ,SUM(CASE WHEN RequestStatus = 0 THEN 1 ELSE 0 END ) AS Pending ,SUM(CASE WHEN RequestStatus = 1 THEN 1 ELSE 0 END ) AS Complete FROM @Test T GROUP BY Country,State ```
Use this: ``` select country, [state], count(*) as Total, sum(case when requeststatus = 0 then 1 else 0 end) as Pending, sum(case when requeststatus = 1 then 1 else 0 end) as Complete from tbl group by country, [state] ``` We first group by the country and state to get aggregated data. Then, for calculating the to...
How to Use where Clause in Count function
[ "", "sql", "sql-server-2008", "" ]
I have data like this ``` --------------------------- | code | other column --------------------------- | C | a | null | a | A | a | null | a | null | a ---------------------------- ``` How can i write query to get row\_number without counting null column. ``` -----...
Well, not specifically. But you can get what you want by using conditional logic: ``` select (case when code is not null then row_number() over (partition by (case when code is not null then 1 else 0 end) order by . . . ) end...
If you need to order on code (descendent in your example) with NULLs last: ``` select decode(code,null,null,row_number() over (order by code DESC NULLS LAST)) rn, code from test; ``` If you need to order on OTHER column: ``` select decode(code,null,null,row_number() over (order by decode(code,null,null,'x') ...
Can row_number() ignore null in oracle
[ "", "sql", "oracle", "" ]
I have a lists of names **John, Rupert, Cassandra, Amy**, and I want to get names which are not exists in table: **Cassandra, Amy** How should I write such query? My table: ``` +----+--------+-----------+------+ | id | name | address | tele | +----+--------+-----------+------+ | 1 | Rupert | Somewhere | 022 | ...
Think in sets. You add names to a the result set with UNION ALL, you remove names from the result set with EXCEPT. ``` select 'John' union all select 'Rupert' union all select 'Cassandra' union all select 'Amy' except select name from mytable; ```
Build up a list of your names to check and do a left join to the `users` table: ``` with to_check (name) as ( values ('John'), ('Rupert'), ('Cassandra'), ('Amy') ) select tc.name as missing_name from to_check tc left join the_table tt on tt.name = tc.name where tt.name is null; ``` SQLFiddle example: <http...
Rows which do not exist in a table
[ "", "sql", "postgresql", "" ]
I have this variable of a string, which I can use to filter for certain days of the week, or the whole weekend using ``` where datepart(dw,date) in (@weekday) ``` where I declare `@weekday` as `nvarchar` When I have `@weekday = '1'` or any single day it works perfectly but when I try `@weekday = '1,7'` it fails to c...
You can't use this that way. You only have these options: 1. to run the whole script in a dynamic SQL statement, which would be bad. 2. change your where to something like that: `where datepart(dw,date) = @weekday1 OR datepart(dw,date) = @weekday2` 3. change your `nvarchar` variable to a table variable, insert 1 and 7...
You are attempting to use `@weekday` as if you had a piece of dynamic SQL, such that your where clause would be: ``` where datepart(dw, date) in (1, 7) ``` However, what is actually happening is: ``` where datepart(dw, date) in ('1, 7') ``` This is trying to compare `datepart(dw, date)` to `'1, 7'` which is obvious...
SQL Server filter for weekend only in variable
[ "", "sql", "sql-server", "" ]
I am trying to write an SQLite statement to get the closest datetime from an user input (from a WPF datepicker). I have a table IRquote(rateId, quoteDateAndTime, quoteValue). For example, if the user enter 10/01/2000 and the database have only fixing stored for 08/01/2000, 07/01/2000 and 14/01/2000, it would return 08...
To get the closest date, you will need to use the **[strftime('%s', datetime)](https://www.sqlite.org/lang_datefunc.html)** SQLite function. With [this](http://sqlfiddle.com/#!5/40935/5) example/demo, you will get the most closest date to your given date. Note that the date `2015-06-25 10:00:00` is the input datetim...
If the table is big, and there is an index on the datetime column, this will use the index to get the 2 closest rows (above and below the supplied value) and will be more efficient: ``` select * from ( select * from ( select t.ID, t.Price, t.PriceDate from Test t where t.PriceDate <= datetime(...
SQLite query to get the closest datetime
[ "", "sql", "sqlite", "datetime", "" ]
I'm dumbfounded that this question has not been asked meaningfully already. How does one go about creating an equivalent function in SQL like `LTRIM` or `RTRIM` for carriage returns and line feeds ONLY at the start or end of a string. Obviously `REPLACE(REPLACE(@MyString,char(10),''),char(13),'')` removes ALL carriage...
Find the first character that is *not* `CHAR(13)` or `CHAR(10)` and subtract its position from the string's length. **LTRIM()** ``` SELECT RIGHT(@MyString,LEN(@MyString)-PATINDEX('%[^'+CHAR(13)+CHAR(10)+']%',@MyString)+1) ``` **RTRIM()** ``` SELECT LEFT(@MyString,LEN(@MyString)-PATINDEX('%[^'+CHAR(13)+CHAR(10)+']%'...
Following functions are enhanced types of `trim` functions you can use. Copied from [sqlauthority.com](http://blog.sqlauthority.com/2008/10/10/sql-server-2008-enhenced-trim-function-remove-trailing-spaces-leading-spaces-white-space-tabs-carriage-returns-line-feeds/) These functions remove trailing spaces, leading spac...
Remove only leading or trailing carriage returns
[ "", "sql", "sql-server", "string", "t-sql", "" ]
I have the following model structure: Model Visitor ``` class Visitor < ActiveRecord::Base has_many: triggers end ``` Model Trigger ``` class Trigger < ActiveRecord::Base belongs_to :visitor, :inverse_of => :triggers belongs_to :event, :inverse_of => :triggers end ``` Model Event ``` class Event < ActiveRec...
Thanks to the clue from Darpa, I eventually settled on this: ``` has_many :custom_trigger, {:class_name => "Trigger", :include => :event, :conditions => ["triggers.some_column >= events.another_column"]} ```
Make sure you first add the correct association between `Visitor` and `Trigger` in your model setup. From there, you can add a custom association as follows: ``` class Visitor < ActiveRecord::Base has_many :approved_triggers, -> { includes(:events).where("events.something = ?", true).references(:events) }, class_nam...
has_many :condition multiple models how to use join here?
[ "", "sql", "ruby-on-rails", "join", "activerecord", "associations", "" ]
## Performance problem on update MySql MyISAM big table making column ascending order based on an index on same table My problem is that the server have only 4 GB memory. I have to do an update query like this: [previous asked question](https://stackoverflow.com/questions/19459643/mysql-update-incremented-not-auto-i...
### Tanks to every body. Yours answers help me much. I think that now I have found a better solution. This problem involve in two critical issue: * efficient paginate on large table * update large table. To go on efficient paginate on large table I have found a solution by make a previous update on the table but doi...
You can use some of this: 1. Update engine to InnoDB, it blocks only one row, not all the table on update. 2. Create #temp table with photo\_id and good orderid and than update your table from this temp: ``` update images im, temp tp set im.orderid = tp.orderid where im.photo_id = tp.photo_id ``` it w...
Update mysql big table hang too time
[ "", "mysql", "sql", "performance", "myisam", "" ]
I used `round()` function to show the file size in from byte to MB. The data was like the following- ``` file_size ---------- 2463 ``` I used this to convert- ``` round(document.file_size / (1024*1024), 3) file_size ``` Now the data is showing like this- ``` file_size ---------- .002 ``` But, what I want is like...
Try `TO_CHAR(round(document.file_size / (1024*1024), 3), 990.000) file_size` More information you can find here: <https://asktom.oracle.com/pls/apex/f?p=100:11:0::NO::P11_QUESTION_ID:2739503983093>
you want a leading zero... try this: ``` to_char(round(document.file_size / (1024*1024), 3),0999) file_size ``` <http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm>
how to show zero on the left before decimal point when using round()?
[ "", "sql", "oracle", "" ]
``` SELECT name , ( SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) - SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) ) * 5 / 100 AS Interest FROM ..... ``` This query return so...
Something like this maybe? ``` SELECT t1.name AS Name, CASE WHEN t1.Interest > 0 THEN Interest ELSE 0 END AS Interest FROM (select name, (sum(case when TransTypeName like 'credit%' then amount else 0 end) - sum(case when TransTypeName like 'Debit%' then amount else 0 end)) *5/100 as Interest from ...........) as t1 ``...
Just give this ``` select greatest(:yourval,0) ``` (Works in Azure and SQL Server 2022.)
How to convert negative value into zero
[ "", "sql", "sql-server", "sql-server-2008", "" ]
So I have a table `Movement` that has a column called `IDNumber`. What I want to do is count the number of times an ID appears in `IDNumber` for each ID in that column I could do this individually for each ID like this: ``` SELECT COUNT(*)FROM movement WHERE IDNumber = 379; SELECT COUNT(*)FROM movement WHERE IDNumbe...
How about: ``` SELECT IDNumber, Count(IDNumber) FROM movement GROUP BY IDNumber ``` You didn't say it was a requirement that it be inserted into a table, right?
Try looking at the group by function with MySQL ``` SELECT COUNT(*), IdNumber FROM movement GROUP BY IdNumber; ``` You can even make it fancier by adding more conditions with a where clause ``` SELECT COUNT(*), IdNumber FROM movement WHERE IDNumber < 1000 GROUP BY IdNumber; ``` or ``` SELECT COUNT(*), IdNumber FR...
SQL - Confusion with INSERT INTO...SELECT and COUNT(*)?
[ "", "mysql", "sql", "select", "count", "sql-insert", "" ]
``` +------------+---------------+---------------+----------------+ | Product ID | Part Sequence | Part Material | Description | +------------+---------------+---------------+----------------+ | 1 | 1 | Steel | Part A | | 1 | 2 | CFK | Part B ...
Using a windowed aggregate function (requiring only a single pass over the table) rather than using a join (which will require two passes over the table): [It will also return products where there are no steel parts - if this is an issue then a similar windowed query can be use to filter those rows out.] [SQL Fiddle]...
Try below ``` Select * from product join (Select Max(Part_Sequence) as sequence,productid from product group by Productid, Part Sequence) d on product.Part_Sequence = d.sequence and product.productid = d.productid ``` if you want query for specific part just apply where clause to inner and outer query for that ...
SQL - Select rows with values greater than max value for id and category
[ "", "sql", "oracle", "" ]
This is my table sample, I had deleted a lot column. ``` id orid to_id seq 1 1 5 A12 2 2 6 A12 3 3 7 A12 4 4 _ A12 <--- I want to find this row 5 5 _ A13 6 6 _ A13 7 7 _ A13 ``` I want to find the extra data. I wan...
I found the answer. This is I want, and this is my code. ``` select b.* from (select * from ForgeRock where seq = 'A13') a right join (select * from ForgeRock where seq != 'A13') b on a.id = b.to_id where b.to_id = '_'; ``` This is [sqlfiddle](http://sqlfiddle.com/#!9/3279d/17)
I am guessing that you want to find rows that have no connection to another row. ``` select fr.* from ForgeRock fr where fr.to_id is NULL and not exists (select 1 from ForgeRock fr2 where fr.from_id = fr2.to_id ); ```
select the extra row data
[ "", "mysql", "sql", "" ]
I'm using a stored procedure with a CTE and doing some paging. I also want to return an output parameter with the total count of the returned query before my paging. My problem is that I get an error that "OrderedSet" is not a valid object name. ``` @ft INT, @page INT, @pagesize INT, @count INT OUTPUT ...
Here are 2 approaches that avoid copying and pasting all the CTEs multiple times. **Return total rows as column of result set** Benefit here is that you can calculate total rows without multiple queries and temp tables, but you have to add logic to your front end to get the total row count from the first row of the r...
Only alternative I see is repeating the query as inline view ``` select @count = numrows FROM ( SELECT count(*) as numrows, ROW_NUMBER() OVER (ORDER BY Id DESC) AS 'Index' FROM tbl_BulkUploadFiles buf WHERE buf.FileType = @ft ) XXX WHERE [Index] BETWEEN @offset AND (@offset + @pagesize) ...
SQL stored procedure SET output param using COUNT(*) ON a CTE
[ "", "sql", "sql-server", "stored-procedures", "pagination", "common-table-expression", "" ]
I am working with sql language. I want to select a `substring` from the string : `Rayan`. When I execute, `select substring(col1, 1, 5) from table1` it works fine. My question is, If I give the length of the string more than it exists, it will shown the same result? ie, `select substring(col1, 1, 6) from table1` res...
You can check the length of the column and conditionally show no output in the event that the length you are trying to select (in characters) be *greater* than this length: ``` SELECT id, CASE WHEN CHAR_LENGTH(col1) <= 10 THEN SUBSTRING(col1, 1, 10) ELSE '' END AS cond_col1 FROM table1 ``` You can replace the value `...
You are use substring function. You are specify maximum length. SUBSTRING ( expression ,start , length ) **Arguments** **expression** Is a character, binary, text, ntext, or image expression. **start** Is an integer or bigint expression that specifies where the returned characters start. If start is less than 1, th...
Select substring in sql
[ "", "mysql", "sql", "postgresql", "" ]
There are many *slightly similar* questions, but none solve precisely this problem. "[Find All Rows With Null Value(s) in Any Column](https://stackoverflow.com/questions/14488859/find-all-rows-with-null-values-in-any-column)" is the closest one I could find and offers an answer for SQL Server, but I'm looking for a way...
You can use `NOT(<table> IS NOT NULL)`. From [the documentation](http://www.postgresql.org/docs/9.4/static/functions-comparison.html) : > If the expression is row-valued, then IS NULL is true when the row > expression itself is null or when all the row's fields are null, while > IS NOT NULL is true when the row expre...
An alternative solution which **might** be of use in some edge cases could be the following (all of the code below is available on the fiddle [here](https://dbfiddle.uk/3DWDB3QB)): ## Setup: ``` CREATE TABLE t ( f1 INT, f2 INT, f3 TEXT, f4 INT, f5 TEXT -- -- arbitrary number of fields... -- ); ``` Po...
How to find all rows with a NULL value in any column using PostgreSQL
[ "", "sql", "postgresql", "" ]
I want to change a format of the dates to format HH:MI:SS PM/AM in SQL Oracle. I want to use it in case when like this: case when to\_char(a.dtime,'HH:MI:SS') >= 12:00:00 then to\_char(a.dtime,'HH:MI:SS PM') else null end as date but SQL does not want to show me all to\_char times > 12:00 but it shows only those whe...
You can use [`TO_CHAR( datetime, format )`](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions180.htm) to format a `DATE` column. The format options are given [here](http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm#i34924). This would give you the time part of a date value (12-hou...
``` SELECT to_char(sysdate,'dd/MM/yyyy hh:mi:ss am') FROM dual ```
SQL How do I extract time from a date to HH:MI:SS PM/AM?
[ "", "sql", "oracle", "" ]
I have a list of components which periodically report status. I want to write a query to find a list of the most recent status grouped by component. Typically I would use the solution described by the accepted answer for this question: [MySQL order by before group by](https://stackoverflow.com/questions/14770671/mysq...
I ended up going with the following query to solve my problem: ``` SELECT component_status.* FROM component_status JOIN (SELECT MAX(component_status_id) AS component_status_id FROM component_status JOIN (SELECT MAX(timestamp) AS timestamp, component_id ...
You can use variables to simulate ``` ROW_NUMBER() OVER (PARTITION BY component_id ORDER BY `timestamp` DESC, component_status_id DESC) ``` window function: ``` SELECT component_id, component_status_id, `timestamp` FROM ( SELECT component_id, component_status_id, `timestamp`, @row_numbe...
Find most recent record MySQL per component
[ "", "mysql", "sql", "group-by", "sql-order-by", "" ]
I have a table PostingPeriod that uses a company calendar to track all working days. Simplified, it looks like this: ``` Date Year Quarter Month Day IsWorkingDay 25.06.2015 2015 2 6 25 1 26.06.2015 2015 2 6 26 1 27.06.2015 2015 2 6 27 0 ``` I have another table that contains...
You could do this by assigning each working day an arbitrary index using `ROW_NUMBER`, e.g. ``` SELECT Date, WorkingDayIndex = ROW_NUMBER() OVER(ORDER BY Date) FROM dbo.Calendar ``` Which will give you something like: ``` Date WorkingDayIndex ----------------------------- 2015-04-27 80 2015-04-28 ...
Starting from OrderDate, the Date if you advance N(DeliveryDays) WorkingDays. If i understood correctly you want something like this: ``` select PurchID, OrderDate, ConfDelivery, DeliveryDay, myDays.[Date] myWorkingDayDeliveryDate from Purchases p outer apply ( select [Date] from (...
Add X number of Working days to a date
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Given table: ``` Agreement: id: int type: string version: int ``` Given Records like: ``` 1 | Terms | 1 2 | Terms | 2 3 | Privacy | 1 ``` I'd like a query that outputs: ``` 2 | Terms | 2 3 | Privacy | 1 ``` I've tried all manner of distinct and self joins to max(version), I just can't seem to crack it...
The easiest thing would probably be to use the `rank` window function: ``` SELECT id, type, version FROM (SELECT id, type, version, RANK() OVER (PARTITION BY type ORDER BY version DESC) AS rk FROM agreement) t WHERE rk = 1 ```
It should work: ``` select max(id) , type , max(version) from Agreement group by type ```
Select all records of type 'x' that are the highest 'version'
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
In postgresql, I have a `case` statement that I need to add a "not equals" clause. When `v1` equals v2, I want it to say 1, when `v1` **DOES NOT EQUAL** `v2`, I would like to say 2. ``` create table test ( v1 varchar(20), v2 varchar(20) ); insert into test values ('Albert','Al'),('Ben','Ben') select case ...
You could always just be more explicit with your case statement. Here's an example... ``` select case when v1 = v2 then 1 when v1 <> v2 then 2 end from test ```
First, you start by [reading the documentation](http://www.postgresql.org/docs/8.1/static/functions-conditional.html). You'll note that the SQL `case` function takes one of two forms: ``` case {expression} when {value-1} then {result-1} ... when {value-N} then {result-N} [ else {default-result} ] end ``` or ``...
Not equals when using CASE statement in SQL
[ "", "sql", "postgresql", "case", "" ]