Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
query with results as below: ``` b_id| l_id | result | Count | avg -----+------+--------- -+-------+----- 1 | 10 | Limited | 2 | 66.66 1 | 10 |Significant| 1 | 33.33 2 | 09 | Critical | 1 |100.00 ``` I am struggling to get a query right using a case statement as below: ``` SELECT DI...
Use bool\_or aggregate (At least the condition is true for one row ) : ``` SELECT b_id, l_id,CASE WHEN bool_or(result='Critical' or (result = 'Significant' AND avg >= 50) ) Then 'Critical' WHEN bool_or(result='Significant') THEN 'Significant' WHEN bool_or(result = 'Medium' AND avg >= 50) THEN 'M...
The `WHEN result = 'Significant' AND result <> 'Critical' THEN 'Significant'` issue aside\*, all three rows qualify and then one one of the first two rows gets selected because of `DISTINCT ON (b_id, l_id)`. You can't control which of the two rows will be selected, that is basically a function of how your data is organ...
case statement with pairs giving incorrect value
[ "", "sql", "postgresql", "postgresql-9.1", "" ]
I am trying to convert 3 columns into 2. Is there a way I can do this with the example below or a different way? For example. ``` Year Temp Temp1 2015 5 6 ``` Into: ``` Year Value Base 5 2015 6 ```
You could use `CROSS APPLY` and row constructor: ``` SELECT s.* FROM t CROSS APPLY(VALUES('Base', Temp),(CAST(Year AS NVARCHAR(100)), Temp1) ) AS s(year,value); ``` `LiveDemo`
This is called unpivot, pivot is the exact opposite(make 2 columns into more) . You can do this with a simple `UNION ALL`: ``` SELECT 'Base',s.temp FROM YourTable s UNION ALL SELECT t.year,t.temp1 FROM YourTable t ``` This relays on what you wrote on the comments, if year is constant , you can replace it with '2015'
SQL convert from 3 to 2 columns
[ "", "sql", "sql-server", "unpivot", "" ]
I've just set up a new PostgreSQL 9.5.2, and it seems that all my transactions are auto committed. Running the following SQL: ``` CREATE TABLE test (id NUMERIC PRIMARY KEY); INSERT INTO test (id) VALUES (1); ROLLBACK; ``` results in a warning: ``` WARNING: there is no transaction in progress ROLLBACK ``` on a **di...
autocommit in Postgres is controlled by the SQL *client*, not on the server. In `psql` you can do this using ``` \set AUTOCOMMIT off ``` Details are in the manual: <http://www.postgresql.org/docs/9.5/static/app-psql.html#APP-PSQL-VARIABLES> In that case **every** statement you execute starts a transaction until ...
``` \set AUTCOMMIT 'off'; ``` The `off value` should be in single quotes
Transactions are auto committed on PostgreSQL 9.5.2 with no option to change it?
[ "", "sql", "postgresql", "transactions", "autocommit", "" ]
I would like to group (a,b) and (b,a) into one group (a,b) in SQL For e.g the following set ``` SELECT 'a' AS Col1, 'b' AS Col2 UNION ALL SELECT 'b', 'a' UNION ALL SELECT 'c', 'd' UNION ALL SELECT 'a', 'c' UNION ALL SELECT 'a', 'd' UNION ALL SELECT 'b', 'c' UNION ALL SELECT 'd', 'a' ``` should yield ``` Col1 | Col2...
Group by a case statement that selects the pairs in alphabetical order: ``` select case when col1 < col2 then col1 else col2 end as col1, case when col1 < col2 then col2 else col1 end as col2 from ( select 'a' as col1, 'b' as col2 union all select 'b', 'a' union all select 'c', 'd' union all ...
As an alternative, you could use a `UNION` to achieve this: ``` WITH cte AS ( SELECT 'a' AS Col1, 'b' AS Col2 UNION ALL SELECT 'b', 'a' UNION ALL SELECT 'c', 'd' UNION ALL SELECT 'a', 'c' UNION ALL SELECT 'a', 'd' UNION ALL SELECT 'b', 'c' UNION ALL SELECT 'd', 'a') ...
Grouping of pairs in sql
[ "", "sql", "sql-server", "t-sql", "" ]
I can't think of a way to speed this up. It's doing a table scan but I kind of have to because I need to update ALL records... The problem is that this table has MILLIONS of records... like around 30 million. This is taking about 50 minutes to run. Anyone have any tips on how I can improve this? ``` update A se...
Here are three options. The first mentioned by Randy is to do the work in batches. The second method is to dump the results into a temporary table and recreate the original table: ``` select . . . , product_dollar_amt = round(A.product_dollar_amt, 2), product_local_amt = round(A.product_local_amt, 2),...
You really don't have any alternatives here. You are updating every single row and it's going to take as long as it takes. I can tell you though that updating 30M rows in a single transaction is not a great idea. You could easily blow out your transaction log. And if this table is used by other users, you are probably ...
is there ANY way I can improve performance on this simple query?
[ "", "sql", "sql-server", "performance", "" ]
I am fetching records from a table and it returns me a set of mixed data here is a simple query ``` SELECT code_id, atb_name_id FROM `attribute_combinations` WHERE products_id =109 ``` It returns me data like this ``` | code_id |atb_name_id| ----------------------- | 1 | 31 | | 2 | 31 | | ...
You can do the following: ``` SELECT code_id, atb_name_id, (SELECT CASE WHEN COUNT(DISTINCT atb_name_id) > 1 THEN 'no' ELSE 'yes' END FROM `attribute_combinations` ac2 WHERE products_id = ac.products_id) AS flag FROM `attribute_combinations` ac WHERE products_id =109 ```
Produce the additional information in a sub select, that you simply join to the original table: ``` SELECT ac.code_id, ac.atb_name_id, CASE WHEN f.count = 1 THEN 'yes' ELSE 'no' END AS flag FROM attribute_combinations ac INNER JOIN (SELECT products_id, COUNT(DISTINCT atb_na...
Mysql check if values are same or not
[ "", "mysql", "sql", "database", "relational-database", "" ]
I'm trying to perform the following in a stored procedure ``` DECLARE @TICKET_AGE INT SELECT @TICKET_AGE = TOP 1 (DATEDIFF(second, DATE_ENTERED, GETDATE())/60) AS TICKET_AGE FROM TICKETS ``` But it's giving error saying INCORRECT SYNTAX NEAR 'TOP' What am i doing wrong? So i've updated my code to look like below...b...
The `TOP 1` comes *before* the variable: ``` SELECT TOP 1 @TICKET_AGE = DATEDIFF(second, DATE_ENTERED, GETDATE()) / 60 FROM TICKETS ```
Not sure if it matters, but this should give you the same result and *might* perform better ``` SELECT @TICKET_AGE = MAX(DATEDIFF(second,DATE_ENTERED,GETDATE()) / 60) FROM TICKETS WHERE LOWER(STATUS_DESCRIPTION) LIKE '%new%' ```
SQL Server SELECT @VARIABLE = TOP 1
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have this string in sql 'PIERCESTOWN WEXFORD EIRE' I want only 'WEXFORD' , the search should be based on the string 'EIRE' So far I have tried ``` DECLARE @a varchar(500) SET @a='MALTON ROAD WICKLOW EIRE' SELECT charindex('EIRE',@a) SELECT SUBSTRING(@a,1,charindex('EIRE',@a)) ``` But it gives me 'MALTON ROAD WICKLO...
Try this ``` DECLARE @a varchar(500), @v varchar(500) SET @a='MALTON ROAD WICKLOW EIRE' SELECT @v = LTRIM(RTRIM(SUBSTRING(@a,1,charindex('EIRE',@a)-1))) SELECT REVERSE( LEFT( REVERSE(@v), ISNULL(NULLIF(CHARINDEX(' ', REVERSE(@v)),0)-1,LEN(@v)) ) ) ``` Result: ``` DATA RESULT -----...
``` DECLARE @a varchar(500), @x varchar(500) SET @a='MALTON ROAD WICKLOW EIRE' SELECT @x = LTRIM(RTRIM(SUBSTRING(@a,1,charindex('EIRE',@a))) SELECT REVERSE( LEFT( REVERSE(@x), CHARINDEX(' ', REVERSE(@x))-1 ) ) ```
Get the word before particular word in sql
[ "", "sql", "sql-server", "" ]
I have 3 table, I want to get Data from those table using join. This is my table structure and data in these 3 tables. I am using **MS Sql server**. [![enter image description here](https://i.stack.imgur.com/rfBwG.jpg)](https://i.stack.imgur.com/rfBwG.jpg) ``` Year Month TotalNewCaseAmount TotalNewCaseCoun...
That will do: ``` ;WITH Table1 AS ( SELECT * FROM (VALUES (2016, 'Januray', 146825.91, 1973), (2016, 'Fabuary', 129453.30, 5384), (2016, 'March', 21412.07, 3198), (2016, 'April', 0.00, 5) ) as t ([Year], [Month], TotalNewCaseAmount, TotalNewCaseCount) ), Table2 AS ( SELECT * FROM (VALUES (2016, 'Januray', 5477...
Try like this, ``` select t1.*, t2.TotalClosingAmount, t2.TotalClosingCount, t3.TotalRetrunAmount, t3.TotalReturnCount from Table1 t1 left join Table2 t2 on t1.year=t2.year and t1.month=t2.month left join Table3 t3 on t1.year=t3.year and t1.month=t3.month ```
Get Data from mutile table in sql server
[ "", "sql", "sql-server", "join", "" ]
Below are the sample tables I have to join. ``` SQL> select 'CH1' chapter , 'HELLO'||chr(10)||'WORLD' output from dual union 2 select 'CH2' chapter , 'HELLO'||chr(10)||'GALAXY' output from dual union 3 select 'CH3' chapter , 'HELLO'||chr(10)||'UNIVERSE' output from dual; CHAPTER OUTPUT --------------- ...
``` select chapter, c.output, page from table_chapters c join table_pages p on c.output like '%' || p.output || '%' order by chapter, page ``` The join condition matches if the output in the "pages" table is an exact substring of the output in the "chapters" table. I assume this is what you need. If you need the...
If the join needs to be done always on the second row of the string, you can use: ``` SQL> select chapter, a.output, page 2 from test_a A 3 inner join test_B B 4 on ( substr(a.output, instr(a.output, chr(10))+1, length(a.output)) = B.output) 5 order by chapter; CHA OUTPUT PAG --- -----...
Oracle SQL join on column with multiple Line feed (chr(10)) seperated values
[ "", "sql", "oracle", "join", "" ]
This post has been totally rephrased in order to make the question more understandable. **Settings** `PostgreSQL 9.5` running on `Ubuntu Server 14.04 LTS`. **Data model** I have dataset tables, where I store data separately (time series), all those tables must share the same structure: ``` CREATE TABLE IF NOT EXIST...
# What's happening You're probably missing rows because of the `DISTINCT ON` clause in `S1`. It appears you're using this to pick only the most recent applicable rows of `SVPOLFactor`. However, you wrote ``` DISTINCT ON(ChannelId, TimeValue) ``` while in the query `S0`, unique rows could also differ by `GranulityId`...
You already got a correct answer, this is just an addition. When you calculate start/end in a Derived Table, the join returns a single row and you don't need `DISTINCT ON` (and this might be more efficient, too): ``` ... FROM S0 LEFT JOIN ( SELECT *, -- find the next StartTimestamp = End of the current peri...
Strange behaviour with a CTE involving two joins
[ "", "sql", "postgresql", "join", "common-table-expression", "distinct-on", "" ]
``` SELECT oi.created_at, count(oi.id_order_item) FROM order_item oi ``` The result is the follwoing: ``` 2016-05-05 1562 2016-05-06 3865 2016-05-09 1 ...etc ``` The problem is that I need information for all days even if there were no id\_order\_item for this date. Expected result: ``` Date Quantity 2016-05-05 15...
You can't count something that is not in the database. So you need to generate the missing dates in order to be able to "count" them. ``` SELECT d.dt, count(oi.id_order_item) FROM ( select dt::date from generate_series( (select min(created_at) from order_item), (select max(created_at) fro...
Friend, Postgresql Count function ignores Null values. It literally does not consider null values in the column you are searching. For this reason you need to include oi.created\_at in a Group By clause PostgreSql searches row by row sequentially. Because an integral part of your query is Count, and count basically st...
How to select all dates in SQL query
[ "", "sql", "postgresql", "date", "" ]
For voyages (Years, ships), how can I group and count sailors by age intervalles in standard SQL or MS-ACCESS? ``` YEAR SHIP SAILOR_AGE 2003 Flying dolphin 33 2003 Flying dolphin 33 2003 Flying dolphin 34 2001 Flying dolphin 23 2003 Flying dolphin 35 2001 Flying dolphin 38 2001 ...
You can do it with a single query using `CASE EXPRESSION` : ``` SELECT t.years,t.ship, CASE WHEN t.Sailor_age between 21 and 40 then 'From 20th to 40th' WHEN t.Sailor_age between 41 and 60 then 'From 40th to 60th' ELSE 'Other Ages' END as Range FROM YourTable t GROUP BY t.years,t....
As this - given the tags - most likely is Access SQL, you can go like this: ``` SELECT YEAR, SHIP, INT(SAILOR_AGE / 20) * 20 AS AgeGroup, COUNT(*) As [NUMBERS] FROM TABLE GROUP BY YEAR, SHIP, INT(SAILOR_AGE / 20) * 20 ```
Group and count by age breaks
[ "", "sql", "sqlite", "ms-access", "ms-access-2010", "ms-access-2007", "" ]
Is it possible to merge these 2 left join into one? I can't think of any way ``` select left1.field1, left2.field2 from masterTable left join ( select somefield, field1, row_number() over (partition by somefield orderby otherfield) as rowNum from childTable inner join masterT...
You can use `max() over()` to get the max of field2 per somefield in the same query. ``` select left1.field1, left1.field2 from masterTable left join (select somefield,field1 ,row_number() over (partition by somefield orderby otherfield) as rowNum ,max(field2) over(partition by somefield) as field2 from chi...
Try this, but without samples of data and output I can't guarantee that it will work properly, it's just guessing. ``` SELECT field1, MAX(field2) AS field2 FROM ( SELECT ct.field1, ct1.field2, ROW_NUMBER() OVER (PARTITION BY ct.somefield ORDER BY ct.otherfield) as rn FROM mast...
merging two left join on same table into one
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I need little help with reading my "chats" SQL table. Column: ``` Chat_ID - decimal(18, 0) primary key, inflexible-yes Sent_ID - decimal(18, 0) Receive_ID - decimal(18, 0) Time - datetime Message - nvarchar(MAX) Sent_ID| Receive_ID | Time | Message -------+----------+------------------+-------...
Update: I understand now that you want to get the latest message between two users regardless if it is sent or received. If that's the case, you can use `ROW_NUMBER`: `ONLINE DEMO` ``` WITH Cte AS( SELECT *, rn = ROW_NUMBER() OVER( PARTITION BY CASE ...
Try this ``` select c.* from ( select User1id,User2id,max(time) as newtime from ( select case when sent_id < receive_id then sent_id else receive_id end as User1id, case when sent_id > receive_id then sent_id else receive_id end as User2id, time from chats where (Sent_ID = 1 o...
SQL SELECT - Chats
[ "", "sql", "select", "" ]
I am making Android app for practicing driving licence theory tests. I will have about 3000 questions. Question object would have several atributes (text, category, subcategory, answers, group). I will create them and put in app, so data won't ever change. When user chooses category, app would go througt data, look whi...
If you do not have to perform complex queries, I would recommend to store your datas in **json** since very well integrated in android apps using a lib such as [GSON](https://github.com/google/gson) or [Jackson](https://github.com/FasterXML/jackson). If you don't want to rebuild your app / redeploy on every question c...
I would recommend a database (SQLite) as it provides superior filtering functionality over xml.
Android - XML or SQLite for static data
[ "", "android", "sql", "xml", "sqlite", "" ]
I need help with a data extraction. I'm an sql noob and I think I have a serious issue with my data design skills. DB system is MYSQL running on Linux. Table A is structured like this one: ``` TYPE SUBTYPE ID ------------------- xyz aaa 0001 xyz aab 0001 xyz aac 0001 xyz aad 0001 xy...
You can join Table A with itself to find all combinations of types and subtypes with the same ID, then compare them with the values in Table B. ``` SELECT t1.type AS type1, t1.subtype AS subtype1, t2.type AS type2, t2.subtype AS subtype2, t1.id FROM TableA AS t1 JOIN TableA AS t2 ON t1.id = t2.id AND NOT (t1.type = t2...
You can use `EXISTS`: ``` SELECT a.* FROM TableA a WHERE EXISTS( SELECT 1 FROM TableB b WHERE (b.Type1 = a.Type AND b.SubType1 = a.SubType) OR (b.Type2 = a.Type AND b.SubType2 = a.SubType) ) AND a.ID = '0001' ``` `ONLINE DEMO`
SQL: Can't understand how to select from my tables
[ "", "mysql", "sql", "" ]
I've tried a lot of techniques though I can't get the right answer. For instance I have table with Country names and IDs. And I want to return only distinct countries that haven't used ID 3. Because if they have been mentioned on ID 2 or 1 or etc they still get displayed which I don't want. ``` SELECT DISTINCT test.co...
``` SELECT DISTINCT c1.name FROM countries c1 WHERE NOT EXISTS ( SELECT 1 FROM countries c2 WHERE c1.name = c2.name AND c2.id = 3 ) ```
I'm now sure I understood your question, but if you want distinct countries where id is not 3, you just need this: ``` select distinct c.name from Countries where c.id <> 3 ```
SQL Joining single table where value does not exist
[ "", "sql", "" ]
From my C# application I am getting the XML data as like below ``` '<NewDataSet> <tblCFSPFSDDeclaration> <PKCFSPFSDDeclaration>-1</PKCFSPFSDDeclaration> <FKCFSPStatus>2</FKCFSPStatus> <FKBatch>EDCCCL05070801</FKBatch> <SDWCountSubmitted>112</SDWCountSubmitted> <SDWCountAc...
I think this will solve your problem. ``` Declare the [FSDPeriod] as datetimeoffset. ``` then you can cast them as you need. If you want only date and time then try this ``` select Convert(varchar(19), cast([FSDPeriod]as datetime),120) from @tblCFSPFSDDeclaration ``` for more conversion see here [conversion helps]...
> Can anyone help to get the data as 01/Apr/2016? Change `[FSDPeriod] datetime` to `[FSDPeriod] varchar(19)` and you will extract the `datetime` value without the timezone information. That value will be implicitly converted to a `datetime` when you insert to the table variable.
Datetime field value getting reduced by 1 day while converting XML data into @table values
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I am writing a report on SQL injection attacks. I've found an example on [Owasp](https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project) as shown bellow. Since this is an example and to me, it seems as a simple query getting a row with the specific ID, does it do anything else or my assumption is correct? ```...
> to me it seems as a simple query getting a row with specific ID Thats the magic of injection. The query **should** only get a row that fits a certain criteria that comes from a request (like a GET or POST from html for example). So `request.getParameter("id")` provides a parameter submitted by the user (or a very b...
The problem with this query is that the SQL is created dynamically. Request.getparameter is probably just a function which returns the id of the row for the specific web request. But if the webpage allows filling this parameter through a text box or the function is called directly from JavaScript any value can be set ...
SQL Injection Query
[ "", "sql", "sql-injection", "" ]
**Update**: Do not provide an answer that uses `NOT EXISTS`. According to [MariaDB](http://www.techonthenet.com/mariadb/exists.php) "SQL statements that use the EXISTS condition in MariaDB are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table." This query will be used ***a lot***, ...
Here was the query that did it: ``` SELECT f.follower FROM following f LEFT OUTER JOIN association_record a ON f.follower = a.user_id AND a.poll_id = 88 WHERE f.followee = 5 AND a.user_id is null ``` Forgot to post the solution to my question after I solved it, and now a month later, I end up having a similar problem...
``` select f.follower from following f, response_record r where f.follower = r.user_id and f.followee = 5 and r.post_id = 88 and r.user_id is null ``` try this
MariaDB: Select the fields from one column in one table that are not in a subset of another column from another table
[ "", "mysql", "sql", "mariadb", "" ]
``` Dim sql As String = "SELECT * FROM old where inputdate BETWEEN '" + DateTimePicker2.Value.ToShortDateString() + "' AND '" + DateTimePicker3.Value.ToShortDateString() + "';" Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataa...
The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query. So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.
I advice you to use the `Parameter` to use `SqlDbType.DateTime` and then pass the `DateTime` directly to the parameter (do not need to convert) , and also avoid `SQL` injections , like this : ``` Dim sql As String = "SELECT * FROM old where inputdate BETWEEN @startDate AND @endDate;" Dim cmd As New SqlCommand(sql, con...
Converting Date to string with DateTimePicker
[ "", "sql", "vb.net", "datetimepicker", "datetime-format", "" ]
Let’s assume I have two tables, A and B, both with an ID column and a foreign key (value). I want to do a select based query that returns only the matching records, not including those that don't meet the condition of having the same data (`ID` and `Value` columns), also sorted by `Value` column of table B. Table A ...
That will give you desired result: ``` SELECT idDet, idEnc, idMetadata, OrderValue, [Value] FROM ( SELECT b.idDet, b.idEnc, b.idMetadata, b.OrderValue, b.[Value], ROW_NUMBER() OVER (PARTITION BY b.idEnc ORDER BY b...
You can use CTE notation ``` ;with cte as( SELECT B.*,row_number() over(partition by b.idmetadata order by b.value,b.iddet desc) rn FROM (VALUES (185442, 22008, 16, 6 ,2), (187778, 22269, 16, 6 ,2), (211260, 24925, 16, 6 ,2), (251476, 29431, 15, 4 ,1), (251477, 29431, 16, 5 ,2), (251478, 29431, 17, 6 ,3) ) as B(idDet,...
SQL Server : matching records from 2 tables with sorting
[ "", "sql", "sql-server", "" ]
I have a table called associate\_ratings with the below structure: ``` id int(11) NO PRI auto_increment associate varchar(10) NO skill_id int(11) NO MUL rating int(11) NO updated_time datetime NO ``` This table holds the skills(`skill_id`) of the associate and their...
Use temporary table and case ``` SELECT skill_id, sum(rating_1), sum(rating_2), sum(rating_3) FROM ( SELECT a.skill_id as skill_id, case a.rating when '1' then 1 else 0 end as rating_1, case a.rating when '2' then 1 else 0 end as rating_2, case a.rating whe...
``` select Skill_id , count(case when rating = 1 then 1 else null end) as Rating1_count , count(case when rating = 2 then 1 else null end) as Rating2_count , count(case when rating = 3 then 1 else null end) as Rating3_count from associate_ratings b left join associate_ratings a on b.Skill_id = a.Skill_id g...
How display the count of associates at each rating?
[ "", "mysql", "sql", "" ]
I need to sum the results of three different queries. Here's what I'm doing but the result is incorrect. If I run each query separately they are fine, but running them together I get different results. ``` select 'Inforce TIV', ISNULL(SUM(a.TSI), 0) + ISNULL(SUM(b.TSI), 0) + ISNULL(SUM(c.TSI), 0) from ( select ISN...
You're doing a cartesian join of the 3 sets of results. You have 2 options: 1. Remove all the "group by" statements 2. Include the columns your grouping by in each of the 3 selects statements, and then add a where clause when joining them together (e.g. where a.code\_suc = b.code\_suc and b.code\_suc = c.code\_suc... ...
The `group by` in the sub queries are probably causing you to get cartesian join on the results, i.e. causing wrong sum through multiplication. Maybe you could write like this? ``` select 'Inforce TIV', ISNULL(SUM(a.TSI), 0) + ISNULL(SUM(b.TSI), 0) + ISNULL(SUM(c.TSI), 0) from ( select ISNULL(SUM(p.[Suma Asegurada...
Sum the results from different queries
[ "", "sql", "sql-server", "" ]
I have a table which has the following values: ``` ID | Name --------------- 1 | Anavaras 2 | Lamurep ``` I need a query which outputs the value which doesn't have entry in the table. For e.g: If my where clause contains `id in('1','2','3','4')`, should produce output has ``` 3 | 4 | ``` for the above entries i...
You would put this into a "derived table" and use `left join` or a similar construct: ``` select v.id from (values(1), (2), (3), (4)) v(id) left join t on t.id = v.id where t.id is null; ```
First you need to split your `in` to a table. Sample split function is here: ``` CREATE FUNCTION [dbo].[split] ( @str varchar(max), @sep char ) RETURNS @ids TABLE ( id varchar(20) ) AS BEGIN declare @pos int,@id varchar(20) while len(@str)>0 begin select @pos = charindex(@sep,@str + @sep) select @id = LEF...
SQL Server : searching value doesn't have entry in table
[ "", "sql", "sql-server", "" ]
A colleague wrote this piece of SQL (SQL Server 2012): ``` SELECT a.account_id ,(SELECT SUM(e.amount) FROM event e WHERE e.event_type_id <> 47 AND e.master_comm_id = (SELECT c.comm_id FROM comm c WHERE c.item_id = a.item_id ...
Top 1 works, but only if the data is ordered (per below SO) You mentioned you tried MIN, but where? This may work (you are very close): ``` SELECT a.account_id ,(SELECT SUM(e.amount) FROM event e WHERE e.event_type_id <> 47 AND e.master_comm_id = (SELECT **MIN**(c.comm_id) ...
Try this one. Since I don't have sample data, I cannot check, but it looks obvious - select only top 1, while the select list is ordered by the ID ascending... ``` SELECT a.account_id ,(SELECT SUM(e.amount) FROM event e WHERE e.event_type_id <> 47 AND e.master_comm_id = (SELECT top 1 c.comm_id...
Finding a min value to use in a subquery
[ "", "sql", "sql-server", "" ]
I created the following tables: ``` create table people ( ID varchar(10), name varchar(35), CONSTRAINT pk_ID PRIMARY KEY (ID) ); create table numbers ( code varchar(10), ID varchar(10), number numeric, CONSTRAINT ...
By "same number" you mean that there is only one number in `numbers` for the person. You can do this with `group by` and `having`: ``` select n.id from numbers n group by n.id having min(number) = max(number); ``` Note: this doesn't take `NULL` into account. Your question doesn't specify what to do if one of the valu...
If I understand correctly you want to see out of the 2 rows for each user in numbers who has the same number twice? If so you could do. ``` SELECT p.ID, p.name, p.number, COUNT(DISTINCT n.id) as num FROM people as p INNER JOIN numbers as n on n.ID = p.ID GROUP BY p.ID, n.number HAVING num > 1 ``` The would return a l...
How to select a specific person in MySQL?
[ "", "mysql", "sql", "" ]
It is asked many times, but not this way. I am on SQL Server 2008, and there is no `STRING_SPLIT` function (like in 2016). A query returns with the following row, see below a single example row. What you see below in bald is a single field actually, so one `varchar` column has it altogether: ``` Appple|10|admin|8456...
``` DECLARE @Result Table(Value varchar(50)) DECLARE @x XML SELECT @X = CAST('<A>' + REPLACE(@StringList, '|', '</A><A>') + '</A>' AS XML) INSERT INTO @Result SELECT t.value('.', 'varchar(50)') as inVal FROM @X.nodes('/A') AS x(t) ``` This will create a table with one column (Value). Each split value from your pipe-d...
``` ALTER FUNCTION [dbo].[split] ( @string varchar(max), @separator varchar(1) -- longer separator is also possible ) RETURNS @result TABLE (keyword varchar(max) ) AS BEGIN declare @pos int=0, @res varchar(100) while len(@string)>0 begin set @pos=CHARINDEX(@separator, @string+@separator,0) select @res=left(@...
Mimic STRING_SPLIT without custom function in SQL Server 2008
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Following sample returns affected ROWCOUNT. Is there a way to return affected IDENTITYs? ``` UPDATE HumanResources.Employee SET JobTitle = N'Executive' WHERE NationalIDNumber = 123456789 IF @@ROWCOUNT = 0 PRINT 'Warning: No rows were updated'; ```
``` UPDATE HumanResources.Employee SET JobTitle = N'Executive' OUTPUT INSERTED.PrimaryKeyID WHERE NationalIDNumber = 123456789 ``` **Here I assumed Id name is PrimaryKeyID.**
``` UPDATE HumanResources.Employee SET JobTitle = N'Executive' OUTPUT INSERTED.YourIdentityColumn WHERE NationalIDNumber = 123456789 ``` [OUTPUT](https://msdn.microsoft.com/en-us/library/ms177564.aspx)
Retrieving affected records through T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following code ``` IF EXISTS(SELECT @FunderID FROM dbo.FunderCharityTbl WHERE @ContributionAmount > ( ( sum(TotalContributions) / 100 ) *10 )) BEGIN RAISERROR ('Sorry contribution is refused limit is breached', 16,1) RETRUN 99 END ``` And I am getting the following error > Ms...
You can't use a Aggregate function in `WHERE` clause, but you can use it in `HAVING` clause ``` IF EXISTS( SELECT 1 --@FunderID FROM dbo.FunderCharityTbl HAVING @ContributionAmount > ((sum(TotalContributions)/100)*10) ) ```
You have to use `GROUP BY` and `HAVING` something like: ``` IF EXISTS( SELECT @FunderID FROM dbo.FunderCharityTbl GROUP BY @FunderID HAVING @ContributionAmount > ((sum(TotalContributions)/100)*10) ) ```
SQL Server : getting an error "Msg147, level15" Why do I get this error and how to fix it
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have two methods for solution, but both are high inefficient to work with value of the order 108 and greater. **Method 1** ``` select 100 + rownum - 1 from dual connect by level <= (200 - 100 + 1) ``` **Method 2** ``` select rownum + 100 - 1 from (select 1 from dual group by cube(1, 2, 3, 4, 5, 6, 7, 8, 9)) wher...
For that many rows a pipelined function would probably the best solution: ``` create or replace TYPE t_numbers IS TABLE OF NUMBER; / create or replace function generate_series(p_min integer, p_max integer) return t_numbers pipelined as begin for i in p_min..p_max loop pipe row (i); end loop; end; / ``` A...
Some other options: **Option 1 - Generate a collection**: ``` CREATE TYPE intlist IS TABLE OF NUMBER(10,0); / CREATE FUNCTION list_between( min_value NUMBER, max_value NUMBER ) RETURN intlist DETERMINISTIC AS o_lst intlist := intlist(); BEGIN IF ( min_value <= max_value ) THEN o_lst.EXTEND( max_value - m...
Generate numbers between min_value and max_value oracle
[ "", "sql", "oracle", "performance", "" ]
I have an SQL table with some data like this, it is sorted by date: ``` +----------+------+ | Date | Col2 | +----------+------+ | 12:00:01 | a | | 12:00:02 | a | | 12:00:03 | b | | 12:00:04 | b | | 12:00:05 | c | | 12:00:06 | c | | 12:00:07 | a | | 12:00:08 | a | +----------+------+ ``` So...
You can use `lag` (SQL Server 2012+) to get the value in the previous row and then compare it with the current row value. If they are equal assign them to one group (`1` here) and a different group (`0` here) otherwise. Finally select the required rows. ``` select dt,col2 from ( select dt,col2, case when lag(col2,1,0...
If you are using Microsoft SQL Server 2012 or later, you can do this: ``` select date, col2 from ( select date, col2, case when isnull(lag(col2) over (order by date, col2), '') = col2 then 1 else 0 end as ignore from (yourtable) ) x where ignore = 0 ``` Th...
Remove duplicates from query, while repeating
[ "", "sql", "sql-server", "t-sql", "" ]
I have this query ``` INNER JOIN view AS vw ON vw.[Id] = vw2.[Id] ``` The problem is the return in vw2.[Id] contains a tab space at the end ('2012 ') and vw does not ('2012'). So I tried doing ``` INNER JOIN view AS vw ON vw.[Id] = Replace(vw2.[Id], char(9), '') ``` Unfortunately, the comparison still returns false...
I suspect there may be more characters you're dealing with than just a tab. For example, you include `REPLACE(Id, char(9), '') = '2012 '` Why is there still a space on the end after the replace? I was able to get your method to work in SQL 2008R2, so below is proof-of-concept code. ``` CREATE TABLE #table1 ( Id varch...
Your logic seems right. Have you tried: ``` INNER JOIN view AS vw ON vw.[Id] = RTRIM(vw2.[Id]) ``` ? You could also combine trims and replaces as a way to get rid of all of the whitespace. Though, it seems like using a sledgehammer to get what you want... ``` INNER JOIN view AS vw ON REPLACE(LTRIM(RTRIM(vw.[Id]), c...
Removing tab spaces in SQL Server 2012
[ "", "sql", "sql-server", "" ]
I have a database with colums I am working on. What I am looking for is the date associated with the row where the SUM(#) reaches 6 in a query. The query I have now will give the date when the number in the colum is six but not the sum of the previous rows. example below ``` Date number ---- ------ 6mar16 1...
You could use this query, which tracks the accumulated sum and then returns the first one that meets the condition: ``` select date from (select * from mytable order by date) as base, (select @sum := 0) init where (@sum := @sum + number) >= 6 limit 1 ``` [SQL Fiddle](http://sqlfiddle.com/#!9/382e3/8...
Most databases support ANSI standard window functions. In this case, cumulative sum is your friend: ``` select t.* from (select t.*, sum(number) over (order by date) as sumnumber from t ) t where sumnumber >= 10 order by sumnumber fetch first 1 row only; ``` In MySQL, you need variables: ``` select t.* fr...
Stop query when SUM is reached (mysql)
[ "", "mysql", "sql", "sum", "" ]
I would like to recreate a table for path analysis in BigQuery (similar to unpivot). For each person, I have his/her page path data like follows. ``` [visitor] [page] [page_orders] A, Pa, 1 A, Pb, 2 A, Pc, 3 A, Pb, 4 A, Pf, 5 B, Px, 1 B, Pb, 2 B, Pz, 3 B, Pk, 4 C, Pb, 1 C, Pz, 2 C, Pa, 3 ``` And I...
``` SELECT visitor, GROUP_CONCAT(page, ' > ') as page_path FROM ( SELECT visitor, page, page_order FROM YourTable ORDER BY visitor, page_order ) GROUP BY visitor ``` Another option: with use of [BigQuery User-Defined Functions](https://cloud.google.com/bigquery/user-defined-functions) (has no dependency on orde...
With BigQuery support for standard SQL, this can be solved by using native operations on ARRAYs. Below is one possible solution: ``` select visitor, (select string_agg(p, ' --> ') from t.pages p) from (select visitor, array(select p.page from t.pages p order by p.page_order asc) pages from (select visitor, array_agg(s...
Create Page Path Table in BigQuery (Path Analysis ; Unpivot )
[ "", "sql", "google-bigquery", "" ]
I am trying to select from a table in SQL Server, so that it groups my `FinalDate` column into week numbers and sums the `ThisApp` column for that week in the next cell. I looked online and I cannot seem to find what I am after. I was wondering if this was something I can do in T-SQL? These are currently the rows in ...
``` DECLARE @tmp table(dat datetime, val float) insert into @tmp values ('15/04/2016' , 20459.92), ('29/05/2016', 7521.89), ('30/05/2016', 5963.61), ('31/05/2016', 3293.72), ('03/06/2016', 27413.20), ('04/06/2016', 8392.16), ('05/06/20...
``` SELECT DATEPART(WEEK, FinalDate) FinalDate , SUM(ThisApp) ThisApp FROM Your_Table GROUP BY DATEPART(WEEK, FinalDate) ``` In order to get `0` for weeks not existent in the dataset you have to create a table with weeknumbers (1-52) and `right join` to it. In that case you'd get something like: ``` SELE...
Group by week number including empty weeks and sum other column
[ "", "sql", "sql-server", "group-by", "week-number", "" ]
I'm using SQL Server 2016, but this is not a 2016 question. Here's what I would like to do. I will have the user's email address and will need to get data for that user. So this is simple: ``` select [firstname],[lastname],[managerid] from employees where workemail='emp@company.com' ``` Very straight forward, but not...
You can do a left-join. The left side expression will have the employee, and the right side will link to a row in the same table and get the manager's info (assuming it exists). Don't do an inner join because if the "manager" row is missing, then you'll get nothing for the employee. ``` Select [e].[firstname] [emp_fn...
You can use a self join where the first instance of the table indicated the employee's details and the second the manager's details: ``` SELECT e.[firstname], e.[lastname], m.[firstname], m.[lastname] FROM employees e LEFT JOIN employees m ON e.[managerid] = m.[id] WHERE e.workemail = 'emp@company.com' ```
Querying the same table twice to get 2 records..in one query
[ "", "sql", "sql-server", "select", "" ]
I need to count the sessions which visited a particular page once and sessions which visited the same page once or more than once. For example: consider these sessions between 1st to 4th April: ``` Session_id| Date ----+--------- 1| 01/04/2016 1| 02/04/2016 2| 01/04/2016 3| 01/04/2016 4| 01/04/2016 4| 03/04/2016 4| 04...
You can't avoid subqueries to get this result, but you can get rid of the `count(distinct)` (which is probably the most expensive part): ``` select no_of_visits, count(*) as sessions FROM ( select session_id, case when min(date) <> max(date) -- at least two different dates then 'mul...
It *seems* you want something like this: ``` select session_id, count(distinct dt) as no_of_visits, case when count(distinct dt) = 1 then "Single visit" else "Multiple visits" end as visit from my_table group by session_id; ``` **Note**: I used dt rather than ...
SQLCount distinct of one column based on another column
[ "", "sql", "oracle", "session", "count", "" ]
I want to search a `student` with multi condition in SQL, ex: `name`, `age`. But we may have only name or only age value or we may have all value with the information from user . I use a form in `HTML` to get values. I don't know how to write the query to select if they not fill all text field . If I have only name va...
@austin wernli comment is one answer and I found another way to use that SELECT \* FROM stuTBL WHERE (name = @name or @name is null) AND (age = @age or @age is null)
Check the `@name = ''` , `@age = ''` along with the condition. If the `@name` is empty it will check the age condition only. If `@age` is empty it will check the name condition only. If the both param have valid data then both the condition will work ``` SELECT * FROM stuTBL WHERE (name = @name OR ISNULL(@name, '')...
Select with multi condition in SQL
[ "", "sql", "" ]
I have a varchar column, and each field contains a single word, but there are random number of pipe character before and after the word. Something like this: ``` MyVarcharColumn '|||Apple|||||' '|||||Pear|||||' '||Leaf|' ``` When I query the table, I wish to replace the multiple pipes to a single one, so the result ...
vkp's method absolutely solves your issue. Another method that works, and also will work in a variety of other situations, is using a triple `REPLACE()` ``` SELECT REPLACE(REPLACE(REPLACE('|||Apple|||||', '|', '><'), '<>',''), '><','|') ``` This method will allow you to keep a delimiter between multiple strings where...
One way is to replace all the `|` with blanks and add a pipe character at the beginning and the end of string. ``` select '|'+replace(mycolumn,'|','')+'|' from tablename ```
Replace multiple repeating character to one
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have these tables: ``` Users Id (PK) NationalCode UserProfiles UserProfileId (PK) One to One with Users SalaryAmount Salaries NationalCode SalaryAmount ``` I want to update `SalaryAmount` for each user inside `UserProfiles` with new one in Salaries. How can I do that? I have tried this: ``` UP...
All you need is another join on `UserProfiles: ``` UPDATE up SET up.SalaryAmount = s.Salary FROM UsersProfiles up JOIN Users u on up.UserProfileId = u.Id JOIN Salaries s ON u.NationalCode = s.NationalCode ```
``` UPDATE up SET up.SalaryAmount = t2.Salary FROM UserProfiles up INNER JOIN Users t1 ON t1.Id = up.UserProfileId INNER JOIN Salaries t2 ON t1.NationalCode = t2.NationalCode GO ``` Is that what you need? I would recommend you to make `UserProfileId` column to be unique in table `UserProfiles` and store Users's unique...
TSQL: How to update this field
[ "", "sql", "t-sql", "" ]
I have asked this question before here: [Between two tables how does one SELECT the table where the id of a specific value exists mysql](https://stackoverflow.com/questions/36069463/between-two-tables-how-does-one-select-the-table-where-the-id-of-a-specific-valu) however I feel that I didn't phrase it well enough. I h...
There ARE if statements in mysql. Anyway! You can do this: ``` SELECT Temperature as Value FROM Mountain WHERE Trip_id = 74 Union All SELECT Atmosphere as Value FROM Forest WHERE Trip_id = 74 ```
You can use below the query. ``` Select T.TripID, M.Temperature, F.Atmosphere From Trip T LEFT OUTER JOIN Mountain M ON T.TripID = M.TripID LEFT OUTER JOIN Forest F ON T.TripID = F.TripID Where T.TripID = 74 ``` So in the above query if both Mountain and Forest table have this ID then Temp and Atmosphere will be disp...
Between two tables how does one SELECT the table where the id of a specific value exists mysql (duplicate)
[ "", "mysql", "sql", "database", "" ]
I have this SELECT statement: ``` SELECT t.clmUnit, t.clmConType, Count(t.clmCaseID) TotalCases, SUM(CASE WHEN t.clmOutcomeType='Resolved' THEN 1 ELSE 0 END) TotalResolved, cast(SUM(CASE WHEN t.clmOutcomeType='Resolved' THEN 1 ELSE 0 END) as decimal(18,2))/cast(Count(t.clmCaseID) as decimal(...
AS Arul Suggested, you need to use cast function on the whole column calculation. ``` SELECT t.clmUnit, t.clmConType, Count(t.clmCaseID) TotalCases, SUM(CASE WHEN t.clmOutcomeType='Resolved' THEN 1 ELSE 0 END) TotalResolved, cast(SUM(CASE WHEN t.clmOutcomeType='Resolved' THEN 1 ELSE 0 END))/Count(t.clmCaseID) *...
Try this one : ``` select convert(DECIMAL(10,2),column) ``` for precision of 2 decimal places
How to fix SQL output into two decimal places
[ "", "sql", "sql-server", "decimal", "" ]
I got a query where iam trying to get the max(date) value of from another table to be used as join condition. ``` SELECT a.col1, a.col2 FROM tablea a, tableb b WHERE a.pk_id = b.fk_id AND a.effdt = (SELECT MAX(effdt) FROM tablea c where c.id= a.id ...
Use the `RANK()` analytic function to eliminate the correlated sub-query: ``` SELECT * FROM ( SELECT a.*, RANK() OVER ( PARTITION BY a.id ORDER BY a.effdt DESC ) AS rnk FROM tablea a INNER JOIN tableb b ON ( a.pk_id = b.fk_id ) WHERE a.effdt <= SYSDATE ) WHERE rnk = 1; `...
The the sub query on table c, an index on `effdt` is not enough. An index on `(id, effdt)` would do better. The key is to cover the `where` clause as well as the `max(effdt)` function in a single index. This is very similar to indexing `order by`: <http://use-the-index-luke.com/de/sql/sortieren-gruppieren/indexed-orde...
make max() function faster when used as inline query join condition
[ "", "sql", "oracle", "join", "max", "greatest-n-per-group", "" ]
Writing SQL in MS SQL server management studio. I have this problem now, I have a table with where there are two of each row with almost identical values: ``` code | name | location | group 1 | Thing | 1 | 1 1 | Thing | 2 | NULL ``` I need to update the NULL GROUP to match the ...
Here's one option `joining` the table to itself: ``` update t1 set grp = t2.grp from yourtable t1 join yourtable t2 on t1.code = t2.code and t2.grp is not null where t1.grp is null ```
One method uses window functions: ``` with toupdate as ( select t.*, max(grp) over (partition by code) as maxgrp from t ) update toupdate set grp = maxgrp where grp is null; ```
If same value in one column in tow rows, update another column with same value from one row
[ "", "sql", "sql-server", "" ]
How do I aggregate 2 select clauses without replicating data. For instance, suppose I have `tab_a` that contains the data from 1 to 10: ``` |id| |1 | |2 | |3 | |. | |. | |10| ``` And then, I want to generate the combination of `tab_b` and `tab_c` making sure that result has 10 lines and add the column of `tab_a` to ...
Perhaps you're new to SQL, but this is generally not the way things are done with RDBMSs. Anyway, if this is what you need, PostgreSQL can deal with it nicely, using different strategies: ### Window Functions: ``` with tab_a (id) as (select generate_series(1,10)), tab_b (id) as (select generate_series(1,2)), ta...
Your question includes an unstated, invalid assumption: that the *position* of the values in the table (the row number) is meaningful in SQL. It's not. In SQL, rows have *no order*. All joins -- everything, in fact -- are based on values. To join tables, you have to supply the values the DBMS should use to determine wh...
Aggregate multiple select statements without replicating data
[ "", "sql", "postgresql", "" ]
I have the following SQL Server Stored Procedure which validates a password. ``` ALTER PROC [dbo].[spValidatePassword] @UserId uniqueidentifier, @Password NVARCHAR(255) AS BEGIN DECLARE @PasswordHash NVARCHAR(255) = HASHBYTES('SHA2_512', (SELECT @Password + CAST((SELECT p.PasswordSalt FROM Passwords p WHERE p.UserId ...
``` ALTER PROC [dbo].[spValidatePassword] @UserId uniqueidentifier, @Password NVARCHAR(255) AS BEGIN DECLARE @PasswordHash NVARCHAR(255) = HASHBYTES('SHA2_512', (SELECT @Password + CAST((SELECT p.PasswordSalt FROM Passwords p WHERE p.UserId = @UserId) AS NVARCHAR(255)))) SELECT CASE WHEN EXISTS ( SELECT...
Try this query, will return `1` if there is a result, else `0` ``` SELECT (CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END) FROM Passwords WHERE UserId = @UserId AND [Password] = @PasswordHash ```
Return value based on count from SQL Server Stored Procedure
[ "", "sql", "sql-server", "t-sql", "" ]
I'm trying to figure this one out. In this scenario, gas prices from a particular city in this database are increasing, so they will need to raise their prices 20%. I'm supposed to create a query that will display what the new price will be from that city only. Here is what it is supposed to look like: [![enter image ...
You dont really need the SUM function if you are only calculating the 20% price increase...Do this instead ``` Select ProductID, tblProduct.ProductType, Price, ((Price *.20)+Price) AS 'Increased Price' From tblProduct join tblCompany On tblProduct.CompanyID = tblCompany.CompanyID Where tblCompany.CompanyID IN ...
``` Select tblProduct.ProductID, tblProduct.ProductType, tblProduct.Price, SUM((tblProduct.Price *.20)+tblProduct.Price) AS 'Increased Price' From tblProduct join tblCompany On tblProduct.CompanyID = tblCompany.CompanyID Where tblCompany.CompanyID IN (Select c.CompanyID From tblCompany c Where c.City = ...
Add Column to Query From Same Table, Update Values in Duplicated Column?
[ "", "sql", "sql-server", "" ]
I have 3 tables with the following schema ``` create table main ( main_id int PRIMARY KEY, secondary_id int NOT NULL ); create table secondary ( secondary_id int NOT NULL, tags varchar(100) ); create table bad_words ( words varchar(100) NOT NULL ); insert into main values (1, 1001); insert into main value...
``` SELECT m.main_id, m.secondary_id, t.tags, t.is_bad_word FROM srini.main m JOIN ( SELECT st.secondary_id, st.tags, exists (select 1 from srini.bad_words b where st.tags like '%'+b.words+'%') is_bad_word FROM ( SELECT secondary_id, LISTAGG(tags, ',') as tags FROM srini.secondary GROUP BY seco...
You can use EXISTS and a regex comparison with \m and \M (markers for beginning and end of a word, respectively): ``` with main(main_id, secondary_id) as (values (1, 1000), (2, 1001), (3, 1002), (4, 1003)), secondary(secondary_id, tags) as (values (1000, 'very good words'), (1001, 'good and bad words'), (1002, 'u...
sql query to join two tables and a boolean flag to indicate whether it contains any words from third table
[ "", "sql", "postgresql", "join", "amazon-redshift", "" ]
I am looking for a SQL query to clean up a hacked SQL Server database. I have some basic SQL knowledge, but I have no idea how to solve the below. For one of our websites we have a SQL Server database that was recently hacked into. Thousands of records were filled with hidden divs, containing all sorts of dodgy refere...
Try this out; will only work if your assumptions are correct. Another assumption hacker did not add nested DIVs. And yes, TEST this thoroughly before running the update. And back up your data before running the update. ``` CREATE TABLE #temp(id INT IDENTITY, html VARCHAR(MAX)); INSERT #temp(html) VALUES('<p>Some text...
A UDF that uses `PATINDEX` may be able to do it. Assuming * All malicious content is in `<DIV>...</DIV>` sections * No `<DIV>...</DIV>` sections exist that are *not* malicious content * You TEST THIS EXTENSIVELY on a backup of your data before applying it to your live database First use this UDF for Pattern replacem...
SQL replace query for variable content
[ "", "sql", "sql-server", "" ]
Is there any query that says > "in .... but not in ....." ? Let's say I have a table about "double agent". This table has Name, Nationality, and Age. ``` +-------------------------+ | Name Nationality Age | +-------------------------+ | Jony US 20 | | Jony China 20 | | Adam Argentina ...
I would do this using aggregation and `having`. I think the clearest approach is: ``` select name from agent group by name having sum(nationality = 'China') > 0 and sum(nationality = 'US') = 0; ``` There are definitely other methods. Here is one that doesn't require `select distinct` or `group by`: ``` select...
If you want to select all agents that are in China but not the US, you can apply the filter in `having` ``` select name from mytable where nationality in ('US', 'China') group by name having sum(nationality = 'US') = 0 ``` Note that in your sample data all agents that are in China are also in the US, so this query wo...
MySQL Query: Is There any Query such "BUT NOT IN <blank>"?
[ "", "mysql", "sql", "" ]
How can I 'score' results using order by, if possible, by number of matches between a given user and every other user in a table. Basically, I have a given 'userid' of '1' and I need to check all of this users 'interests' against of users interests and order by the number of like matches between users. Say userid '1'...
You can do a `SELF JOIN`: ``` SELECT i2.userid FROM interests i1 INNER JOIN interests i2 ON i2.userid <> i1.userid AND i2.interest = i1.interest WHERE i1.userid = 1 GROUP BY i2.userid ORDER BY COUNT(*) DESC; ``` `ONLINE DEMO`
The easiest way is to get a list of all users and shares and counts and then select and order the ones you want from that sub-query. It makes the logic clear: ``` SELECT userid, otherid, sameCount FROM ( SELECT base.userid, other.userid as otherid, count(*) sameCount FROM interests base JOIN interests other ON b...
how do I get a count of matches across multiple tables joining by id?
[ "", "mysql", "sql", "" ]
I have two tables. One table shows me inbound inventory by month and the other shows me outbound inventory by month. Essentially I would like to show both inbound and outbound inventory by month on a single table. 1. ``` select warehouses.id, count(pallets.id), to_char(pallets.in_date, 'FMMonth-YY') as in_month fro...
One way to achieve this is to use the existing queries (with some minor modifications) as inline views. And use a FULL OUTER JOIN operation to combine them. No indication is given whether warehouse\_id could be NULL or not, so in place of the equality comparison, the example below uses a "null-safe" comparison so NULL...
To simplify the query I think you can trick the COUNT this way : *Note: The query inside the WITH clause is maybe sufficient for you. However I added the WITH clause to be able to make a union. It depends on what you want the output to be.* ``` WITH computed_warehouses AS ( -- Maybe this single select (inside the W...
Combining aggregated columns into single table
[ "", "sql", "postgresql", "join", "aggregate", "" ]
Alright, so I managed to connect these two tables: ``` CREATE TABLE [dbo].[T_Artikli] ( [ArtikliId] INT IDENTITY (1, 1) NOT NULL, [Naziv] NVARCHAR (100) NOT NULL, [Sifra] VARCHAR (13) NOT NULL, [Vp] FLOAT (53) NOT NULL, [MP] FLOAT (53) NOT NULL, [Napomena] NVARCHAR (300) NOT...
First of all, you are using identity which is automatically generated. so you cannot create the same row. Secondly, you referenced the wrong foreign key I believe
The problem is here ``` CONSTRAINT [FK_T_Stanje_T_Artikli] FOREIGN KEY ([StanjeId]) REFERENCES [dbo].[T_Artikli] ([ArtikliId]) ``` Your foreign key is incorrect. It should be: ``` CONSTRAINT [FK_T_Stanje_T_Artikli] FOREIGN KEY ([ArtiklId]) REFERENCES [dbo].[T_Artikli] ([ArtikliId]) ```
SQL deleting connected rows and adding same values
[ "", "sql", "database", "" ]
I have a table with approximately 8 million rows. The rows contain an ID, a date, and an event code. I would like the select all the ID's and dates for which the event code is equal to 1 and there has been an event code equal to 2 at some time in the past. For example, my table looks like this: ``` ID Date C...
If you only want to select the max date for each `ID`: ``` WITH Cte AS( SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Date DESC) FROM tbl WHERE Code = 1 ) SELECT ID, Date, Code FROM Cte c WHERE rn = 1 AND EXISTS( SELECT 1 FROM tbl t WHERE ...
You can use `exists`. ``` select * from t where code = 1 and exists (select 1 from t t1 where t.id = t1.id and t.dt > t1.dt and t1.code=2) ```
SQL Server 2012 SELECT max date based on multiple conditions
[ "", "sql", "sql-server", "select", "sql-server-2012", "" ]
I am writing a sql code for a report page that that joins three tables. Here is the query I have written. ``` comm.CommandText = "SELECT Count(DISTINCT Courses.CourseID) AS CourseCount, Count(DISTINCT Students.StudentID) AS StudentCount, Count(Students.StartDate) AS StartCount, School.Name, School.StartDate, School.Sc...
When you want aggregates from different tables, you should not join the tables and then aggregate, but always build the aggregates first and join these instead. In your case you were able to avoid issues by counting distinct IDs, but that is not always possible (i.e. when looking for sums or avarages). You can count co...
You can do this with conditional aggregation. Just add this to the `SELECT`: ``` SUM(CASE WHEN Student.StartDate >= DATEADD(month,-1, GETDATE()) THEN 1 ELSE 0 END) as RecentStudents ```
Using COUNT Function in Table Joins
[ "", "sql", "asp.net", "sql-server", "" ]
If I have a table such as: ``` name1 | name2 | id | +----------------+--------------+-----------+ | A | E | 1 | | A | F | 1 | | B | G | 1 | | C | H | 1 | | D ...
One approach is to use subquery that finds all ids that have a value 'E' in column `name2` and then filter out all these ids: ``` SELECT * FROM table WHERE id NOT IN ( SELECT DISTINCT id FROM table WHERE name2 = 'E' ) ```
SELECT \* FROM `table` WHERE id NOT IN (SELECT id FROM `table` WHERE name2 <> 'E')
select query -mysql
[ "", "mysql", "sql", "select", "" ]
I have a table called user\_versions. This table doesn't have any identity column due to the requirements. If a user updates their details a new version is created, a columns called version is incremented by 1 and the other version isn't live anymore but is kept again this is due to requirements and the new version goe...
With standard syntax it would be: ``` select uv.* from user_versions uv inner join(select user_id, max(version) as version from user_versions group by user_id) as t on uv.user_id = t.user_id and uv.version = t.version ```
``` with cte as ( select user_id,name,email,version, row_number() over (partition by user_id order by version desc) as rn from user_versions) select user_id,name, email, version from cte where rn = 1 ```
I need to select records based on the value of a column in the same table.
[ "", "sql", "" ]
I've got a table with close to 7 million rows in it. Here's the table structure ``` `CREATE TABLE `ERS_SALES_TRANSACTIONS` ( `saleId` int(12) NOT NULL AUTO_INCREMENT, `ERS_COMPANY_CODE` int(3) DEFAULT NULL, `SALE_SECTION` varchar(128) DEFAULT NULL, `SALE_DATE` date DEFAULT NULL, `SALE_STOCKAGE_EXACT` int(4)...
I don't agree with Jimmy B here. Your query looks perfect in my opinion. Depending on how many records there are for company 48 either the full table should be read sequentially (when it's many, say, 50% of all table records) or an index on ERS\_COMPANY\_CODE should be used (when it's not that many, say, only 1% of al...
I don't know if there is a way to speed this up. But, you can try using an index. I would recommend one on `ERS_SALES_TRANSACTIONS(ERS_COMPANY_CODE, SALE_SECTION, SALE_DATE, SALE_NET_AMOUNT)`. This is a covering index for the query, meaning that all columns used for the query are in the index -- and hence the data bas...
Mysql Query Optimization
[ "", "mysql", "sql", "indexing", "innodb", "" ]
I have the following table: ``` custid custname channelid channel dateViewed -------------------------------------------------------------- 1 A 1 ABSS 2016-01-09 2 B 2 STHHG 2016-01-19 3 C 4 XGGTS 2016-01-09 6 D 4 ...
``` ;WITH cte AS ( SELECT custid, custname, channelid, channel, dateViewed, CAST(DATEADD(day,15,dateViewed) as date) as dateEnd, ROW_NUMBER() OVER (PARTITION BY custid, channelid ORDER BY dateViewed) AS rn FROM (VALUES (1, 'A', ...
I'm not sure how this solution will scale - but with some good index candidates and decent data housekeeping, it'll work.. You're going to need some extra info for starters, and to normalize your data. You will need to know the first charging period start date for each customer. So store that in a customer table. Her...
How to COUNT rows according to specific complicated rules?
[ "", "sql", "sql-server", "count", "rows", "" ]
Hi i am in need of help to optimize a query for large database records above 1 Millions . Current query is taking 27-30 seconds to execute. ``` SELECT SQL_CALC_FOUND_ROWS candidate.candidate_id AS candidateID, candidate.candidate_id AS exportID, candidate.is_hot AS isHot, candidate.date_modified AS dateModifiedSort, c...
I've changed changed the table alias in the below query, use this This Must Solve Your Problem ``` SELECT SQL_CALC_FOUND_ROWS candidate.candidate_id AS candidateID, candidate.candidate_id AS exportID, candidate.is_hot AS isHot, candidate.date_modified AS dateModifiedSort, candidate.date_created AS dateCreatedSort, can...
1. Get rid of `saved_list_entry`, it adds nothing. 2. Delay joining to `user`. This will let you get rid of the `GROUP BY`, which is adding a bunch of time, and possibly inflating the value of `FOUND_ROWS()`. Something like: ``` SELECT c2.*, ou.first_name AS ownerFirstName, ou.last_name AS ownerLastN...
Query Optimization for large database
[ "", "mysql", "sql", "query-optimization", "" ]
I am trying to retrieve the product with the highest price: ``` SELECT ProductName, Price FROM [Products] ORDER BY Price DESC LIMIT 1 ``` I wanted to know if there is another way of doing this in a more efficient way, with MAX for example.
Use MAX and GROUP BY ``` SELECT ProductName, MAX(Price) [Price] FROM [Products] GROUP BY ProductName ORDER BY MAX(Price) DESC LIMIT 1; ```
I've always done it with the following SELECT top 1 Name FROM tableName ORDER BY Price DESC
SQL - getting record with maximum value
[ "", "sql", "max", "" ]
I'm writing code to manage users in a sqlite database with Go. I'm trying to check if a username is taken, but my code is ugly. My table looks like: ``` id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password TEXT ``` And I check if a username is taken with: ``` func UserExists(db * sql.DB...
Use [`QueryRow`](https://golang.org/pkg/database/sql/#DB.QueryRow) to query at most one row. If the query doesn't return any row, it returns `sql.ErrNoRows`. ``` func UserExists(db * sql.DB, username string) bool { sqlStmt := `SELECT username FROM userinfo WHERE username = ?` err := db.QueryRow(sqlStmt, userna...
I know this is a bit old, but I don't see any clean answers here. Notice below the if rows.Next() statement which will return a boolean if there are any rows or not: ``` package main import ( "database/sql" _ "github.com/mattn/go-sqlite3" "log" ) func main() { exists, _ := SelectDBRowExists(`SELECT *...
Checking if a value exists in sqlite db with Go
[ "", "sql", "sqlite", "go", "" ]
In this example, I'm trying to return a list of values (in this case, company names) that have no entries in another table (entries in this case meaning invoices). In other words, I'm trying to return a list of companies that have no invoices. Here is my code: `Select CompanyName From tblCompany join tblInvoice ON tbl...
Use left join and filter on nulls: ``` select CompanyName from tblCompany left join tblInvoice on tblCompany.CompanyID = tblInvoice.CompanyID where tblInvoice.CompanyID is null ``` This works because missed joins return nulls in the joined table's values.
Try this ``` Select CompanyName From tblCompany Where tblCompany.CompanyID NOT IN ( Select CompanyID From tblInvoice) ``` That is get all the `CompanyName` from `tblCompany` where the `CompanyID` not exists in the `tblInvoice`. Or you can try the below one, ``` select CompanyName from ...
Return Values from one table that have no entries in another?
[ "", "sql", "sql-server", "" ]
I have the following table: ``` ITEM DATE VALUE ---------------------- ITEM1 2016-05-04 1 ITEM1 2016-05-05 3 ITEM1 2016-05-06 3 ITEM1 2016-05-09 3 ITEM1 2016-05-04 4 ITEM2 2016-05-10 1 ITEM2 2016-05-05 2 ITEM2 2016-05-06 3 ITEM2 2016-05-09 1 ITEM2 2016-05-10 1 ``` And I want to...
It looks like a variation of gaps-and-islands. **Sample data** ``` DECLARE @T TABLE (ITEM varchar(50), dt date, VALUE int); INSERT INTO @T(ITEM, dt, VALUE) VALUES ('ITEM1', '2016-05-04', 1), ('ITEM1', '2016-05-05', 3), ('ITEM1', '2016-05-06', 3), ('ITEM1', '2016-05-09', 3), ('ITEM1', '2016-05-10', 4), ('ITEM2', '2016...
Assuming the correction to the sample data I suggested in the comments, this seems to fit the bill: ``` declare @t table (ITEM char(5), Date date, Value tinyint) insert into @t(ITEM,DATE,VALUE) values ('ITEM1','20160504',1), ('ITEM1','20160505',3), ('ITEM1','20160506',3), ('ITEM1','20160509',3), ('ITEM1','20160510',4)...
Assign sequential numbers to rows with repeating values
[ "", "sql", "sql-server", "sql-server-2008", "window-functions", "" ]
I've a dataset that has some comments that would exclude subjects. I want to make a mini dataset to collect these subjects. I'm trying to use SAS SQL for this so I tried to do this: ``` PROC SQL; CREATE TABLE EXCLUDE as SELECT * FROM data_set WHERE UPCASE(COMMENT) like '%(INELIGI...
You could do it via a like-join against a list of the terms to exclude : ``` data words ; input word $char16. ; datalines ; INELIGABLE REFUSED ; run ; proc sql ; create table exclude as select a.* from data_set a left join words b on upcase(a.comment) like cats('%',b.word,'%') where missing(b....
You can use perl regular expressions to do this, if you're working with a string that already is formed. (If not, you're better off just writing the separate syntax, PRXs are slow.) Equivalent code here, one written out, one with a PRX using a single string: ``` proc sql; select * from sashelp.class where not ...
SAS SQL: WHERE LIKE 'list of words'
[ "", "sql", "sas", "" ]
I'm new to SQL and have a large database that contains IDs and Service Dates and I need to write a query to give me the first date each ID had a service. I tried: ``` SELECT dbo.table.ID, dbo.otherTable.ServiceDate AS EasliestDate FROM dbo.table INNER JOIN dbo.table.ID = dbo.otherTable.ID ``` But the output is every...
Use [`GROUP BY`](https://msdn.microsoft.com/en-us/library/ms177673.aspx) and [`MIN`](https://msdn.microsoft.com/en-GB/library/ms179916.aspx) to get the first date for each ID: ``` SELECT dbo.table.ID, MIN(dbo.otherTable.ServiceDate) AS EasliestDate FROM dbo.table INNER JOIN otherTable ...
You have to include a WHERE in your current query: ``` SELECT dbo.table.ID, dbo.otherTable.ServiceDate AS EasliestDate FROM dbo.table INNER JOIN dbo.table.ID = dbo.otherTable.ID WHERE Month(dbo.otherTable.ServiceDate) = 1 ``` Or you can search with Year(dbo.otherTable.ServiceDate) = 2016 Or you can use Day(dbo.otherT...
SQL Query to get oldest date
[ "", "sql", "sql-server-2008", "" ]
``` CREATE TABLE #EmpPcodes ( YearMonth INT, YEAR INT, MONTH INT, RunNo INT, Amount NUMERIC(18, 3), GroupCode NvarCHAR(30), GroupName NvarCHAR(250), GroupAName NvarCHAR(250), PayrollGroup INT, EmployeeId INT )...
Actually you are missing one column in insert statement whch also need some value: use this: ``` INSERT INTO #pArrangeAllcode SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId,NULL FROM dbo.#EmpPcodes ```
Use below query for inserting records. ``` INSERT INTO #pArrangeAllcode SELECT YearMonth, YEAR, MONTH, RunNo, Amount, GroupCode, GroupName, GroupAName, PayrollGroup, EmployeeId,NULL FROM dbo.#EmpPcodes ```
How to add temp table to another temp table with extra column
[ "", "sql", "sql-server", "dynamic-sql", "" ]
Hi sql'ers though am dealing with SQL from past 4 years. I encountered little complex situation today. I have a mysql table with columns, id,movieid,Lang,comment, and timestamp so i want to render comment for a particular movie in which user can decide a range that from where to where he wants a comment for that parti...
As far I understand you need to fetch 4 comments in total (between 6th and 10th) so you want to use `LIMIT` for that, starting from 6th record: ``` SELECT `comment` FROM aaa WHERE movieid = 2 AND `language` = 'en' LIMIT 6,4 ```
You can try this: ``` SELECT comment from aaa where movieid=2 and language='en' comment between 6 and 10 ```
this sql made me little complex situation
[ "", "mysql", "sql", "" ]
I have an sql table: ``` DATE USER FLAGGED COMMAND 1 Alice 0 sudo gparted 2 Bob 1 sudo 3 Bob 0 mv 4 Alice 1 sudo rm -rf 5 Charlie 1 sudo chown ``` I want to select last flagged action of a user ``` DATE USER ...
Here you first select latest entries for user and then drop those that are not flagged. Instead you should first select all entries that are FLAGGED and then find the most recent of them. This code should work. ``` select DATE, USER, REQUEST from ( select DATE, USER, REQUEST, FLAGGED row_number() over(part...
Move the flagged condition to the sub-query, so only the rows with flagged=1 will be retrieved and you can select the latest one with rn=1 condition. ``` select DATE, USER, REQUEST from ( select DATE, USER, REQUEST, FLAGGED, row_number() over(partition by USER order by date desc) rn from USERDATA where flagged = 1 ) s...
SQL select latest entry in the category among visible
[ "", "sql", "" ]
I have problem with my REGEXP expression which I want to loop and every iteration deletes text after slash. My expression looks like this now ``` REGEXP_SUBSTR('L1161148/1/10', '.*(/)') ``` I'm getting L1161148/1/ instead of L1161148/1
You said you wanted to loop. CAVEAT: Both of these solutions assume there are no NULL list elements (all slashes have a value in between them). ``` SQL> with tbl(data) as ( select 'L1161148/1/10' from dual ) select level, nvl(substr(data, 1, instr(data, '/', 1, level)-1), data) formatted from tbl co...
You can try removing the string after the last slash: ``` select regexp_replace('L1161148/1/10', '/([^/]*)$', '') from dual ```
Regexp_substr expression
[ "", "sql", "oracle", "" ]
My table structure is like below ``` TblMemberInfo | TblCarInfo MemberID Name | Id MemberId CarNumber 1 Sandeep | 1 2 1234 2 Vishal | 2 1 1111 3 John | ...
Here is one method: ``` select mi.MemberID, mi.Name, min(CarNumber) as CarNumber from TblMemberInfo mi join TblCarInfo ci on mi.MemberID = ci.MemberID group by mi.MemberID, mi.Name having count(*) = 1; ``` This works, because with only one row in the group, the `min()` returns the right value. And alternat...
A couple more options! ``` select mi.MemberId, mi.Name, ci.CarNumber from TblMemberInfo mi join TblCarInfo ci on mi.MemberId = ci.MemberId group by mi.MemberId, mi.Name, ci.CarNumber having min(ci.Id) = max(ci.Id) ``` Using a subquery to retrieve the single `MemberId's` is a good idea if you have a lot of other ...
Select all columns from two tables grouping by all columns in table1 and specific column in table2
[ "", "sql", "sql-server", "" ]
I've got a set of data which has an `type` column, and a `created_at` time column. I've already got a query which is pulling the relevant data from the database, and this is the data that is returned. ``` type | created_at | row_num ----------------------------------------------------- "or...
What about a [self join](https://stackoverflow.com/questions/3362038/what-is-self-join-and-when-would-you-use-it) ? It would look like this : ``` SELECT t1.type , t2.type , ABS(t1.created_at - t2.created_at) AS time_diff FROM your_table t1 INNER JOIN your_table t2 ON t1.row_num = t2.row_num + 1 ```
``` select type_1, type_2, created_at_2-created_at_1 as time_distance from (select type type_1, lead(type,1) over (order by row_num) type_2, created_at created_at_1, lead(created_at,1) over (order by row_num) created_at_2 from table_name) temp where type_2 is not null ```
Aggregating multiple rows more than once
[ "", "sql", "postgresql", "aggregate", "" ]
I have to develop an insert query on sql server which inserts a nchar value from another nchar value, but I have to increment it by 1. I have to preserve the left 0 (not always be a 0). How can I make the conversion? This is my code: ``` DECLARE @CIG int; SET @CIG = (SELECT MAX([VALUE1]) FROM [DB].[dbo].[TABLE]) +1; `...
Assuming That you have set NCHAR(10) length for your column, to preserve zero if there ``` DECLARE @tmp NCHAR(100) ='0761600002511'; SELECT LEFT(@tmp ,3)+CAST((CAST(RIGHT(@tmp ,97)AS INT)+1) AS NCHAR(10)) ```
You should Convert/cast first and then take max. Try this. ``` DECLARE @CIG int; SELECT @CIG = MAX(CONVERT(INT, [VALUE1]) + 1 FROM [DB].[dbo].[TABLE]; ```
SQL Server insert Top nchar +1 that could start by 0
[ "", "sql", "sql-server", "" ]
I have an SQL table, in which I store my application logs. I have a column errors, in which I store values like this example ``` +------+--------+----------------------------------------------+ | id | name | error | +------+--------+-------------------------------------------...
Remove the last digit part and count. **Query** ``` SELECT LEFT(error, LEN(error) - 4) AS [Error Like], COUNT(LEFT(error, LEN(error) - 4)) AS [Occurence] FROM tbl_error GROUP BY LEFT(error, LEN(error) - 4); ``` Or you can do it with a sub-query also. **Query** ``` SELECT t.[Error Like], COUNT(t.[Error Like]) AS [...
It looks like you want to strip out the last four characters and aggregate: ``` select left(error, len(error) - 4) as ErrorLike, count(*) from applogs group by left(error, len(error) - 4) order by count(*) desc; ```
How to get most frequent values in SQL where value like a variable?
[ "", "sql", "sql-server", "" ]
As part of a SQL stored procedure (producing XML output) I have the following line: ``` FORMAT(Quantity * ld.UnitPrice, 'N2') AS '@value' ``` This has produced perfectly acceptable results for several months now. Last week however the service into which the XML that this procedure produces failed because the value wa...
You could probably remove the format function. Then if required add `convert(decimal(9,2), YourColumn)`
You can use the FORMAT function with format of 'F2'. 'F' is the Fixed-Point format specifier. This is supported by all numeric types. ``` DECLARE @quantity int = 65; DECLARE @unitPrice money = 150.33; SELECT FORMAT(@quantity * @unitPrice, 'F2') AS 'Amount'; ``` [![enter image description here](https://i.stack.imgur....
What is the best way to reformat this piece of SQL to avoid the thousands separator
[ "", "sql", "sql-server", "" ]
I have table similar to this: ``` ID ProductName Price 1 Water 0.89 1 Water 0.99 1 Water 0.79 2 Coke 1.99 3 Sprite 1.99 ``` What I would like is to get is the lowest price of every product. ( ID can't change for same name ) If I could group just by one column it would be fine but I ...
Just use an aggregation on the product name (or id): ``` SELECT Products.ProductName, MIN(Products.Price) as Price FROM Products GROUP BY Products.ProductName; ```
You are very close to it. Just use `min()` function: ``` SELECT Products.ProductName, min(Products.Price) FROM Products GROUP BY Products.ProductName; ```
MS Access Selecting distinct rows
[ "", "sql", "ms-access", "" ]
I have a string that is adding data to a table so I can print a report or labels from the data. The data consists of addresses and is causing the string to fail because of the comma in the address. this string has been working but when it has some weird addresses I think that is what is causing this. ``` sqls = "INSER...
I'm uncertain whether the comma in the address is the problem. It looks to me like the apostrophe in *O'TOOL* should be a problem. But if it is not the cause of the first error Access complains about, it should trigger another error after you fix the first error. For a simple example, the following code triggers error...
Yes, it is the apostrophe. You can use this function to avoid this and most other troubles when concatenating SQL: ``` ' Converts a value of any type to its string representation. ' The function can be concatenated into an SQL expression as is ' without any delimiters or leading/trailing white-space. ' ' Examples: ' ...
VBA SQL String Run-Time Error 3075
[ "", "sql", "ms-access", "vba", "" ]
I have a table which is something like the below ``` Key CL EmailAddress CT Product1 Product2 Product3 Product4 Product5 1 X abc@gmail.com A 12 null null null null 2 X abc@gmail.com B 123 22 null null null ``` For each row I c...
As an alternative to MTO's approach, you could unpivot the data from your table: ``` select * from your_table unpivot (product for pos in (product1 as 1, product2 as 2, product3 as 3, product4 as 4, product5 as 5)); KEY CL EMAILADDRESS CT POS PRODUCT ---------- -- ------------- --- ---------- ---...
**Oracle Setup** ``` CREATE TABLE table_name ( "Key" INT PRIMARY KEY, CL CHAR(1), EmailAddress VARCHAR2(100), CT VARCHAR2(100), Product1 INT, Product2 INT, Product3 INT, Product4 INT, Product5 INT ); INSERT INTO table_name SELECT 1, 'X', 'abc@gmail.com'...
SQL how to merge records Oracle
[ "", "sql", "oracle", "oracle11g", "" ]
I have the following query ``` SELECT COUNT(DISTINCT ETABLISSEMENTS.IU_ETS) AS compte,ETABLISSEMENTS.IU_GREFFE FROM ENTREPRISES LEFT OUTER JOIN ETABLISSEMENTS ON ETABLISSEMENTS.IU_ENTREPRISE = ENTREPRISES.IU_ENTREPRISE LEFT OUTER JOIN dbo.BASES ON dbo.ETABLISSEMENTS.IU_BASE = dbo.BASES.IU_BASE LEFT OUTER JOIN dbo.ET...
You use **with** clause ``` with t as ( SELECT COUNT(DISTINCT ETABLISSEMENTS.IU_ETS) AS compte,ETABLISSEMENTS.IU_GREFFE FROM ENTREPRISES LEFT OUTER JOIN ETABLISSEMENTS ON ETABLISSEMENTS.IU_ENTREPRISE = ENTREPRISES.IU_ENTREPRISE LEFT OUTER JOIN dbo.BASES ON dbo.ETABLISSEMENTS.IU_BASE = dbo.BASES.IU_BASE LEFT OUTER JO...
When you are tired, you are messing up. This is what I've done earlier and I thought as not working ``` SELECT t.compte, PARTENAIRES.LIBEL AS Greffes FROM ( SELECT COUNT(DISTINCT ETABLISSEMENTS.IU_ETS) AS compte,ETABLISSEMENTS.IU_GREFFE FROM ENTREPRISES LEFT OUTER JOIN ETABLISSEMENTS ON ETABLISSEMENTS.IU_ENTREPRISE ...
Left join returning different results when changing column name
[ "", "sql", "sql-server", "" ]
``` SELECT Count(*) AS MonthTotal FROM CRMProjects WHERE CreatedDate between '01 May 2016' and '31 May 2016' SELECT Count(*) AS YearTotal FROM CRMProjects WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' SELECT Count(*) AS MonthNew FROM CRMProjects WHERE CreatedDate between '01 May 2016' and '31 May 2016' AN...
I would suggest something like this: ``` SELECT 'Month Total' AS Label, Count(*) AS Value FROM CRMProjects WHERE CreatedDate between '01 May 2016' and '31 May 2016' UNION ALL SELECT 'Year Total' AS Label, Count(*) AS Value FROM CRMProjects WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' UNION ALL SELECT ...
You can use `SUM(CASE)` as a kind of `SUMIF` for this... ``` SELECT SUM(CASE WHEN CreatedDate between '01 May 2016' and '31 May 2016' THEN 1 END) AS MonthTotal, SUM(1) AS YearTotal, SUM(CASE WHEN CreatedDate between '01 May 2016' and '31 May 2016' AND SystemType = 'O' THEN 1 END) AS MonthNew, SUM(CA...
Can I make one select statement in SQL?
[ "", "sql", "select", "relational-database", "" ]
Imagine i have such a table : ``` Nr Date 2162416 14.02.2014 2162416 11.08.2006 2672007 13.04.2016 2672007 27.11.2007 3030211 31.01.2013 3030211 25.04.2006 3108243 11.04.2016 3108243 24.08.2009 3209248 05.04.2016 3209248 08.06.2012 3232333 11.04.2012 323...
Simple way, use `EXISTS` to remove a row if another row with same Nr but later date exists: ``` delete from tablename t1 where exists (select 1 from tablename t2 where t2.nr = t1.nr and t2.date > t1.date) ``` Alternatively: ``` delete from tablename where (nr, date) not in (select nr, m...
If you always have pairs of rows, you can use: ``` delete your_table where (nr, date) in ( select nr, min(date) from your_table group by nr ) ``` If you want to handle the case in which you only have one row, you can add a condition: ...
Remove one of two Rows where first column is identical and second with different date
[ "", "sql", "oracle", "" ]
I have a table `comments` which contains a field `student_id`(foreign key to `students` table. I have another table `students` What I would like to do, is run a query that displays all students who have not made any comments. The SQL I have, only shows students who have made comments ``` SELECT studentID, email, firs...
You could do this: ``` SELECT studentID, email, first_name, last_name FROM students LEFT JOIN comments ON students.id = comments.student_id WHERE comments.student_id IS NULL ```
One method uses `not exists`: ``` select s.* from students s where not exists (select 1 from comments c where s.id = c.student_id ); ```
How to select 'exceptions' in SQL?
[ "", "sql", "" ]
I have tables called Products and ProductsDetails. I want to get something like the price of an order. So let's say I want 5 pairs of "Headphonesv1" ( Comparing with not ID but name, since name could change ), 2 packs of "GumOrbit" and 7 packs of "crisps". Pair of headphonesv1 costs 10$, gum 1$ and crisps 2$. So the an...
I think if you just want to see that total cost for multiple items you can use a aggregate and case expression to get the SUM. ``` SELECT Products.billID, Products.Date, SUM(CASE WHEN ProductsDetails.name LIKE 'Headphonesv1' THEN ProductsDetails.Price * 5 WHEN ProductsDetails.name LIK...
You probably have another two tables: `cart(cartID int/*,more info*/)` and `cartItems(cartID int /*FK*/, item varchar(50),qty int)` where you add something. Finally, ``` select sum(pd.price * ci.qty) tot FROM Products p INNER JOIN ProductsDetails pd ON p.billdID = pd.billID inner join cartItems ci on ci.item = pd.nam...
SQL Using Multiply 3 Times with different ID's
[ "", "sql", "" ]
I execute this query: ``` SELECT distinct(accounts.account_id), transactions.trn_code , transactions.trn_date FROM accounts join transactions ON accounts.account_id = transactions.account_id WHERE accounts.account_currency = 'USD' AND accounts.account_cards_linked > 1 AND transactions.trn_date >= '2015/03/01' AND tr...
You need to do a `JOIN` on `MAX(trn_date)` of each account: ``` SELECT a.account_id, t.trn_code, t.trn_date FROM accounts a INNER JOIN transactions t ON a.account_id = t.account_id INNER JOIN ( SELECT account_id, MAX(trn_date) AS trn_date FROM transactions WHERE trn_date >= ...
Select Max(trn\_date) and remove the date from the group by ``` SELECT distinct(accounts.account_id), transactions.trn_code , MAX(transactions.trn_date) FROM accounts join transactions ON accounts.account_id = transactions.account_id WHERE accounts.account_currency = 'USD' AND accounts.account_cards_linked > 1 AND t...
cant appear only the max date for a number of transactions
[ "", "mysql", "sql", "sql-server", "date", "mysql-workbench", "" ]
Trying to grab a count for 2-3 types of entry determined by column name 'adsource' value of the last 8 days. So far I've been able to grab one type only and add to results. Database MySql. **Results i'm getting now (only one type):** ``` days_ago monthday type1 --------------------------------- 1 ...
Try something like this.. ``` SELECT * FROM ( SELECT DATEDIFF(NOW(), edate) AS days_ago, DATE(edate) AS monthday, COUNT(DISTINCT (case when adsource=9 then entries.email end)) AS type1, COUNT(DISTINCT (case when adsource=12 then entries.email end)) AS type2, COUNT(DISTINCT (case when adsource=3 then entries.email end...
Whats the second column? Just add it to query: ``` SELECT DATE(edate) AS monthday, COUNT(DISTINCT entries.email) AS type1, COUNT(DISTINCT entries.type2) AS type2 FROM entries WHERE iplocation = 'mx' AND adsource = 9 AND DATEDIFF(DATE(edate), now()) BETWEEN 0 and 7 GROUP BY DATE(edate)) AS temp ```
How to include multiple COUNT per day in one query?
[ "", "mysql", "sql", "join", "count", "" ]
i have a table like this ``` userid | points | position 1 | 100 | NULL 2 | 89 | NULL 3 | 107 | NULL ``` i need a query for update the position column ordering by points desc, example result: ``` userid | points | position 1 | 100 | 2 2 | 89 | 3 3 | 107 | 1 ```
I would not use physical columns that depend on values in other rows, otherwise you have to update the entire table every time one row changes. Use a view or other mechanism to calculate the position on the fly. The query to calculate "position" would look something like: ``` SELECT userid, points, RAN...
Also consider using DENSE\_RANK() instead of RANK() when you want to increment the ranking of your 'position' by 1 as the 'points' change. RANK() will do what you want, though it will create number sequence gaps according to how many duplicate 'userids' are equal in 'points' standing's (if that's ever the case in your ...
update column with incremental value
[ "", "sql", "sql-server", "" ]
I've just started using SQL and I have a pretty basic question: I'm tried dividing 2 columns (amount/rate) - I converted them from 'money' to 'INT' but when I tried executing it gave me this error: > Operand data type varchar is invalid for divide operator. This is the query I typed: ``` select referenceid, ...
Try like this, ``` SELECT referenceid ,CONVERT(DECIMAL(15, 3), sellamount) AS 'amount' ,CONVERT(DECIMAL(15, 3), rateactual) AS 'Rate' ,CONVERT(DECIMAL(15, 3), (CONVERT(DECIMAL(15, 3), sellamount) / CONVERT(DECIMAL(15, 3), rateactual))) AS 'local amount' FROM currencyfxconversions ```
Your issue is that you're using a column that you use in the same context. You can't use am alias as a table column in the select context. You must repeat the last alias queries, as follows: ``` SELECT referenceid ,CONVERT(DECIMAL(15, 3), sellamount) AS 'amount' ,CONVERT(DECIMAL(15, 3), rateactual) AS 'Rate' ,CONVERT(...
Operand data type varchar is invalid for divide operator
[ "", "sql", "sql-server", "" ]
I have tables `users` and `topics`. Every user can have from 0 to several topics (one-to-many relationship). How I can get only those users which have at least one topic? I need all columns from users (without columns from topics) and without duplicates in table `users`. In last column I need number of topics. **UPD...
Firstly you need to have your two tables, because you have left limited information about your table structure I will use an example to explain how this works, you should then be able to easily apply this to your own tables. Firstly you need to have two tables (which you do) Table "user" ``` id | name 1 | Joe Blogg...
You can select topic number per user and then join it with user data. Something like this: ``` with t as ( select userid, count(*) as n from topic group by userid ) SELECT user.*, t.n FROM user JOIN t ON user.id = t.userid ```
SQL query (Join without duplicates)
[ "", "sql", "postgresql", "having", "" ]
I'm new to SQL queries and I need to make a join starting from this query: ``` SELECT b.Name, a.* FROM a INNER JOIN b ON a.VId = b.Id WHERE b.SId = 100 AND a.Day >= '2016-05-05' AND a.Day < '2016-05-09'; ``` and adding 2 more columns to the first selected data (SCap and ECap from table c). From what I'...
I found a solution for my query after some further investigations and here is what I managed to do: ``` SELECT b.Id, b.Name, c.S_Time, c.E_Time, s.Cap AS S_Cap, e.Capa AS E_Cap, FROM b INNER JOIN (SELECT VId, MIN(TimestampL...
You can use a `CTE` with `ROW_NUMBER` in order to retrieve the two records: ``` ;WITH Info_CTE AS ( SELECT VId, CAST (TimestampLocal AS DATE) AS Day, Cap, ROW_NUMBER() OVER (PARTITION BY VId ORDER BY TimestampLocal) AS rn1, ...
SQL Select where first value and last value of daterange
[ "", "sql", "sql-server", "t-sql", "" ]
I am attempting to get the maximum Decimal value from a column and then add 1 to it to get the next value. However, the column's values are of type varchar, meaning that I must filter to make sure that it only attempts to cast values it can, like '123,' while avoiding values like '123a' What I have attempted so far is...
What you are missing is empty strings. Your condition: *Id NOT LIKE '%[^0-9]%'* is true when Id is the empty string. This should work: ``` SELECT (MAX(CAST(Id AS DECIMAL(38,0))) + 1) AS 'New ID' FROM database WHERE Id NOT LIKE '%[^0-9]%' AND Id <> '' AND (LEN(Id) + 1) < 39 ``` The outer CAST is redundant (MA...
You should use `try_convert()`: ``` SELECT MAX(TRY_CONVERT(DECIMAL(38, 0), id)) + 1 AS [New ID] FROM database WHERE Id NOT LIKE '%[^0-9]%' AND (LEN(Id) + 1) < 39 ; ``` Your example converts back to a decimal, but I think you want a string: ``` SELECT TRY_CONVERT(VARCHAR(38), MAX(TRY_CONVERT(DECIMAL(38, 0), id)) + 1)...
Selecting maximum varchar casted into a decimal
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have two tables. ``` table_1 | table_2 id col_1 | col_2 | col_1 | col_2 1 1 | B | 1 | B 2 1 | C | 3 | C 3 1 | D | 5 | D .... ``` I write this query ``` SELECT * FROM table_1 t1 LEFT JOIN table_2 t2 ON t1.col_1 = t2.col_1 WHERE t1.col_1 = 1 AND ( ...
I *think* this is what you're looking for: ``` Select t1.* From table_1 t1 Left Join table_2 t2 On t1.col_1 = t2.col_1 And t2.col_1 != 'B' Where t1.col_1 = 1 And t2.col_1 Is Not Null ``` As I understand your question, you're looking to do a `LEFT JOIN` on the seco...
You only want results from table\_1, so you don't even need a join. ``` select * from table_1 t1 where not exists ( select 1 from table_2 t2 where t1.col_1 = t2.col_1 and t2.col_2 = t2.col_2 ) ``` You can provide any other `where` condition in the inner select statement to specify what type of match shou...
left join where b.key is null by two columns
[ "", "sql", "postgresql", "" ]
trying to generate a list of genres with the number of tracks and the % of tracks belonging to that genre. No of tracks should be order ascending. Output should look something like this with 3 seperate columns. ``` Genre No.of Tracks % of Tracks Rock 5 20% Genre table consists of - GenreI...
[Check at sqlfiddle](http://sqlfiddle.com/#!9/053e1a/2) ``` SELECT g.nameOfGenre, COUNT(t.TrackId) AS tracks_count, COUNT(t.TrackId) / tt.total_tracks * 100 AS tracks_percent FROM Genre g LEFT JOIN Track t ON t.GenreId = g.genreId JOIN (SELECT COUNT(*) AS total_tracks FROM Track) AS tt GROUP BY g.genreId ``` ...
**EDIT**: After seeing the OP's comment, I believe the following query should be more suitable. Unlike the answer below me, I will use an implicit join. ``` SELECT Genre.genreName, Track.trackName, COUNT(Track.genreID) AS "Track Count", ( ( (COUNT(Track.genreID) / COUNT(Track.trackID)) * 100 ) AS "Percent Of Tracks") ...
generate a list in sql
[ "", "mysql", "sql", "sqlite", "" ]
someone can help me please? I have a field with this structure: 2,3,4,5,6,0,1 they are day of the week and I have to find when if today is the last delivery day of the week, the problem is this: Example, today it's day 3 and with the following query I can select all the one that finish with the number 3 but if I have ...
With a CASE statement should look something like this: ``` declare @today int set @today=DATEPART(dw,GETDATE())-2 print @today select cfv.value from CompanyFieldvalues cfv join CompanyFields cf on cf.companyFieldId=cfv.companyFieldId where cf.name='NextDeliveryDates' and cfv.companyId in( select cfv.companyId from Co...
You can replace the CASE statement with the logical expression: ``` (((@today != 0 or @today!=1) AND (cfv.value not like '%,0' or cfv.value not like '%,1')) OR NOT (@today != 0 or @today!=1)) ``` So your query will become: ``` declare @today int set @today=DATEPART(dw,GETDATE())-2 print @today select cast (cfv.value...
SQL, Case with Like inside of the where
[ "", "sql", "database", "datetime", "case", "ssms-2012", "" ]
This is my statement ``` select * from table1 where col1 not in (select col2 from table2); ``` I want to try(but failed) ``` select t1.* from table1 t1 inner join table2 on t1.col1<> t2.col2 ``` Is there another way to do this?
``` select t1.* from table1 t1 left join table2 t2 on t1.col1 = t2.col2 where t2.col2 is null ``` This is standard implementation of missing record search.
If You try to find out the data of t1.c1 (t1=table1, c1=column1) that is exist or not exist in t2.c2 then use flowing script `select t1.c1 from t1 left join t2 on t1.c1=t2.c2` other wise if you want to find only t1.c1 data that is not in t2.c2 then below script is help full `select t1.c1 from t1 where t1.c1 not in (...
SQL:find table1.col1 not exist table2.col2, return table1's records
[ "", "sql", "" ]
Following is my table structure. ``` Measure type |Grade |date LNF |K |1/1/2016 LNF |K |2/1/2016 CNF |K |3/1/2016 LDR |K |4/1/2016 ``` LNF,CNF,LDR is measure types, K is grade level. I need to list only the la...
Try like this, ``` SELECT Measuretype ,Grade ,Max(DATE) as LatestDate FROM YourTableName GROUP BY Measuretype ,Grade ``` This would give output like this ``` Measure type |Grade |date LNF |K |2/1/2016 CNF |K |3/1/2016 LDR |K ...
Try this: ``` SELECT Measure type, Grade, MAX(date) FROM mytable GROUP BY Measure type, Grade HAVING COUNT(*) > 1 ``` The query returns records having duplicate `Measure type, Grade` values. It selects the latest date for each group as requested in the OP.
List only the latest record when measure type and grade same
[ "", "mysql", "sql", "" ]
I have a problem with a query.... I have a this query: ``` declare @today int set @today=DATEPART(dw,GETDATE())-2 select cast (cfv.value as VARCHAR), cfv.companyId from CompanyFieldvalues cfv join CompanyFields cf on cf.companyFieldId=cfv.companyFieldId where cf.name='NextDeliveryDates' and cfv.companyId in( select cf...
It looks like you are trying to implement conditional logic within your `WHERE` clause, but you are going about it incorrectly. You'll need to either break the statements up or use dynamic string building to create the query and execute it. It should look something like this. Depending on your validation routines for @...
Seeing that the data structure is this one: 2,3,4,5,6,0,1, I found a partially solution in this way: ``` declare @today int set @today=DATEPART(dw,GETDATE())-2-2 print @today select cast (cfv.value as VARCHAR) from CompanyFieldvalues cfv join CompanyFields cf on cf.companyFieldId=cfv.companyFieldId where cf.name='N...
SQL - Day of the week issue on select
[ "", "sql", "datetime", "sql-like", "week-number", "weekday", "" ]
SQL newbie here. So we have 3 tables: ``` categories(cat_id,name); products(prod_id,name); relationships(prod_id,cat_id); ``` It is a one-to-many relationship. So, given a category name say "Books". How do I find all the products that come under books? As an example, ``` categories(1,Books); categories(2,Pho...
You have to join tables on related columns and specify `WHERE` clause to select all records where category name = `'Books'` ``` SELECT p.* FROM categories c JOIN relationships r ON c.cat_id = r.cat_id JOIN products p ON r.prod_id = p.prod_id WHERE c.name = 'Books' -- or specify parameter like @Books ```
You need to `JOIN` the three tables. ``` SELECT p.* FROM relationships r INNER JOIN products p ON p.prod_id = r.prod_id INNER JOIN categories c ON c.cat_d = r.cat_id WHERE c.name = 'Books' ```
SQL Join involving 3 tables, how to?
[ "", "mysql", "sql", "join", "" ]
Let me describe my doubt. I have system where I have three entities, Doctor, Patient and Appointment. An appointment has the doctor's id and patient Id. I need now to retrieve all the patients which have an appointment with a concrete doctor, and I'm not sure what will be faster, a distinct or a subselect for the id's...
As with any performance question, you should test on your data and your hardware. The suspect problem in the first version the `DISTINCT` after the `JOIN`; this can require a lot of extra processing. You can write the second as: ``` SELECT p.id, p.name, p.surname FROM patient p WHERE p.id IN (select a.patientid FROM ...
Neither. These suffer from "inflate-deflate". That is, the `JOIN` leads to more rows in a temp table, only to prune back to what you need. This is costly. (And it can give wrong answers for `COUNT` and `SUM`.) ``` SELECT DISTINCT ... JOIN ... and SELECT ... JOIN ... GROUP BY ... ``` This performs poorly because of o...
What is faster, subselect or distinct (MySQL)?
[ "", "mysql", "sql", "mariadb", "" ]