Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have the following code that gets the months between two date ranges using a CTE ``` declare @date_start DateTime, @date_end DateTime ;WITH totalMonths AS ( SELECT DATEDIFF(MONTH, @date_start, @date_end) totalM ), numbers AS ( SELECT 1 num UNION ALL SELECT n.num + 1 num FRO...
This query is using two CTEs, one recursive, to generate a list of values from nothing (SQL isn't really good at doing this). ``` totalMonths AS (SELECT DATEDIFF(MONTH, @date_start, @date_end) totalM), ``` This is part is basically a convoluted way of binding the result of the `DATEDIFF` to the name `totalM`. This co...
`totalMonths` query evaluates to a scalar result (single value) indicating the number of months that need to be generated. It probably makes more sense to just do this inline instead of using a named CTE. `numbers` generates a sequence of rows with a column called `num` starting at `1` and ending at `totalM + 1` which...
Need help to understand SQL query
[ "", "sql", "sql-server", "common-table-expression", "" ]
I want to use the result of a `FULL OUTER JOIN` as a table to `FULL OUTER JOIN` on another table. What is the syntax that I should be using? For eg: T1, T2, T3 are my tables with columns id, name. I need something like: ``` T1 FULL OUTER JOIN T2 on T1.id = T2.id ==> Let this be named X X FULL OUTER JOIN T3 on X.id...
``` SELECT COALESCE(X.id,t3.id) AS id, *-- specific columns here instead of the * FROM ( SELECT COALESCE(t1.id,t2.id) AS id, * -- specific columns here instead of the * FROM T1 FULL OUTER JOIN T2 on T1.id = T2.id ) AS X FULL OUTER JOIN T3 on X.id = t3.id ```
Often, chains of full outer joins don't behave quite as expected. One replacements uses `left join`. This works best when a table has all the ids you need. But you can also construct that: ``` from (select id from t1 union select id from t2 union select id from t3 ) ids left join t1 on ids.i...
Multiple Full Outer Joins
[ "", "sql", "impala", "" ]
I have two tables, student and school. **student** ``` stid | stname | schid | status ``` **school** ``` schid | schname ``` Status can be many things for temporary students, but `NULL` for permanent students. How do I list names of schools which has no temporary students?
Using `Conditional Aggregate` you can count the number of `permanent student` in each `school`. If total count of a school is same as the conditional count of a school then the school does not have any `temporary students`. Using `JOIN` ``` SELECT sc.schid, sc.schname FROM student s JOIN school sc...
You can use `not exists` to only select schools that do not have temporary students: ``` select * from school s where not exists ( select 1 from student s2 where s2.schid = s.schid and s2.status is not null ) ```
SQL query using NULL
[ "", "sql", "postgresql", "" ]
I have a MySQL database with tables `countries` and `exchange_rates`: ``` mysql> SELECT * FROM countries; +----------------+----------+----------------+ | name | currency | GDP | +----------------+----------+----------------+ | Switzerland | CHF | 163000000000 | | European Union | EUR ...
Use a `left join` to include countries with missing exchange rates, and a case expression to always set USA GDP to USA GDP: ``` SELECT c.name, GDP, CASE WHEN c.name = 'USA' THEN c.GDP ELSE c.GDP/er.rate END AS 'GDP US$' FROM countries c LEFT JOIN exchange_rates er ON er.currency = c.currency; ``` Also,...
In order to get #1, you just need to use `left join` instead of inner join: ``` SELECT countries.name, GDP, countries.GDP/exchange_rates.rate AS 'GDP US$' FROM countries LEFT JOIN exchange_rates ON exchange_rates.currency=countries.currency; ``` In order to get #2, just add to the exchange\_rate table a record fo...
MySQL Join with condition when matching certain value
[ "", "mysql", "sql", "join", "left-join", "" ]
Suppose there are the following rows ``` | Id | MachineName | WorkerName | MachineState | |----------------------------------------------| | 1 | Alpha | Young | RUNNING | | 1 | Beta | | STOPPED | | 1 | Gamma | Foo | READY | | 1 | Zeta | Zatta |...
You can view this as a case of the group-wise maximum problem, provided you can obtain a suitable ordering over your `MachineState` column—e.g. by using a [`CASE`](http://www.postgresql.org/docs/current/static/functions-conditional.html#FUNCTIONS-CASE) expression: ``` SELECT a.Id, COALESCE(a.MachineName, t....
This is a prioritization query. One method uses variables. Another uses `union all` . . . this works if the states are not repeated for a given id: ``` select t.* from table t where machinestate = 'STOPPED' union all select t.* from table t where machinestate = 'RUNNING' and not exists (select 1 from table t2 wh...
Merging multiple rows according to an order
[ "", "sql", "psql", "" ]
I am moving from MS Access to SQL Server, yay! I know that SQL Server has a huge capacity over of 500k Terabytes, but I have also been told by my boss that SQL Server will eventually not be able to handle the rate I am inserting into my tables. I have a table with 64 columns and each day around ~20,000 rows are added ...
It has less to do with `sql server` and more to do with the box it's running on. How big is the hard drive? How much memory is in there? What kind of CPU is sitting on it? 20000 a day isn't so much, even with wide varchar(). But without good indexing, partitioning, and the memory, disk space and CPU to handle queries a...
**Very** rough, back-of-the-envelope calculations: * 16 bytes per field * 64 fields per record * 20,000 records per day You're adding 20MB per day to the table. 7GB per year. This is not a large amount of data. There are many people running multi-terabyte databases on SQL Server. What's more important is the proces...
How soon will SQL Server reach capacity at this rate?
[ "", "sql", "sql-server", "database", "" ]
``` select isnull(column1,'')+','+isnull(column2,'')+','+isnull(column3,'') AS column4 from table ``` From the above query, I am getting what I need, which is really good. But the thing here is if all the columns all `NULL` I am getting commas which I have used to separate the fields. I want comma is to be replaced w...
You might pack the `+ ','` into the `ISNULL()` ``` select isnull(column1+',','')+isnull(column2+',','')+isnull(column3,'') AS column4 from table ```
You can do this using `stuff()` like this: ``` select stuff((coalesce(',' + col1, '') + coalesce(',' + col2, '') + coalesce(',' + col3, '') ), 1, 1, '') ``` Other databases often have a function called `concat_ws()` that does this as well.
To NULL particular fields in retrieval time in sql
[ "", "sql", "sql-server", "" ]
I don't know how to ask that also this is an example. Say I have 2 tables: pages: ``` idpage title 0 first 1 second 2 third ``` reads: ``` idread idpage time 50 0 8:15 83 0 2:58 ``` If I do `SELECT * FROM pages,reads WHERE pages.idpage=reads.idpage AND pages.idpage<2` I will have...
Always use explicit `JOIN` syntax. *Never* use commas in the `FROM` clause. What you need is a `LEFT JOIN`. And, the way you are expressing the query makes this much harder to figure out. So: ``` SELECT p.idpage, p.title, COALESCE(idread, 0) as idread, COALESCE(time, cast('0:00' as time)) as time FROM p...
You need a left join and CASE expression to complete the values when they are null, like this: ``` SELECT p.*, case when r.idread is null then 0 else r.idread end as idread case when r.time is null then '0:00' else r.time end as time FROM pages p LEFT OUTER JOIN reads r ON(p.idpage = r.idpage) WHERE p...
Select row even if a condition is not true
[ "", "sql", "" ]
How do I combine the calculation date columns all into one column? What's the SQL function to make this happen? They rest of the fields are distinct values based on the calculation date. I only need the distinct values associated with the dates. [![enter image description here](https://i.stack.imgur.com/9SKqg.jpg)](ht...
You can use COALESCE ``` SELECT COALESCE(Calculation_Date, Calculation_Date) FROM tableName ```
Assuming only 1 of them will ever have a value, one option is to use `coalesce`: ``` select coalesce(date1, date2) from yourtable ```
T-Sql Combining Multiple Columns into One Column
[ "", "sql", "sql-server", "t-sql", "" ]
This is with respect to oracle Input ``` CUSTID FROMDT ACTIVITY NEXTDATE 100000914 31/01/2015 14:23:51 Bet 3.999996 100000914 31/01/2015 14:29:07 Bet 3.999996 100000914 31/01/2015 14:32:59 Bet 2 100000914 31/01/2015 14:35:35 Bet 1.999998 100000914 31/01/20...
``` SELECT CUSTID, ACTIVITY, total - LAG( total, 1, 0 ) OVER ( PARTITION BY CUSTID ORDER BY FROMDT ) AS total FROM ( SELECT CUSTID, FROMDT, ACTIVITY, SUM( NEXTDATE ) OVER ( PARTITION BY CUSTID ORDER BY FROMDT ) AS total, CASE ACTIVITY WHEN LEAD( ACTIVI...
``` select custid, activity, sum(amount) from (select jg_dig_test.*, (row_number() over (partition by custid order by fromdate) - row_number() over (partition by custid, activity order by fromdate) ) as grp from jg_dig_test ) jg_dig_test group by custid, grp, activity ORDER BY CUSTI...
Aggregations on Lead & LAG in oracle
[ "", "sql", "oracle", "window-functions", "" ]
I need to get the COUNT of each `id_prevadzka` IN 4 tables: First I tried: ``` SELECT p.id_prevadzka, COUNT(pv.id_prevadzka) AS `vytoce_pocet`, COUNT(pn.id_prevadzka) AS `navstevy_pocet`, COUNT(pa.id_prevadzka) AS `akcie_pocet`, COUNT(ps.id_prevadzka) AS `servis_pocet` FROM shop_prevadzky p LEFT J...
Try count distinct as in: Using your data sample **[SQL Fiddle Demo](http://sqlfiddle.com/#!9/9f63cd/3)** ``` SELECT p.id_prevadzka, COUNT(distinct pv.id) AS `vytoce_pocet`, COUNT(distinct pn.id) AS `navstevy_pocet`, COUNT(distinct pa.id) AS `akcie_pocet`, COUNT(distinct ps.id) AS `servis_pocet` ...
That is because you are joining all tables and created a cartesian product ``` shop_prevadzky x _vytoce x _navstevy x _akcie x _servis ``` You may want ``` SELECT p.*, (SELECT COUNT(id_prevadzka) FROM shop_prevadzky_vytoce s WHERE s.id_prevadzka = p.id_prevadzka) AS `vytoce_pocet`, (SELECT COUNT(id_preva...
SQL - How to use more COUNT on many tables?
[ "", "mysql", "sql", "left-join", "" ]
I have two records on my table: **Table:** ``` ID StartDate EndDate 1 2013-01-01 2016-01-01 2 2016-02-01 NULL ``` My query: ``` @DatePeriodFrom = 2016-01-01 @DatePeriodTo = 2016-01-01 select * from tableabove ta where (ta.StartDate >= @DatePeriodFrom and ta.EndDate >= @DatePeriodTo) ``` My problem here is ...
In case if you need to find all intersections of periods: ``` where ta.StartDate <= @DatePeriodTo and (ta.endDate IS NULL or ta.endDate >= @DatePeriodFrom) ```
``` select * from tableabove ta where ta.StartDate <= @DatePeriodFrom and (ta.endDate is NULL or ta.EndDate >= @DatePeriodTo) ``` Output: [Table values](https://i.stack.imgur.com/SPcm0.png) [![Output](https://i.stack.imgur.com/gRyJW.png)](https://i.stack.imgur.com/gRyJW.png) [![enter image description here](https://...
sql conditional where clause
[ "", "sql", "" ]
I've looked online a few days now to how to use STUFF on sql server, most of the examples I see are involving only two tables and my query is going through 3 tables and I just can't get it to work here is the query without the STUFF function which gets me all the data I want : ``` select c.category_name,r.role_name fr...
Here's a version of what I came up with. @GiorgosBetsos was correct that the `JOIN` needs to be moved to the inner query. I'm not sure why he's still seeing duplicates, but the following query returns the data as expected: ``` -- Set up the data DECLARE @roles TABLE (role_id INT, role_name VARCHAR(20)) DECLARE @role_c...
Try this: ``` SELECT DISTINCT c_out.category_name, STUFF((SELECT ',' + r.role_name FROM roles as r INNER JOIN role_categ as rc ON rc.role_id=r.role_id WHERE rc_out.category_id=rc.category_id FOR XML PATH('')),1,1,'') FROM role_categ AS rc_out JOIN categori...
SQL Server String Concat with Stuff
[ "", "sql", "sql-server", "string", "t-sql", "concatenation", "" ]
Here is the table information: Table name is Teaches, ``` +-----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+-------+ | ID | varchar(5) | NO | PRI | NULL | | | course_id | varchar...
You may try this: ``` SELECT DISTINCT T.course_id FROM teaches T WHERE T.course_id NOT IN ( SELECT T1.course_id FROM teaches AS T1 INNER JOIN teaches AS T2 ON T1.course_id = T2.course_id AND T1.`year` = T2.`year` AND T1.id <> T2.id WHERE T1.`year` = 2009...
For your homework, below sql can be done. This is followed your logic, id exist more than once is means course appeared more than once. ``` select DISTINCT T1.course_id from teaches T1 where T1.course_id not in ( select a.course_id from teaches as a inner join teaches as b on a.course_id = b.course_id and a.year...
Rewriting MySQL query without using GROUP BY
[ "", "mysql", "sql", "" ]
I want list all flights in flights table where Departure and arrival is egal to table 2. The specificity is that the Departure in flight is XXXX -dsdjqlkdjlqs or XXXXdkjfhkds etc... and in table 2 is only XXXX Code : ``` CREATE TABLE flights (`Name` varchar(10), `Departure` varchar(50), `Arrival` varchar(10),...
I think the following is what you are looking for: ``` Select flights.name, flights.Departure from flights inner join Table2 on Table2.Dep = SUBSTRING(flights.Departure,1,4) and Table2.Arri = SUBSTRING(flights.Arrival,1,4) ; ``` You need the SUBSTRING instead of wildcards, since you only want ...
``` select flights.name, flights.Departure from flights inner join table2 on substr(flights.Departure, 1, 4) = table2.Dep ```
SQL JOIN return record from table flights corresponding form table 2
[ "", "mysql", "sql", "join", "inner-join", "" ]
I would like to preface this by saying I am VERY new to SQL, but my work now requires that I work in it. I have a dataset containing topographical point data (x,y,z). I am trying to build a KNN model based on this data. For every point 'P', I search for the 100 points in the data set nearest P (nearest meaning geograp...
Doing updates row-by-row in a loop is almost always a bad idea and **will** be extremely slow and won't scale. You should really find a way to avoid that. After having said that: All your function is doing is to change the value of the column value in memory - you are just modifying the contents of a variable. If you...
I'm not sure if the proof of concept example does what you want. In general, with SQL, you almost *never* need a FOR loop. While you can use a function, if you have PostgreSQL 9.3 or later, you can use a [`LATERAL` subquery](http://www.postgresql.org/docs/current/static/queries-table-expressions.html) to perform subque...
Iterate through table, perform calculation on each row
[ "", "sql", "postgresql", "postgis", "" ]
When I try to insert data using AJAX without postback it's not inserting. I wrote AJAX in ajaxinsert.aspx page and I wrote a webmethod in the same page view code (i.e ajaxinsert.aspx.cs). What is the problem? ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ajaxinsert.aspx.cs" Inherits="ajaxweb.ajaxinsert...
Please modify below line in your above .aspx page code ``` data: { studentname: Name }, ``` To ``` data: JSON.stringify({studentname: Name }), ``` Javascript Code ``` <script type="text/javascript" > $(document).ready(function () { $("#insert").click(function (e) { e.preventDef...
Save data to database without postback using jQuery ajax in ASP.NET - See more at: <http://www.dotnetfox.com/articles/save-data-to-database-without-postback-using-jquery-ajax-in-Asp-Net-1108.aspx#sthash.7lXf0io7.dpuf> Please find the below link:- <http://www.dotnetfox.com/articles/save-data-to-database-without-postbac...
inserting data in sql database without postback in asp.net
[ "", "jquery", "sql", "asp.net", "asp.net-ajax", "" ]
I have this grouping problem that I can't seem to figure out. Any advice would be greatly appreciated! Let's say I have a table like this: ``` Name Passed? PlanID Plan ----------------------------------------- Tom 1 1 Math Tom 1 1 Reading Tom 0 ...
If there is a possibility that we may see multiple passes for the same name and you just want to pick up the first one, use below query: ``` select pass.name, pass.passed, pass.planID from (Select name, passed, planID from table where passed = 1) pass, (Select name, min(planID) planId from table where passed = 1) mi...
if return just passed? = 1 ``` select * from table where Passed? = 1 ``` returns as you want
SQL Grouping calculations
[ "", "sql", "group-by", "case", "" ]
I have in my Moodle `db` `table` for every `session` `sessid` and `timestart`. The table looks like this: ``` +----+--------+------------+ | id | sessid | timestart | +----+--------+------------+ | 1 | 3 | 1456819200 | | 2 | 3 | 1465887600 | | 3 | 3 | 1459839600 | | 4 | 2 | 1457940600 | | 5 |...
You can easy use this: ``` select sessid,min(timestart) FROM mytable GROUP by sessid; ``` **And for your second question, something like this:** ``` SELECT my.id, my.sessid, IF(my.timestart = m.timestart, 'yes', 'NO' ) AS First, my.timestart FROM mytable my LEFT JOIN ( SELECT sessid,min(timestart) AS ...
**Query** ``` select sessid, min(timestart) as timestart from your_table_name group by sessid; ``` Just an other perspective if you need even the `id`. ``` select t.id, t.sessid, t.timestart from ( select id, sessid, timestart, ( case sessid when @curA then @curRow := @curRow + 1 e...
Get first date from timestamp in SQL
[ "", "mysql", "sql", "moodle", "" ]
Ignore the practicality of the following sql query ``` DECLARE @limit BIGINT SELECT TOP (COALESCE(@limit, 9223372036854775807)) * FROM sometable ``` It warns that > The number of rows provided for a TOP or FETCH clauses row count parameter must be an integer. Why doesn't it work but the following works? `...
<https://technet.microsoft.com/en-us/library/aa223927%28v=sql.80%29.aspx> > Specifying bigint Constants > > Whole number constants that are outside the range supported by the int > data type continue to be interpreted as numeric, with a scale of 0 and > a precision sufficient to hold the value specified. For example, ...
``` DECLARE @x AS VARCHAR(3) = NULL, @y AS VARCHAR(10) = '1234567890'; SELECT COALESCE(@x, @y) AS COALESCExy, COALESCE(@y, @x) AS COALESCEyx, ISNULL(@x, @y) AS ISNULLxy, ISNULL(@y, @x) AS ISNULLyx; ``` Output: ``` COALESCExy COALESCEyx ISNULLxy ISNULLyx ---------- ---------- ...
SELECT TOP COALESCE and bigint
[ "", "sql", "sql-server", "" ]
I want to write a query for oracle that verifies if all combinations exist in a table. My problem is that the "key-columns" of the table are FKs linked to other tables, which means that the combinations are based on the rows of the other tables. ERD example: [![enter image description here](https://i.stack.imgur.com/Z...
You can identify all the possible combinations with [cross joins](http://docs.oracle.com/cd/E11882_01/server.112/e41084/statements_10002.htm#BABGHCBD), which generate the cartesian product of the rows: ``` select a.id, b.id, c.id from tablea a cross join tableb b cross join tablec c ``` Depending on the exact result ...
To get possible combinations, cross join works. So you can get your 24 rows with: ``` with a as ( select 1 id1 from dual union all select 2 id1 from dual union all select 3 id1 from dual ) , b as ( select 1 id2 from dual union all select 2 id2 from dual union all select 3 id2 from dual union...
Verify existance of all combinations in table
[ "", "sql", "database", "oracle", "combinations", "" ]
I'm querying an access db from excel. I have a table similar to this one: ``` id Product Count 1 A 0 1 B 5 3 C 0 2 A 0 2 B 0 2 C 5 3 A 6 3 B 5 3 C 7 ``` From which I'd like to r...
Use your `GROUP BY` approach in a subquery and `INNER JOIN` that back to the `[BD$]` table. ``` SELECT BD2.* FROM ( SELECT BD1.ID FROM [BD$] AS BD1 WHERE BD1.Product IN ('A','B') GROUP BY BD1.ID HAVING SUM(BD1.Count) > 0 ) AS sub INNER JOIN [BD$] AS BD2 ON sub.I...
IN() statement can perform badly a lot of times, you can try EXISTS() : ``` SELECT * FROM [BD$] BD WHERE BD.Product in('A','B') AND EXISTS(SELECT 1 FROM [BD$] BD2 WHERE BD.id = BD2.id AND BD2.Product in('A','B') AND BD2.Count > 0) ```
SELECT all rows where sum of count for this id is not 0
[ "", "sql", "excel", "ms-access", "" ]
i have two sql query in one of them i perform left outer join, both should return same no of records but returned no of rows are different in both the sql queries ``` select Txn.txnRecNo from Txn inner join Person on Txn.uwId = Person.personId full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo left j...
I suspect that the `TxnAdditionalInsured` table have **duplicate records**. use `distinct` ``` select distinct Txn.txnRecNo from Txn inner join Person on Txn.uwId = Person.personId full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured...
A `left` join will produce all rows from the left side of the join *at least* once in the result set. But if your join conditions are such that there are *multiple* rows from the right side that match a particular row on the left, that left row will appear multiple times in the result (as many times as it is matched w...
returned no of rows different on left join
[ "", "sql", "sql-server", "" ]
The database itself is about storing cocktails with their own recipes (Recipe) and ingredients (RecipeIngredient). Each user (User) has their own "pantry" (UserIngredients) in which they can store the ingredients they have at home. This query should now show them the cocktails they can mix I've got the following query...
Try ``` SELECT u.User_Name, MAX(r.Recipe_Name) FROM User u INNER JOIN UserIngredient ui ON u.User_ID = ui.User_ID INNER JOIN RecipeIngredient ri ON ui.Ingredient_ID = ri.Ingredient_ID INNER JOIN Ingredient i ON ri.Ingredient_ID = i.Ingredient_ID INNER JOIN Recipe r ON ri.Recipe_ID = r.Recipe_ID WHERE u...
To get the desired result using this database, try ``` SELECT DISTINCT u.User_Name, r.Recipe_Name FROM User u INNER JOIN UserIngredient ui ON u.User_ID = ui.User_ID INNER JOIN RecipeIngredient ri ON ui.Ingredient_ID = ri.Ingredient_ID INNER JOIN Ingredient i ON ri.Ingredient_ID = i.Ingredient_ID INNER ...
How do I limit the result to just different results?
[ "", "mysql", "sql", "" ]
I have a column (XID) that contains a varchar(20) sequence in the following format: xxxzzzzzz Where X is any letter or a dash and zzzzz is a number. I want to write a query that will strip the xxx and evaluate and return which is the highest number in the table column. For example: ``` aaa1234 bac8123 g-2391 ``` Af...
A bit painful in SQL Server, but possible. Here is one method that assumes that only digits appear after the first digit (which you actually specify as being the case): ``` select max(cast(stuff(col, 1, patindex('%[0-9]%', col) - 1, '') as float)) from t; ``` Note: if the last four characters are always the number yo...
Using Numbers table ``` declare @string varchar(max) set @string='abc1234' select top 1 substring(@string,n,len(@string)) from numbers where n<=len(@string) and isnumeric(substring(@string,n,1))=1 order by n ``` **Output:1234**
A query that will search for the highest numeric value in a table where the column has an alphanumeric sequence
[ "", "sql", "sql-server", "" ]
I am creating a library system that only has 1 copy of each book. The user would enter the book and the dates they want it for. After the system would check that the book is not reserved for the dates the user wants it. I'm trying to insert data into a table if the variables are not already in the table. e.g. if the i...
Turns out that I needed to just do the two things separately, in different parts of my code.
You problably want something like this: ``` INSERT INTO table_name (name, id, start_date, end_date, days) SELECT name, id, start_date, end_date, days FROM (SELECT 'test' AS name, 4 AS id, '0000-00-00' AS start_date, '1000-00-00' AS end_date, 3 AS days) AS t WHER...
SQL insert into a table depending on values in the table
[ "", "mysql", "sql", "select", "insert-into", "" ]
I have to show "birthday" days in format 'dd.mm' from format 'dd.mm.yy' but only if that "birthday" has more than 10 employees from table named "employeeFirm". when I go : `select birthday from employeeFirm;` I get: ``` 01.11.73 08.09.77 01.11.65 01.11.74 (null) (null) 01.11.85 (null) 01.11.88 01.11.65 01.11.56 01.11...
Try this: ``` SELECT ddmm, count FROM ( SELECT distinct Substr(Birthday,1,5) as ddmm , Count(Birthday) OVER(PARTITION BY Substr(Birthday,1,5)) AS count from employeeFirm ) A where count> 10 ```
You can use TO\_CHAR like this: ``` SELECT case when t.formated is not null then t.formated else to_char(s.birthday,'DD.MM.YYYY') end as new_birthDay FROM employeeFirm s LEFT OUTER JOIN(SELECT TO_CHAR(birthday,'DD.MM') as formated FROM employeeFirm GROUP B...
Show "birthday" days in format 'dd.mm' from format 'dd.mm.yy' but only if that "birthday" has more than 10 employees
[ "", "sql", "oracle", "" ]
Why am getting this error > Incorrect syntax near the keyword when I execute the below code ``` SELECT * FROM [dbo].[priority_table] p WHERE EXISTS ( (SELECT 1 FROM [dbo].[item_table] i WHERE i.priority_id = p.priority_id) AND filter = @filter ) OR ( @filter I...
Move the `Open parenthesis` before `EXISTS` ``` SELECT * FROM [dbo].[priority_table] p WHERE ( EXISTS (SELECT 1 FROM [dbo].[item_table] i WHERE i.priority_id = p.priority_id) AND filter = @filter ) OR ( @filter IS NULL ) ```
This is not ju-ju magic. Exists in a where clause is just written like a sub-query (specifically a semi-join), thus (extra lines added for emphasis): ``` SELECT * FROM [dbo].[priority_table] p WHERE EXISTS ( SELECT 1 FROM [dbo].[item_table] i WHERE i.priority_id = p.priority_id AND (i.filter = @...
Incorrect syntax near the keyword when using EXISTS
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
Table `tmp` : ``` CREATE TABLE if not exists tmp ( id INTEGER PRIMARY KEY, name TEXT NOT NULL); ``` I inserted 5 rows. `select rowid,id,name from tmp;` : | rowid | id | name | | --- | --- | --- | | 1 | 1 | a | | 2 | 2 | b | | 3 | 3 | c | | 4 | 4 | d | | 5 | 5 | e | Now...
I assume you already know a little about `rowid`, since you're asking about its interaction with the `VACUUM` command, but this may be useful information for future readers: `rowid` is [a special column available in all tables](https://www.sqlite.org/lang_createtable.html#rowid) (unless you use `WITHOUT ROWID`), used ...
I found a solution for some case. I don't know why, but this worked. 1.Rename column "id" to any other name (not PRIMARY KEY) or delete this column because you have already "rowid". ``` CREATE TABLE if not exists tmp ( my_i INTEGER NOT NULL, name TEXT NOT NULL); ``` 2.In...
How to get rid of gaps in rowid numbering after deleting rows?
[ "", "sql", "sqlite", "" ]
I have a ticket details table that stores the information of transactions. Here is an example of the table data: ``` Ticket_Number Detail_type_ID Description Date_Created TotalAmount Barcode 1 11 Card Sale 1/1/16 5 123 1 1 Book ...
Stab in the dark. I'm not sure I fully understand your requirements quite right. ``` with Sales as ( select t.Barcode, t.Date_Created as Sale_Date, row_number() over (partition by t.Barcode order by t.Sale_Date) as Load_Seq from <Transactions> as t where Description = 'Card Sale' ...
You can do this with a self-join or with a subquery. Here is some pseudo-code ``` SELECT t1.Barcode, SUM(t1.Date - t2.Date) FROM TheTable t1 JOIN TheTable t2 ON t1.Barcode=t2.Barcode AND t1.Code = 'Redemption' AND t2.Code = 'Sale' GROUP BY Barcode ``` And then to get that last row you'll have to UNION with another q...
How to find number of days between results
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2008-r2", "" ]
I have a mini database (`mymoney`) which has a column called `total_amount`. Now I would like to get this column and ad an extra column `GRP2` (with values `low`, `medium` or `high`) based on the row value in the `total_amount` column. **So I have this**: ``` total_amount 5000 27000 36000 50000 ``` **And I would like...
You are misusing the `CASE` expression. Try like this: ``` SELECT total_amount, CASE WHEN total_amount <= 30000 THEN 'low' WHEN total_amount > 30000 AND total_amount <= 40000 THEN 'medium' ELSE 'high' END AS GRP2 FROM gates_money ```
You are use simple CASE expression whereas you need searched CASE expression ``` SELECT mymoney.total_amount, CASE WHEN mymoney.total_amount <= 30000 THEN 'low' WHEN mymoney.total_amount >= 31000 AND mymoney.total_amount <= 40000 THEN 'medium' ELSE 'high' END AS GRP2 FROM mymoney ```
SQL CASE conditions always returning ELSE value
[ "", "sql", "sqlite", "case", "" ]
How can I convert month number to month name if have following records: eg. ``` select date from tableClient; 17.01.07 18.02.08 18.03.08 18.04.08 18.05.08 18.06.08 18.07.08 18.08.08 ``` Expected result is : ``` 17.January.07 18.February.08 18.March.08 18.April.08 ...... ``` How to convert just MM from that that r...
You have to use `to_char()` function with `trim()` function to get rid off extra spaces after month name: ``` select trim(to_char(sysdate, 'dd.Month')) || '.' || to_char(sysdate,'yy') from dual; ``` With your example: ``` select id, firstName, lastName, trim(to_char(date, 'dd.Month')) || '.' || to_char(date,'yy') f...
Use **TO\_CHAR** with `FMMONTH` to **display** the date in your **desired format**. From the [documentation](https://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00216), > Format Model Modifiers > > The FM and FX modifiers, used in format models in the TO\_CHAR > function, control blank pad...
Convert month number to month name from two tables
[ "", "sql", "oracle", "" ]
I understand why you use `COUNT(*)` and `COUNT(DISTINCT col)`, but in which cases would you use simply `COUNT(col)`. Wouldn't `COUNT(col)` return the same result as `COUNT(*)`? ``` SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders WHERE CustomerID=7; ``` and ``` SELECT COUNT(*) AS OrdersFromCustomerID7 F...
When you use **COUNT(Colomn)** It won't count **nulls**. As opposed to **COUNT(\*)** which will count **each row** individually no matter null or not. Lets take this case: ``` ID | NAME 1 John 2 NULL 3 Jonathan SELECT COUNT(*) FROM Table -- return 3 SELECT COUNT(NAME) FROM Table -- return 2 ``...
Try this: ``` DECLARE @tbl TABLE(ID INT IDENTITY,SomeValue INT); INSERT INTO @tbl VALUES(1),(2),(NULL); SELECT * FROM @tbl SELECT COUNT(*) AS COUNT_Asterisk ,COUNT(SomeValue) AS COUNT_SomeValue FROM @tbl ```
When would you use a column name instead of * in a count?
[ "", "sql", "count", "" ]
I have two separately unique columns in a table: `col1`, `col2`. Both have a unique index (`col1` is unique and so is `col2`). I need `INSERT ... ON CONFLICT ... DO UPDATE` syntax, and update other columns in case of a conflict, but I can't use both columns as `conflict_target`. It works: ``` INSERT INTO table ... O...
## A sample table and data ``` CREATE TABLE dupes(col1 int primary key, col2 int, col3 text, CONSTRAINT col2_unique UNIQUE (col2) ); INSERT INTO dupes values(1,1,'a'),(2,2,'b'); ``` ## Reproducing the problem ``` INSERT INTO dupes values(3,2,'c') ON CONFLICT (col1) DO UPDATE SET col3 = 'c', col2 = 2 ``` Let's c...
`ON CONFLICT` requires a unique index\* to do the conflict detection. So you just need to create a unique index on both columns: ``` t=# create table t (id integer, a text, b text); CREATE TABLE t=# create unique index idx_t_id_a on t (id, a); CREATE INDEX t=# insert into t values (1, 'a', 'foo'); INSERT 0 1 t=# inser...
Use multiple conflict_target in ON CONFLICT clause
[ "", "sql", "postgresql", "upsert", "" ]
I have this table with multiple columns. Primary key is `(type,ref,code)` with row type `t1`, `t2`, and two states Valid `(V)` and Invalid `(I)`. Every invalid row in state `t1` should have a valid row in the state `t2`, but my table already has some rows with Invalid state that don't have the valid row in the state `...
You can use the following query to get to-be-duplicated rows: ``` SELECT type, ref, code, state FROM mytable AS t1 WHERE state = 'I' AND type = 't1' AND NOT EXISTS (SELECT 1 FROM mytable AS t2 WHERE t1.ref = t2.ref AND t1.code = t2.code AND state = 'V'...
If it is a primary key, must be unique and not null for definition. so if you need two or more states you need another table, or another field(if just two) but than get seek to query
Duplicate All single rows in database table
[ "", "sql", "sql-server", "sql-insert", "not-exists", "" ]
I have searched this website for all possible solutions but still can't find an answer for my Pivot problem. I have a table with the following data. ``` Portfolio | Date | TotalLoans | ActiveLoans | TotalBalance -------------------------------------------------------------------- P1 | 2015-12-31 | ...
You need first to [**`UNPIVOT`**](https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx?f=255&MSPPError=-2147217396) your table. You can do it using this query: ``` SELECT Portfolio, [Date], Val, ColType FROM (SELECT Portfolio, [Date], TotalLoans, ActiveLoan...
This is Giorgos Betsos solution as dynamic SQL. This will deal without the need to write the date values explicitly. Please: If you like this: **Do not** mark this solution as accepted, set the acceptance to Giorgos Betsos. There's the hard work! But you may vote on it :-) ``` CREATE TABLE #tbl(Portfolio VARCHAR(10),...
SQL Server Pivot on multiple fields
[ "", "sql", "sql-server", "pivot", "" ]
I've been just transferred to the new job site and given a set of sqls which are in operation. There are several sqls which are written like [A] below. What looks weird to me is that the alias of the table is the same as the table name itself. Allow me to ask you two questions about [A]. ``` [A] select /*+ INDEX(Table...
Yes, the first hint appears to be syntactically valid (though presumably you can test that yourself) assuming that `IDX01` is an index that exists on `TableA` and that it is possible for the query to use that index. I'm not a fan of having this sort of hint in production code since it generally implies that you're tryi...
I would like to respond only to your second question. It is absolutely OK to provide an alias with the same name as the table, and absolutely unnecessary to do so. It adds no clarity, and you can still use the `table_name.column_name` syntax without the alias.
Oracle SQL - a hint clause and a table alias
[ "", "sql", "oracle", "" ]
I'm trying to load a local DB with SQLite under a RedHat Linux server. I have a C code to load the database from a very large file spliting the columns. The bad new is that sqlite3 is not installed in the machine (`fatal error: sqlite3.h: No such file or directory`) and I won't be able to have permissions to install `l...
You can use the [amalgation](https://www.sqlite.org/amalgamation.html) version. It is a single `.c` file you can include in your project, and all of SQLite is available. No need for dynamic linking.
You could probably try to dynamically load the sqlite3 library at runtime. There are quite few stuff to learn about it, but that's a powerful functionality and I am quite sure this would solve your problem. Here is a link describing how you can do it : <http://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html>
How to use sqlite3 in C without the dev library installed?
[ "", "sql", "c", "bash", "sqlite", "" ]
My scenario is to have a table for logging and reporting some important settings that users can change in a set of sites we maintain (each site has its own DB). When I was designing the table (going to be deployed on each DB), I was confused if I require a `Primary Key` or not. I have a column named `SiteID` and each r...
You need to focus on your use case. If you can avoid data duplication (e.g. from the application side) and you know your data, and know what type of index etc. you need, you can easily avoid that; mainly if you talking about massive scans for reporting and when data duplication is not issue. In many MPP databases (da...
A table without duplicate rows *always has* at least one candidate key. We can pick one to declare via `PRIMARY KEY`; any others are via `UNIQUE NOT NULL`. (`UNIQUE NOT NULL` is the constraint that you get from a `PRIMARY KEY` declaration.) If you don't *tell* the DBMS about your candidate keys then it can't help you b...
No primary key vs Composite primary Key
[ "", "sql", "database-design", "" ]
I have a table `Product`: ``` Name Description ---------------------- x 1 y 2 z 3 ``` I have another table `Producttemp`: ``` Name Description ------------------ x 1 x 1 x 2 r 3 r 3 z 8 z 8 ``` I nee...
Try this one ``` INSERT INTO [Product] SELECT DISTINCT PT.[Name],PT.[Description] FROM [Producttemp] AS PT LEFT OUTER JOIN [Product] AS P ON P.[Name] = PT.[Name] AND P.[Description] = PT.[Description] WHERE P.[Name] IS NULL ```
From what I understood you do not want to insert rows from '**Producttemp**' that are already in '**Product**'. For this you can use **MERGE** ``` MERGE Product AS P USING(SELECT DISTINCT Name,Descrip FROM Producttemp) AS PT ON P.Name = PT.Name AND P.Descrip=PT.Descrip WHEN NOT MATCHED THEN INSERT(Name,Descrip) VAL...
Insert of data in a query in SQL Server
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I have a table (in SQL Server) that has 2 columns. One column contains multiple server names separated with a tilda `~`. This column could or could not contain the actual server name. The other column has the actual server name. I am looking for a way to separate the first column values into their own separated column...
@Hogan - I ended up combining your script with some help from the link that @Sean Lange put in his comment. Here is what I came up with. ``` WITH splitit AS ( SELECT y.i.value('(./text())[1]', 'nvarchar(4000)') as Separated_Server, Actual_Server_Name FROM ( SELECT x = CONVERT(XML, '<i>' ...
The easiest way to accomplish this is with a string splitter. Aaron Bertrand has fairly complete list of viable options here. <http://sqlperformance.com/2012/07/t-sql-queries/split-strings>. Notice that none of these have any loops or recursion. I am not quite sure what you are trying to do with this information but yo...
SQL - Separate Out Text From String
[ "", "sql", "sql-server", "substring", "" ]
``` EmpID EmpName EmpSalary EmpDept 1 Steve 5000 HR 2 Robert 5000 Management 3 Brad 3000 HR 4 Sam 4000 HR 5 Dave 2000 Management 6 Stuvart 4500 Management ``` How to get employee details from the EMPLOYEE table whose salary ...
You can use an `order by` clause with `rownum` for Oracle *version < 12c*: ``` SELECT EmpID, EmpName, EmpSalary, EmpDept FROM EMPLOYEE WHERE ROWNUM = 1 AND EMPDEPT = 'HR' ORDER BY EmpSalary DESC ``` Otherwise you can use the following: ``` SELECT EmpID, EmpName, EmpSalary, EmpDept FROM EMPLOYEE WHERE EMPDEPT = '...
``` SELECT EmpID,EmpName,MAX(EmpSalary),EmpDept FROM Employee WHERE EmpDept='HR' GROUP BY EmpSalary ```
Maximum salary of employee in specific department
[ "", "sql", "oracle", "performance", "oracle11g", "" ]
I have a table called **emp**: ``` ╔════╦══════╦═══════════╗ ║ id ║ name ║ fathersid ║ ╠════╬══════╬═══════════╣ ║ 1 ║ a ║ 2 ║ ║ 2 ║ s ║ null ║ ║ 3 ║ d ║ 1 ║ ║ 4 ║ f ║ 3 ║ ╚════╩══════╩═══════════╝ ``` I want to print the name corresponding with its father's name. I have ...
Its almost correct, you need to alias the tables so the reader will know you are comparing the inner query to the outer query : ``` SELECT t.NAME, (SELECT s.name FROM emp s where s.id = t.father_id) as Father_name FROM emp t ``` You can do this with a join: ``` SELECT t.name,s.name as Father_Name FROM emp t L...
I prefer to solve this type of problem using a self-join: ``` SELECT e1.name AS name, COALESCE(e2.name, 'Not Available') AS fatherName FROM emp e1 LEFT JOIN emp e2 ON e1.fathersid = e2.id ```
Query for replacing one field with the value of corresponding field
[ "", "mysql", "sql", "database", "oracle", "" ]
I need to assign two values to my select based on a CASE statement. In pseudo: ``` select userid , case when name in ('A', 'B') then 'Apple' when name in ('C', 'D') then 'Pear' end as snack from table ; ``` I am assigning a value for `snack`. But lets say I also want to assign a value fo...
Functions destroy performance. But you could use a common-table-expression(cte): ``` with cte as ( Select IsNameInList1 = case when name in ('A', 'B') then 1 else 0 end, IsNameInList2 = case when name in ('C', 'D') then 1 else 0 end, t.*...
When doing things like this I tend to use a join with a [table valued constructor](https://msdn.microsoft.com/en-us/library/dd776382.aspx): ``` SELECT t.UserID, s.Snack, s.Drink FROM Table AS T LEFT JOIN (VALUES (1, 'Apple', 'Milk'), (2, 'Pear', 'Cola') ...
How to assign multiple values in CASE statement?
[ "", "sql", "sql-server", "case-statement", "" ]
I have a select statement: ``` select DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time from table 1 ``` now, how to add into next column if statement: ``` contract_time >= 390 then display A contract_time < 390 then display B contract_time is null display C? (because Contract start date or En...
Use a [case expression](https://msdn.microsoft.com/en-us/library/ms181765.aspx): ``` ;With cte as ( select DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time, a, b, c from table 1 ) select contract_time case when contract_time is null then c when contract_time >= 390 then a ...
Use IIF function which supports in SQL Server 2012 otherwise you can also use CASE WHEN...THEN ...END ``` ;With cte_table1 as ( SELECT DATEDIFF(day,[Contract Start Date],[Contract End Date]) as contract_time, A, B, C FROM [table 1] ) SELECT contract_time, IIF(contract_time i...
If statement based on other column
[ "", "sql", "sql-server", "datetime", "if-statement", "switch-statement", "" ]
I have three tables: `albums`, `songs`, and `images`. The tables look something like this: `albums` table: ``` id | title | image_id 5 | First Album | 1 6 | Another Album | 2 ``` `songs` table: ``` id | album_id | title | image_id 32 | 5 | My Song |...
Here is a solution using multiple LEFT JOINs, with demo using data you provided. The final query: ``` SELECT s.title, COALESCE(i1.path, i2.path) FROM songs s LEFT JOIN albums a ON s.album_id = a.id LEFT JOIN images i1 ON s.image_id = i1.id LEFT JOIN images i2 ON a.image_id = i2.id ORDER BY s.id; ``` Below ...
Something like this should work: ``` SELECT s.title, COALESCE(si.path, ai.path) FROM albums AS a INNER JOIN songs s ON a.id = s.album_id LEFT JOIN images ai ON i.id = a.image_id LEFT JOIN images si ON i.id = s.image_id ``` Note that you have to join the `images` table to the `albums` table AND to the `songs` table. `...
MySQL conditional LEFT JOIN?
[ "", "mysql", "sql", "" ]
I have a Table with two colums. * The first column is a date stored as: (example): `01/01/2015 00:00:00` * The seconds column is a number : as (example) : 500 I have written an SQL Statement which looks like this: ``` select * from cc_open_incident_view WHERE (DATE =(NOW() - INTERVAL 1 MONTH)) ``` If I execute thi...
Edit: Changed query as per OP ``` select * from cc_open_incident_view WHERE date between (CURDATE() - INTERVAL 1 MONTH ) and CURDATE() ``` Previous Answer: If date is saved as `date` then use this ``` select * from cc_open_incident_view WHERE date >= (CURDATE() - INTERVAL 1 MONTH ) ``` If date is saved as string...
``` SELECT * FROM cc_open_incident_view WHERE yourdatetimecolumn BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() ``` Also note that `CURDATE()` returns only the `DATE` portion of the date, so if you store `yourdatetimecolumn` as a `DATETIME` with the time portion filled, this query will not select the today's ...
Mysql -- Last 30 days
[ "", "mysql", "sql", "" ]
I am using a smartphone to collect data from the accelerometer and then saving it in a postgresql database, in a server. Basically, each time I read the accelerometer, I save the latitude/longitude at which the smartphone is at the moment, as well as the timestamp where it happened. Now, I want to read from the databa...
``` SELECT latitude, longitude, count(1) as "Count", min(timestamp) as "Start", max(timestamp) as "End" FROM table GROUP BY latitude, longitude ORDER BY min(timestamp) asc ```
``` create or replace function foo( out latitude numeric, out longitude numeric, out cnt int, out start_time numeric, out end_time numeric ) returns setof record as $$ declare c record; p record; i int := 1; begin select null into p; for c in (select * from table order by timestamp) loop if ...
Preserve order from subquery (with GROUP BY and ORDER BY)
[ "", "sql", "postgresql", "group-by", "sql-order-by", "" ]
i am writing sql and I am stuck in the following line ``` select employeeid, (case paidL when'1' Then 1 when '0' Then 0 end)...
Your case syntax is obviously wrong. But you have another error: *Never* use single quotes for column aliases. This is an example of an error waiting to happen. It is best to use column and table names that do not need to be escaped. If they do, use square braces or double quotes. The query you want should look like ...
Your case syntax is all wrong, use this : ``` select employeeid, (case when paidL = '1' Then 1 when paidL = '0' Then 0 end) as paidLeave from Lea order by employeeid ``` Also, order by comes after group by! An...
sql syntax is not working with group by clause
[ "", "sql", "sql-server", "" ]
I have a table that contains the number of workers in a set of different job fields, in all of the wards in the country. How can you find the number of wards that have more than x amount of workers (across all job fields)? My current query looks like this: ``` SELECT (SELECT COUNT(1) FROM Table WHERE (SELECT SUM...
``` select count(ward) from (SELECT ward FROM Table GROUP BY ward having SUM(working) > x) t ```
``` SELECT ward, SUM(working) FROM YourTable GROUP BY ward HAVING SUM(working) > @x ```
How do you count all of the values in a column that satisfy your condition? (sqlite)
[ "", "sql", "sqlite", "count", "" ]
I have a table like below and wish to select distinct people e.g row 2, 9, 11, 20. I don't want to select MAX() as that's not random. And I don't want to select Jack twice. It needs to be one person from each set of records ``` ID Name Category Level 1 Jack Dragon 3 2 Jack Falls 5 3 Jack Sp...
Assuming set of records = rows with the same value of "Name": ``` with cte_random as ( select *, rank() over (partition by forenames order by newid()) as rnk from tbl ) select id, name, category, level from cte_random where rnk = 1 ```
This seems trickier than it sounds, creating a `temp` table with an extra `tempId` column should work. Try: ``` create table #temp(ID int, Name char(10), Category char(10), Level int, tempId varchar(36)) insert #temp select ID, Name, Category, Level, NEWID() as 'tempId' from yourTable select ID, Name, Category, Level...
SQL select random record
[ "", "sql", "sql-server", "random", "newid", "" ]
Here's the problem. :( A column of my table `Answers` which is like ``` Answers ------------------------------------ id | user_id | question_id | ans ------------------------------------ 1 | 1 | 1 | 0 2 | 1 | 2 | 85 3 | 2 | 1 | 5 4 | 2 ...
Yes. One method uses a `case` statement: ``` select a.*, (case when a.id is not null then coalesce(ans, -1) end) as ans from b left join a on b.answerid = a.id; ``` I just made up the `join` conditions and columns. The key is to use the join key to determine if there is a record match.
You'll need to check the existence of a not-nullable column in the answers table, like this: ``` select ..., case when answers.ans is not null then answers.ans when answers.id is not null then -1 else null end ```
Is it possible to do a left outer join where something other than NULL fills the non-values?
[ "", "sql", "sql-server", "t-sql", "database-design", "" ]
I have two tables, one is `Countries` that contains `codeCountry` and `nameCountry` and second table `Client` that contains `privat_code_country.` CodeCountry for example AUS and nameCountry Austria. I want to select all the countries that have a minimum number of clients, in other words, I have to join this two table...
You need a RANK: ``` select * from ( select s.codeCountry, count(*) as cnt, rank() over (order by count(*)) as rnk -- rank based on increasing counts from countries s join client t on s.codeCountry = t.privat_code_country group by s.codeCountry ) dt where rnk = 1 `...
If you want the list of countries which share the minimum number of clients: ``` select x.codeCountry, x.cnt as number_of_clients from ( select t.codeCountry, min(t.cnt) over () as min_cnt, t.cnt from ( select s.codeCountry, count(*) as cnt from countries s join ...
Select all the countries that have a minimum number of clients
[ "", "sql", "oracle", "" ]
It's not gentlemanly to not like many items. But I need a query that `exclude` many items (`not in`) using a list of many items using `not like`. ``` | source | |========| | danny | | ram | | nach | | boom | | trach | | banana | | key_exclude | |================| | danny | | ram | | l...
Here is a solution query using subqueries: ``` select * from source AS s where s.`key` not in( select k.`key` from key_exclude AS k ) AND NOT EXISTS( select 1 from like_exclude l WHERE s.`key` LIKE CONCAT('%', l.`key`, '%')); ``` Below is a full demo with data verified, also put on SQLFiddle by OP <http://sq...
Let me first say that it is indeed very ungentlemanly not to like so many things. But sometimes you just have to... Anyways..one way to do it is to use `RLIKE` in combination with `GROUP_CONCAT` instead of `LIKE`. That would result in something like this. This will probably go 'wrong' if there are special regexp chara...
How to not likes many items in MySQL?
[ "", "mysql", "sql", "" ]
I have create a report using visual studio 2015 with SSDT Tools installed from the following link <https://msdn.microsoft.com/en-us/mt186501> The database is on SQL Server 2014. The reports work on my machine however when I try to upload a report on customers machine(Which has SQL Server 2014 and not visual studio). ...
If you have the solution > properties > TargetServerVersion set to SQL Server 2008 R2, 2012 or 2014 and then upload the RDL from the bin folder instead of the project folder, it should work. I was getting the same error and that solved it.
Your report is targeting SQL server 2016
Error while uploading a report
[ "", "sql", "reporting", "sql-server-data-tools", "" ]
My `requirement` is to calculate the `distance` between two `locations` on a given [map](https://www.google.co.in/maps?source=tldsi&hl=en) using [mysql](https://www.mysql.com/). I found a function in [mysql](https://www.mysql.com/) named [ST\_Distance\_Sphere](https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience...
[ST\_DISTANCE\_SPHERE](https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html#function_st-distance-sphere) requires points to be expressed as `POINT(longitude, latitude)`, you have them reversed in your code ``` set @lat1 = 38.898556; set @lon1 = -77.037852; set @lat2 = 38.897147; set @lon2 = -77.0...
**For all who are working with MYSQL 8:** For all mysql geolocation functions there **must** be the right **SRID** used, otherwise you won't get the right results. Most commenly used is SRID 4326 (GPS Coordinates, Google Earth) AND SRID 3857 (used on Google Maps, OpenStreetMap, and most other web maps). Example of a...
ST_Distance_Sphere in mysql not giving accurate distance between two locations
[ "", "mysql", "sql", "mysql-workbench", "" ]
I have rows in Oracle database table (having +2M records) and I want to extract records with some condition. The constraint is not setup on the table. Any help will be appreciated. ``` nif num_sum -------------------------- 123 456 123 456 123 789 ...
Given your description, "Records having a nif with one or more same num\_sum is allowed (a nif shouldn't be for two different num\_sums)" I think you want the following: ``` SELECT nif FROM sumcon GROUP BY nif HAVING COUNT(DISTINCT num_sum) > 1; ``` First, in your original query `DISTINCT` is superfluous. Next, ...
You don't return any records because there's only 1 distinct value for `nif`, so the count is not greater than 1.
Sql: Extract records with some condition
[ "", "sql", "oracle", "" ]
I'm trying to extract transaction details from two already existing tables: 1. `transactions`, containing the total amount received, 2. `bills`, with a row for each bill received in the transaction, and containing the denomination of the bill. Both are indexed with a common `session` id. [*Correction:* only the `tran...
Do not use correlated subqueries. That's inefficient. And **do *not* include `b.denom`** in the `GROUP BY` clause. That's your primary error. ### Postgres 9.4+ In Postgres **9.4** or later use the dedicated aggregate `FILTER` feature: ``` SELECT t.session , to_char(t.amount::numeric, '"$"9990D99') AS "USD" ...
I think you are almost there. You need to do another group by after your query. For instance: ``` WITH q1 as (SELECT t.session, to_char(t.amount::numeric, '"$"9990D99') AS "USD", (select count(b.denom) where b.denom = '50' ) AS "50", (select count(b.denom) where b.denom = '20') AS "20", (select cou...
How to group multiple subqueries in the same output row
[ "", "sql", "postgresql", "aggregate", "" ]
I am trying to find a more efficient way to write PL/SQL Query to to select insert from a table with 300+ columns, to the back up version of that table (same column names + 2 extra columns). I could simply type out all the column names in the script (example below), but with that many names, it will bother me... :( `...
Specify literals/null for those two extra columns. ``` INSERT INTO TABLE_TEMP SELECT t1.*, null, null FROM TABLE t1 WHERE id = USER_ID ```
You can pretty easily build a column list for any given table: ``` select table_catalog ,table_schema ,table_name ,string_agg(column_name, ', ' order by ordinal_position) from information_schema.columns where table_catalog = 'catalog_name' and table_schema = 'schema_name' and table_name = 'table_na...
A more efficient way to do a select insert that involves over 300 columns?
[ "", "sql", "plsql", "" ]
I have 2 tables: `questions` and `answers`, each question has 4 alternatives and only 1 alternative is correct. Is there any way to force `answers` table to accept only 1 correct alternative for each question, (something like unique index)? `answers` table design sample: ``` id question_id is_correct text 0...
The one way you can do this without a trigger is by storing the information in the `Questions` table rather than the `Answers` table. You can just include a column `CorrectAnswerId` with a foreign key relationship to the `Answers` table.
Since you want to allow only one correct answer you can alter your design to this direction. You can remove the column "is\_correct" from the "answers" table and add a column "correct\_answer\_id" to the "questions" table. So for each question you will have only one correct answer, by definition. This design has the ...
MySQL: store only 1 correct answer (indexing)
[ "", "mysql", "sql", "indexing", "" ]
Hi i'm saving file name as a date and time with file extension like below ``` 43201612150389.docx, 73201611843471.jpg ``` in my sql table, now I want after dot which extension using sql simple query any one have idea.
Use [**`SUBSTRING_INDEX`**](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index): ``` SELECT SUBSTRING_INDEX(mycol, '.', -1) ``` [**Demo here**](http://sqlfiddle.com/#!9/bcda7/1) In SQL Server you can use [**`PARSENAME`**](https://msdn.microsoft.com/en-us/library/ms188006.aspx): ``...
MySql: ``` SELECT SUBSTRING_INDEX(field, '.', -1) ``` SQL: ``` SELECT PARSENAME(field, 1) ```
How to get the value after dot in sql query
[ "", "sql", "split", "sql-server-2012", "" ]
I have a SQL query that goes like this: ``` select v FROM v.rsversion between 'minVer' and 'maxVer'; ``` Where the `version` is expressed as a string of format `x.y.z` This will return fine all existing versions between 0.2.0 and 0.2.9 but will return nothing if the range is 0.2.0 and 0.2.10 Is there a way to make ...
With Postgres you could do this by splitting up the version into three numbers and then compare those numbers. For other DBMS you would need to find a different way of splitting a string like `0.2.1` into three numbers. ``` with rsversion (v) as ( values -- only here for sample data ('0.2.0'), ('0.2.1'), ...
The reason this is not working as designed is because 0.2.0 and 0.2.x are not literal numbers, so if you are trying to do a string comparison it's looking at each incremented character and comparing them. So 0.2.0, 0.2.1, 0.2.10, 0.2.2, 0.2.3, etc is how it's arranging the strings. You may be able to make this work b...
SQL query between strings representing version numbers
[ "", "sql", "" ]
``` SET @s:=''; SELECT @s:= CONCAT('SHOW GRANTS FOR \'',user,'\'@\'',host,'\';') FROM mysql.user where user = 'root'; PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; ``` I dont mind to achieve this using any stored proc. Let say I have 2 users with root **'root'@'%'** and **'root'@'localhost'** What...
With the appropriate privileges, you can do something like: ``` mysql> system rm -f /tmp/get_show_grants.sql; mysql> SELECT CONCAT('system rm -f /tmp/show_grants.sql; SELECT CONCAT(\'SHOW GRANTS FOR \'\'\', `user`, \'\'\'@\'\'\', `host`,\'\'\';\') INTO OUTFILE \'/tmp/show_grants.sql\' FROM `mysql...
This in also not the answer, as the question is more on the execution of multiple prepared statements, Another example can be like in case we need to OPTIMIZE all tables in a database, @wchiquito answer is accepted for that reason Finally Percona already came up with [pt-show-grants](https://www.percona.com/doc/percon...
MySQL User Privileges list in one shot
[ "", "mysql", "sql", "" ]
I have 2 tables, Table 1 StockCard ``` OutletKey ProductKey Date qty 101 ABC 01/01/2014 10 101 ABC 21/02/2014 5 101 ABC 31/03/2014 5 101 ABC 05/06/2014 2 101 ABC 20/10/2014 3 101 ABC 11/11/2014 ...
For most RDBMSs, I would do it like this: ``` SELECT sc.OutletKey ,sc.ProductKey ,sd.LastStockDate AS StockDate ,SUM(sc.qty) AS TotalQty FROM StockCard sc INNER JOIN ( SELECT OutletKey ,MAX(StockDate) AS LastStockDate FROM stock_date GROUP BY OutletKey ) sd ON s...
This should do the trick ``` Select StockCard.OutletKey, StockCard.ProductKey, stock_date.StockDate, sum(StockCard.TotalQty) as TotalQty from StockCard inner join stock_date on StockCard.OutletKey = stock_date.OutletKey group by StockCard.OutletKey, StockCard.ProductKey, stock_date.StockDate ``` What this does... Se...
SQL SERVER How To join 2 tables
[ "", "sql", "join", "" ]
Now I have one table, let's say table PROPERTY, which have 2 columns called A and B, ``` A B PIVOT 1 dog T 2 cat T 1 chien F 1 gou F 2 chat F 2 miao F ``` Now I want to add one column C, whose content is based on A and B, and is indexed by 1. that's to say, ``` A B C 1 dog dog 2 cat...
Why not use **merge**: ``` merge into PROPERTY t using (select min (b) as min_b, a from CFG_DIM_PROPERTY b where b.pivot = 'T' group by a) t1 on (t.a = t1.a) when matched then update set t.c = t1.min_b; ```
Looks like you want output like this? Because your table doesn't have a column `c` yet. And if you want to add it, you can use below logic to get its value. Also note that if for each `A`, if there are more than 1 `PIVOT1` as `T`, then you can get unexpected result. ``` with tbl(A,B,PIVOT1) as( select 1,'do...
Update a column with information from 3 other columns
[ "", "sql", "oracle", "" ]
**Dataset:** *(Just highlighting error condition data, other conditions work fine)* [![enter image description here](https://i.stack.imgur.com/dIFsq.png)](https://i.stack.imgur.com/dIFsq.png) **Query:** ``` SELECT `id`, `uid`, `activity_type`, `source_id`, `parent_id`, `parent_type`, `post_id`, `statu...
SQL uses [three valued logic](https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/). The NULL <> 'ALBUM' and NULL = 'ALBUM' both evaluate to UNKNOWN. You need to use IS NOT NULL or IS NULL to compare with nulls.
The `user_activity.parent_type <> 'ALBUM'` condition also filters every `NULL` value on that column, since `NULL <> 'ALBUM'` isn't `true`, is `undetermined`. So you can use something like this: ``` AND (`user_activity`.`parent_type` <> 'ALBUM' OR `user_activity`.`parent_type` IS NULL) ``` Or: ``` AND COALESCE(`user_...
Logical condition in WHERE - Incorrect results
[ "", "mysql", "sql", "where-clause", "" ]
I'm having problems with date format in an SQL statement ``` CurrentTime = Format(CurrentTime, "dd/mm/yyyy hh:mm") SQL = "SELECT Count([ID]) AS Booked FROM [Appointment Slots] WHERE [Appointment Slots].Time=#" & CurrentTime & "#" ``` The bizarre thing here is that sometimes when I run the code this works. Other times...
> Is there no way to compare a date in Access SQL that is independent of > format? Consider a query with a parameter in its `WHERE` clause, similar to this ... ``` WHERE [Appointment Slots].Time=[Enter Appointment Time] ``` You can also add a `PARAMETERS` clause at the beginning of your SQL statement, but it's not a...
You should make it a habit using the *ISO sequence*, and *nn* for minutes. Also escape the "/" and ":" to have a true slash and colon, otherwise they will be replaced with the localized date and time separators: ``` CurrentTime = Format(CurrentTime, "yyyy\/mm\/dd hh\:nn") ``` This also works for *ADO* and *FindFirst...
Access VBA & SQL date formats
[ "", "sql", "ms-access", "vba", "" ]
I've got this `User` table: ``` +----------+-------+ | Username | Value | +----------+-------+ | User4 | 2 | | User1 | 3 | | User3 | 1 | | User2 | 6 | | User4 | 2 | +----------+-------+ ``` And I do this query to get the top 2's sums: ``` SELECT Username, SUM(Value) AS Sum FROM Use...
You can use [**`WITH ROLLUP`**](http://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html) modifier: ``` SELECT COALESCE(Username, 'All'), SUM(Value) AS Sum FROM User GROUP BY Username WITH ROLLUP ORDER BY Sum DESC ``` or, if you want just top 2 along with the sum of *all*: ``` SELECT Username, s FROM ( S...
Use union ``` SELECT Username, SUM(Value) AS Sum FROM User GROUP BY Username ORDER BY Sum DESC LIMIT 0, 2 union SELECT'ALL', SUM(Value) AS Sum FROM User ```
MySQL one row of sum after limited results
[ "", "mysql", "sql", "mariadb", "mariasql", "" ]
I have a table (trips) that has response data with columns: * TripDate * Job * Address * DispatchDateTime * OnSceneDateTime * Vehicle Often two vehicles will respond to the same address on the same date, and I need to find the one that was there first. I've tried this: ``` SELECT TripDate, Job, Vehicle, Di...
You can just filter the rows down by selecting only the `MIN` OnSceneDateTime like below: ``` SELECT TripDate, Job, Vehicle, DispatchDateTime,OnSceneDateTime FirstOnScene FROM Trips as AllTrips WHERE AllTrips.OnSceneDateTime = (SELECT MIN(OnSceneDateTime) FROM Trips as FirstOnScene WHERE AllTrips.TripDate...
Here is a total shot in the dark based on the sparse information provided. I don't really know what defines a given incident so you can adjust the partition accordingly. ``` with sortedValues as ( select TripDate , Job , Vehicle , OnSceneDateTime , ROW_NUMBER() over(partition by Add...
Compare two rows in SQL Server and return only one row
[ "", "sql", "sql-server", "" ]
I need to join tableA to tableB on employee\_id and the cal\_date from table A need to be between date start and date end from table B. I ran below query and received below error message, Would you please help me to correct and query. Thank you for you help! **Both left and right aliases encountered in JOIN 'date\_sta...
RTFM - quoting [LanguageManual Joins](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Joins) > Hive does not support join conditions that are not equality conditions > as it is very difficult to express such conditions as a map/reduce > job. You may try to move the BETWEEN filter to a WHERE clause, re...
If your situation allows, do it in two queries. First with the full join, which can have the range; Then with an outer join, matching on all the columns, but include a where clause for where one of the fields is null. Ex: ``` create table tableC as select a.*, b.skill_group from tableA a , tableB b ...
Join Tables on Date Range in Hive
[ "", "sql", "hadoop", "hive", "left-join", "" ]
I am trying to create a contact report that shows ALL contact persons AND select those who where present. The presence are stored in a many to many table. Both document id and who was present. The tables are as follow: ``` CREATE TABLE pe (peid int4, peco int4, pename varchar(30)); INSERT INTO pe (peid, peco...
Can you perform like this (if you need simply to check if present) ``` SELECT pename,coname,presdoc = 2 AS present FROM pe LEFT JOIN co ON coid=peco LEFT JOIN pres ON prespe=peid WHERE peco = 1 ``` Or even better ``` SELECT DISTINCT pename,coname,presdoc = 2 AS present FROM pe LEFT JOI...
I think the issue is with the condition `presdoc=2` which forces to return only records which were present. This is what you need. `SQLFiddle Demo` ``` SELECT pename, coname, CASE WHEN presdoc=2 THEN 'Present' ELSE NULL END AS Present FROM pe LEFT JOIN co ON coid=peco LEFT J...
show all records in table 1 using many to many relations - postgresql
[ "", "sql", "postgresql", "postgresql-9.1", "" ]
I need your assistance with the below query as I am not sure how to modify to show me the correct results. Column2 has records that begin with: ``` 005.... 04.... 01.... 05.... XYZ.... 234.... 6789.... V875.... ``` I would like to modify the query to exclude records that begin with a single zero for example 04,01,05 ...
Use a regular expression to exclude records that begin with a single zero: ``` WHERE NOT Regexp_like( column, '^0[^0]' ); ```
You can do this using just `like`: ``` where col not like '0%' or col like '00%' ```
Oracle Not Like
[ "", "sql", "oracle", "" ]
I have a table I wish to select data from by grouping the data by using a certain key. For each group I would also like to count how many rows belonging to the group meets a certain criteria. Even if 0 row from that group meets the criteria, I still want to return this group and have a "Count" field display that 0 rows...
I would suggest using [`CASE WHEN`](http://www.postgresql.org/docs/8.1/static/functions-conditional.html) (standard ISO SQL syntax) like in this example: ``` SELECT a.category, SUM(CASE WHEN a.is_interesting = 1 THEN 1 END) AS conditional_count, COUNT(*) group_count FROM a GROUP BY a.category `...
You have a condition on which you `GROUP BY`. Simply add a column with a conditional expression that can be summed up: ``` ..., SUM( CASE WHEN othercondition THEN 1 ELSE 0 END ) AS MatchingCondition, ... ``` The rows for which the condition is true will yield 1, thereby appearing as a row count in the grou...
How to count how many rows inside a "group by" group meets a certain criteria
[ "", "sql", "postgresql", "count", "group-by", "" ]
I have a query something like: ``` SELECT * FROM qAll WHERE name not in('Alina,Charaidew,Sukapha') ``` which is not working. What will be the best way to do so? As this list a generated dynamically and maybe different every time.
In CF, You should use cfqueryparam to for your query parameteres. To pass a list as parameter, you should add list attribute to the cfqueryparam. Your query should be similar to below: ``` <cfset nameList = "Alina,Charaidew,Sukapha"> <cfquery name="queryName" datasource="#Application.ds#"> SELECT * FROM qAll W...
Sql server treating `'Alina,Charaidew,Sukapha'` as a single Value, that's why are not getting any result. Query should be like.. ``` SELECT * FROM qAll WHERE name not in('Alina','Charaidew','Sukapha') ```
Filtering a list of names from query
[ "", "sql", "coldfusion", "qoq", "" ]
I want to "create or replace" a trigger for a postgres table. However, there is not such sql expression. I see that I can do a "`DROP TRIGGER IF EXISTS`" first (<http://www.postgresql.org/docs/9.5/static/sql-droptrigger.html>). My question are: 1. Is there a recommended/better option than (`DROP` + `CREATE` trigger)...
Postgresql has transaction DDL so `BEGIN > DROP > CREATE > COMMIT` is the equivalent of `CREATE OR REPLACE` [This](https://wiki.postgresql.org/wiki/Transactional_DDL_in_PostgreSQL:_A_Competitive_Analysis) is a nice write-up of how postgre's transactional DDL compares to other systems (such as oracle) Current postgres...
No way to create or replace a trigger but can do this way ``` DROP TRIGGER IF EXISTS yourtrigger_name on "yourschemaname"."yourtablename"; ```
Create or replace trigger postgres
[ "", "sql", "postgresql", "ddl", "database-trigger", "" ]
I am new to SQL and I am kind of lost. I have a table that contains products, various fields like `productname`, `category` etc. I want to have a query where I can say something like: select all products in some category that have a specific word in their productname. The complicating factor is that I only want to ret...
If you just need to to paginate your query and return a specific range of results, you can simply use [OFFSET FETCH Clause](https://technet.microsoft.com/en-us/library/gg699618.aspx). That way there is no need to filter result items by `RowNumber`. I think this solution is easier: ``` SELECT * FROM SHOP.dbo.PRODUCT ...
Building on what `esiprogrammer` showed in his answer on how to return only rows in a certain range using paging. Your second question was: > Ideally I want to be able to not give a category and search word and it will just list all products. You can either have two queries/stored procedures, one for the case where ...
Optional parameters in SQL query
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Existing table t: ``` namz varchar2(255), sumz number, datez date ------------------------------------------- John 100.50 01.01.2016 Ivan 200.45 02.02.2014 ... John 400.32 03.03.2016 ``` Can I get grouped monthly sales for defining period by using simple ...
Using the dataset ``` CREATE TABLE tmp AS (SELECT 'John' name, 100.5 Sumz, '01-Jan-16' datez FROM dual UNION SELECT 'Ivan' name, 200.45 Sumz, '02-Feb-14' datez FROM dual UNION SELECT 'John' name, 400.32 Sumz, '03-Mar-16' datez FROM dual UNION SELECT 'John' name, 200.0 Sumz, '03-Mar-16' datez FROM dual UNION SELECT '...
You can use the function `YEAR`, `MONTH` and `CONCAT` like this : ``` SELECT namz, CONCAT(MONTH(datez),'.',YEAR(datez)) as d, SUM(something) as s FROM t WHERE datez>date1 AND datez<=date2 GROUP BY namz, d ``` The result will be like : ``` namez d s --------------------- Ivan 01.2014 1234.45 John 02.2014 12...
SQL Select with difficult grouping
[ "", "sql", "oracle", "" ]
I explain it with an example. We have 5 events (each with an start- and end-date) which partly overlap: ``` create table event ( id integer primary key, date_from date, date_to date ); -- insert into event (id, date_from, date_to) values (1, to_date('01.01.2016', 'DD.MM.YYYY'), to_date('03.01.2016 23:59:59', 'DD...
This will get all the time ranges and the count of events occurring within those ranges: ``` SELECT * FROM ( SELECT dt AS date_from, LEAD( dt ) OVER ( ORDER BY dt ) AS date_to SUM( startend ) OVER ( ORDER BY dt ) AS num_events FROM ( SELECT date_from AS dt, 1 AS startend FROM event UN...
If you need only to get the number and don't need to operate with more precise time values, it will be just something like this: ``` SELECT MAX(c) max_overlap FROM (SELECT d, COUNT(1) c FROM (SELECT date_from d FROM event UNION ALL SELECT date_to FROM event ) A GROUP BY A.d ) B ``` Otherwise it will need to use recu...
Count max number of overlapping timeranges in a timerange
[ "", "sql", "oracle", "performance", "" ]
I have fallen a problem to set date first into my SQL query. Here is the code below where I have set by using IF, Else IF. But I need one sql statement not IF, Else IF. ``` DECLARE @CurrentDate DATE, @FirstDayOfWeek INT SELECT @CurrentDate = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) SELECT @FirstDayOfWeek = DATEPART(...
The result of `DATEPART(DW, . . .)` depends on the current value of `@@DATEFIRST`, so you need to take that into account when setting the new value of `@@DATEFIRST`. The simplest thing would be to set `@@DATEFIRST` back to 1, get the current day of the week, and then set `@@DATEFIRST` to that. By the way, if you just ...
I know your question mentions `DATEFIRST`, but is there any reason you don't just calculate it based on how many days it has been since the first of the year? ``` SELECT ((DATEPART(DY, GETDATE()) - 1) % 7) + 1 ``` --- *old answer:* Just got to mention that if `DATEFIRST` has been changed from the default of 7, this...
Set datefirst dynamically by the first day of the year
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have this query: ``` SELECT YEAR(`data`) AS ano, SUM(ativo) AS tempo_ativo FROM rh.processamento GROUP BY YEAR(`data`); ``` The result from this query is ``` ano tempo_ativo 2015 108247387 2016 172003845 ``` And this query: ``` SELECT YEAR(`data`) AS ano, SUM(tempo) AS tempo_extra FROM rh.aprovacoes WHERE tipo =...
If the second query *always* returns all records of the first one, then you can try using a `LEFT JOIN`: ``` SELECT t1.ano, tempo_extra, tempo_ativo FROM ( SELECT YEAR(`data`) AS ano, SUM(tempo) AS tempo_extra FROM rh.aprovacoes WHERE tipo = 'BH' OR tipo = 'HE' AND estado=1 GROUP BY YEAR(`data`) ) AS t1 LE...
Try this: ``` SELECT * FROM ( SELECT YEAR(`data`) AS ano, SUM(tempo) AS tempo_extra FROM rh.aprovacoes WHERE tipo = 'BH' OR tipo = 'HE' AND estado=1 GROUP BY YEAR(`data`) ) t1 LEFT JOIN ( SELECT YEAR(`data`) AS ano, SUM(ativo) AS tempo_ativo FROM rh.processamento GROUP BY YEAR(`data`) ) t...
Join 2 queries results
[ "", "mysql", "sql", "" ]
I'm new to SQL so please forgive me if I use incorrect terminology and my question sounds confused. I've been tasked with writing a stored procedure which will be sent 3 variables as strings (varchar I think). I need to take two of the variables and remove text from the end of the variable and only from the end. The ...
Building on the answer given by Tom H, but applying across the entire table: ``` set nocount on; declare @suffixes table(tag nvarchar(20)); insert into @suffixes values('co'); insert into @suffixes values('corp'); insert into @suffixes values('corporation'); insert into @suffixes values('company'); insert into @suffix...
I'd keep all of your suffixes in a table to make this a little easier. You can then perform code like this either within a query or against a variable. ``` DECLARE @company_name VARCHAR(50) = 'Global Widgets Corporation LLC' DECLARE @Suffixes TABLE (suffix VARCHAR(20)) INSERT INTO @Suffixes (suffix) VALUES ('LLC'), (...
SQL Server 2012: Remove text from end of string
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a table with a `VARCHAR2` column which contains values that are a mixture of pure-numbers and alpha-numerics. I have a `CODE` column that contains: ``` 200 215 220 A553 D545 etc. ``` The following query works: ``` select * from TABLE where CLASS = 3 AND (CODE >= 210 and CODE < 220) or CODE = 291) ``` V...
The problem can be in your `WHERE` condition, given that it forces Oracle to cast your code to number; Try keeping the `WHERE` condition in `varchar2` format: ``` with TABLE_(code, class_) as ( select '200',3 from dual union all select '215',3 from dual union all select '220',3 from dual union all select 'A553',3 fro...
The `ORDER BY` has nothing to do with the problem -- at least not directly. SQL in general, and Oracle in particular, make no promises about the order of evaluation of conditions in the `WHERE` clause. Hence, the `WHERE` clause is not (necessarily) evaluated in the order written. The presence of the `ORDER BY` might a...
Oracle ordering of results using a mixed varchar column but numeric where clause
[ "", "sql", "oracle", "sql-order-by", "" ]
I want to get a 14 rows query result even when table has only 6 records available. For example table has only 6 records so I want to make a SELECT and the output throw me the 6 records with 8 blank rows. Like this: ``` |trackings | --------------- |track1 | |track2 | |track3 | |track4 | |t...
You might be better off implementing this in your application layer, however, if you want to do this in SQL, you can use a CTE to implement this. The first CTE creates 14 empty records, in the second CTE these empty records are unioned with the results of your query, and in the final query the top 14 results are select...
I have added otherField1, otherField2 just to do a generic answer This resultset, allways have 14 records, the latests filled with null if there are less that that number in the table ``` select top 14 tracking, otherField1, otherField2 from ( select tracking, otherField1, otherField2, 1 as orderBy from yourTabl...
SQL select returning a defined number of rows
[ "", "sql", "sql-server", "select", "rows", "" ]
What is a proper way to make a query in Tarantool DB with SQL LIKE keyword? For example: ``` SELECT * FROM space where smth LIKE '%some_value%'; ``` Can I search for values using a part of index or I need to write my own LUA script for such functionality?
Yes, you shoud write Lua Script, that'll iterate over space and use lua function `gsub` on `'smth'` field of tuple. There's no way, for now, to search for part of string.
There is nothing wrong with your query if you use tarantool version 2.x. ``` SELECT * FROM "your_space" WHERE "smth" LIKE '%some_value%'; ```
SQL LIKE query in Tarantool
[ "", "sql", "sql-like", "tarantool", "" ]
I have to store in the Boolean field the words " SI or NO " ( affirmation and negation in Spanish). But I can only use these: TRUE: 't' 'true' 'y' 'yes' 'on' '1' FALSE: 'f' 'false' 'n' 'no' 'off' '0' ``` create table sales ( code varchar(3), sold boolean, CONSTRAINT pk_codesale PRIMAR...
you could do this: ``` insert into sales(code, sold) (SELECT '001',CASE WHEN 'FILLHERE' ='SI' THEN 1 ELSE 0 END ); ``` Where in the part of 'FILLHERE' you fill the text where you fill "SI" or "NO" from your application.
I try that code: ``` insert into sales(code, sold) ( SELECT '001',CASE WHEN 'FILLHERE' ='SI' THEN 't' ELSE 'f' END ); ```
Add " SI or NO" in a Boolean field
[ "", "sql", "database", "boolean", "" ]
I'm trying to filter a table to show only the distinct values of a column using only the WHERE clause of an SQL statement. Below is an example table: ``` Person ID | Name | City ---------------------------- 1 person1 city1 2 person2 city1 3 person3 city2 4 per...
This in a `where` clause will have the desired effect. ``` PersonId IN (SELECT MAX(PersonId) FROM table1 GROUP BY city) ```
Something like this should do it: ``` select * from table1 where PersonID IN ( SELECT MIN(PersonID) AS MinID FROM table1 GROUP BY City ) ```
SQL filtering records by unique column using WHERE clause only
[ "", "sql", "sql-server", "" ]
This is my **bill** table: ``` shop_id | billing_date | total ------------------------------ ABC | 2016-03-07 | 100 ABC | 2016-03-14 | 200 DEF | 2016-03-07 | 300 DEF | 2016-03-14 | 100 GHI | 2016-03-07 | 30 ``` I want to get one line per shop, with **average total per week**, the **curre...
Hey you can try this way for current year using `WEEK` and `MONTH` of mysql. as per your data entries in table is week wise: [SQLFIDDLE](http://sqlfiddle.com/#!9/e7cab/6) ``` select shop_id,(sum(total)/(WEEK(MAX(bdate)) - WEEK(MIN(bdate))+1)) as weekly_avg,(sum(total)/(MONTH(MAX(bdate))-MONTH(MIN(bdate))+1)) as mothl...
Is this the sort of thing you are after??: ``` SELECT DISTINCT(bill.shop_id),wk as WeeklyTotal,mt as MonthlyTotal,ma as MonthlyAverage FROM bill JOIN (SELECT AVG(total) wk,shop_id FROM bill WHERE YEAR(billing_date) = 2016 AND MONTH(billing_date) = 1 GROUP BY shop_id) as weekly ON bill.shop_id = weekly.shop...
MySQL : weekly and monthly average
[ "", "mysql", "sql", "database", "" ]
For some work, the requirement is such that we want to retain the table and database structure while truncating all data in the multiple table at one go. Since Truncate Table\_name only truncates one table at time. Is there a way to truncate multiple table? Help would be appreciated.
The easiest way may be the following: If you have foreign key constraint then temporarily set it `OFF`. `SET FOREIGN_KEY_CHECKS=0;` To set it `ON` again: `SET FOREIGN_KEY_CHECKS=1;` --- **To truncate all tables under a particular database** ``` SELECT CONCAT('TRUNCATE TABLE ',TABLE_NAME,';') AS truncateCommand ...
Do you have relationship in your tables ? If so you cannot truncate Tables .. However to remove all data & Reseed Identity use this query ``` EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' --Disable all triggers EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL' --Delete -- Then reseed if Tab...
TRUNCATE data from all tables in a Database
[ "", "mysql", "sql", "database", "truncate", "" ]
I need to check complete DLL. I need a sql query for the same. If I use `DESC` or `DESCRIBE` in Oracle, it shows me all columns and type. But I also need all `Constraints`, `Triggers` acting on it, etc. Just like how Oracle SQL Developer shows the structure if you click on `SQL` tab. What should be my query command?
The table definition with constraints: ``` select DBMS_METADATA.GET_DDL('TABLE', 'MY_TABLE' ) from dual; ``` The triggers on table: ``` select DBMS_METADATA.GET_DDL('TRIGGER',trigger_name) from user_triggers where table_name='MY_TABLE'; ```
For constraints: ``` Select constraint_name from all_constraints where table_name='Table_Name'; ``` For triggers: ``` select trigger_name from all_triggers where table_name='Table_Name'; ```
I need to check Table structure with triggers, constraints
[ "", "sql", "oracle", "dll", "triggers", "" ]
I have a query that scans for people with same name but different ids. Table structure is Staff(name,id) What I want to find is people who share the same name but with different id(they are different people). I do happen to have two people with same name & diff id. ``` +---------+-----+ | NAME | ID | +---------+...
If you want only one result you can do something like this: ``` select a.name, b.name, a.id, b.id from staff a, staff b where a.name = b.name and a.id > b.id ``` This way, only one of the combinations between them will answer the join condition, therefore , only one will be returned BTW - please avoid the use of ...
I don't think you need `JOIN` for this *I want to find is people who share the same name but with different id* Using `Having` clause to filter the `name's` who has more than one `ID` ``` select NAME from yourtable Group by name having count(distinct id)> 1 ```
Selecting records with the same name give duplicate results
[ "", "sql", "oracle", "" ]
I have a table for packages, where each package consists of Number of Days, Days included [any day(s) Sunday, Monday, ... ] ``` Package | Duration | Days Included ------------------------------------------- Package 1 | 10 days | '1,2,3' [Sun, Mon, Tue] Package 2 | 15 days | '4,5,6,7' [Wed, Thu, Fri, Sat] Package 3 ...
You can do it with Numbers table and calendar table,i have created some test data which uses normalized version of your packagedays table. ``` ---package table create table packagetable ( id int, maxduration int ) insert into packagetable select 1,10 ----storing number of days in normalized way create table packag...
``` DECLARE @StartDate DATETIME DECLARE @NoDays INT DECLARE @DaysIncluded VARCHAR(20) DECLARE @EndDate DATETIME, @LOOP INT, @Count int SET @StartDate = getdate() SET @NoDays = 10 SET @DaysIncluded = '1,2' SET @LOOP = @NoDays SET @EndDate = @StartDate WHILE (@LOOP > 0) BEGIN SET @EndDate = DATEADD(DD, 1, @EndDate) ...
Find End Date based on Start date and Duration - T-SQL
[ "", "sql", "sql-server", "t-sql", "date", "" ]
I've a query : ``` select C.ChapterID, C.ChapterName, TA.TestAllotmentID, T.TestName, S.StudentFname, B.BatchName, TA.UpdatedDate from TransTestAllotment TA, MstStudent S, MstBatchDetails B, MstTest T, MstChapter C where TA.StudentID = 47 and TA.BatchID = 10 and T.TestID = TA.TestID ...
You should fix your query to use proper explicit `JOIN` syntax. But the answer to your question is to use window functions: ``` with q as ( <your query here> ) select q.* from (select q.*, row_number() over (partition by chapterid order by updateddate desc) as seqnum from q ) q where...
Thank you Gordon Linoff. My final query is as below. ``` Select Y.* from (select X.*, row_number() over (partition by chapterid order by updateddate desc) as SequencNo from (Select C.ChapterID,C.ChapterName,TA.TestAllotmentID, T.TestName, S.StudentFname,B.BatchName,TA.UpdatedDate from TransTestAllotment T...
Retrive distinct record based on ID order by Date
[ "", "sql", "sql-server", "" ]
I have a SQL Server query which takes data from Oracle 8i server using linked server connection. My question here is completely on Oracle SQL. There is a StyleSizes table. One style can have one or more sizes associated with it. I need to find any one Style\_CD which has more than one Size\_CD. This can be achieved by...
If you want one style that has more than one size, quickly, then you can use `exists`: ``` select m.* from da.stylesize m where exists (select 1 from da.stylesize m2 where m2.style_cd = m.style_cd and m2.size_cd <> m.size_cd) and rownum = 1; ``` Then, you want to be sure you have an index on `da.stylesize(style...
You should use ROWNUM which is similar to MySQL limit and SQL-SERVER top : ``` SELECT STYLE_CD FROM OPENQUERY(LinkedORAServer, 'SELECT STYLE_CD FROM(SELECT STYLE_CD FROM DA.StyleSize M GROUP BY STYLE_CD HAVING COUNT(SIZE_CD) > 1) WHE...
First record which meets GROUP BY and HAVING clauses
[ "", "sql", "oracle", "" ]
i need to create table with a variable name. Heres my code, i dont know why it not work. ``` BEGIN SET @tablename = tablename; SET @sql_text = concat('CREATE TABLE ',@tablename,' (ID INT(11) NOT NULL, team0 DOUBLE NOT NULL, team1 DOUBLE NOT NULL)'); PREPARE stmt FROM @sql_text; EXECUTE stmt; DEALLOCATE PRE...
Wrap `tablename` with `'` to indicate that it is string literal and not identifier. ``` BEGIN SET @tablename = 'tablename'; SET @sql_text = concat('CREATE TABLE ',@tablename,' (ID INT(11) NOT NULL, team0 DOUBLE NOT NULL, team1 DOUBLE NOT NULL)'); PREPARE stmt FROM @sql_text; EXECUTE stmt; DEALLOCATE PREPARE...
``` BEGIN SET @tablename = 'tablename'; SET @sql_text = concat('CREATE TABLE ',@tablename,' (ID INT(11) NOT NULL, team0 DOUBLE NOT NULL, team1 DOUBLE NOT NULL)'); PREPARE stmt FROM @sql_text; EXECUTE stmt; DEALLOCATE PREPARE stmt; END ```
SQL Procedure CREATE Table with variable Tablename
[ "", "mysql", "sql", "procedure", "" ]
I am trying learn how to optimize SQL statements and I was wondering if it's possible to estimate what might be making my queries slow just by seeing the execution plan. ``` *************************** 1. row *************************** id: 1 select_type: PRIMARY table: <derived2> type: A...
No, it's not really possible to diagnose the performance issue from just the EXPLAIN output. But the output does reveal that there's a view query that's returning (an estimated) 384,000 rows. We can't tell if that's a stored view, or an inline view. But we can see that that results from that query are being materializ...
I'd look at the `extra` field in the execution plan, and then examine your query and your database schema to find ways to improve performance. `using temporary` means a temporary table was used, which may slow down the query. Furthermore, temporary tables may end up being written to the disk (and not stored in RAM, wh...
Is it possible to see why my queries are so slow just by seeing the execution plan
[ "", "mysql", "sql", "" ]
I have a sql query ``` Select * from `products` where (`product_company`='mad over donuts' OR `product_company`= 'dunkin donuts') AND (`flavour`='vanilla') AND (355 < `price` < 561 ) ; ``` Which fetches me elements greater than some fixed price and less than some fixed price.It also includes other constraints ...
Change ``` 355 < price < 561) ``` to ``` price between 356 and 560 ``` to correct the problem (between includes equals so need to shrink the range) i.e. ``` Select * from `products` where (`product_company`='mad over donuts' OR `product_company`= 'dunkin donuts') AND (`flavour`='vanilla') A...
in place of this ``` Select * from `products` where (`product_company`='mad over donuts' OR `product_company`= 'dunkin donuts') AND (`flavour`='vanilla') AND (355 < `price` < 561 )"; ``` " is causing problem try this ``` Select * from `products` where (`product_company`='mad over donuts' OR `product_c...
Sql Error 1064,Syntax Error
[ "", "mysql", "sql", "" ]
I have the following problem: I should print the count of sunk ships of all countries. So I write the following: ``` use ships; select CLASSES.CLASS, COUNT(*) from CLASSES left join SHIPS on CLASSES.CLASS = SHIPS.CLASS left join OUTCOMES on NAME = SHIP where RESULT = 'sunk' group by CLASSES.CLASS; ``` but if some co...
The proper way to do this is using `LEFT JOIN`, but with the condition in the `ON` clause: ``` select c.CLASS, COUNT(o.RESULT) from CLASSES c left join SHIPS s on c.CLASS = s.CLASS left join OUTCOMES o on s.NAME = o.SHIP and o.RESULT = 'sunk' group by c.CLASS; ``` Notice that the table ali...
It depends on the SQL dialect you use. If you use Informix as a database, you can use nvl() function: ``` SELECT <whatever>, nvl(ships, 0) AS ship_num FROM SHIPS; ``` Using Sqlite3 you can use coalesce() function: ``` SELECT <whatever>, coalesce(ships, 0) AS ship_num FROM SHIPS; ``` etc. All dialects of SQL will ha...
SQL - show all rows in table using group by and where
[ "", "sql", "" ]
I am trying to concatenate 2 values from the same column but with different conditions. here is my sample table. ``` ---------------------------------- | user_id | key | value | ---------------------------------- 1 firstname maria 1 lastname enuole 2 firstname chris...
Another way using `Conditional Aggregate` but I prefer `Group_concat` approach ``` select user_id, concat(F_name, ' ', L_name) From ( select user_id, max(case when key = 'firstname' then value end) F_name, max(case when key = 'lastname' then value end) as L_name From Yourtable Group by user_id ) A ```
You can do this using `group_concat()` and `order by`. In your case, the solution is pretty simple: ``` select user_id, group_concat(value separator ' ' order by key) as name from t where key in ('firstname', 'lastname') group by user_id; ``` Or, use the `join` approach: ``` select tfirst.user_id, concat_ws('...
Concatenate 2 values from the same column with different conditions
[ "", "mysql", "sql", "join", "" ]
Let's assume I have table1: ``` id Column2 Column3 Column4 1 YES NO NO 2 NO YES YES 3 NO YES NO 4 YES YES NO 5 NO NO NO ``` and I have table2: ``` id Column5 1 NO 2 YES 3 NO 6 YES 7 YES ``` I want to join them to have output like th...
Well, if you are looking for the exact output, then you can use `COALESCE` along with `FULL OUTER JOIN` ``` select COALESCE(A.ID,B.ID) ID,COL1,COL2,COL3,COL4 from Table1 A full outer join Table2 B ON A.id = B.id order by a.id asc ``` [![enter image description here](https://i.stack.imgur.com/VmaMF.png)](https://i.sta...
You will have to do a `full outer join`. Note the `NULL` in line 4/5 for the right table and in 6/7 for the left table. Something like ``` SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.id=table2.id; ```
Join two tables having in final table value (or null) for every id
[ "", "sql", "oracle", "" ]
I'm having difficulty in removing NULLS. The ISNULL statement seems to work for the dynamic result, but not the second one. My final extract query is : ``` select itemid,title,description,cat,fibre,washing,colours,promo, max(case when seqnum = 1 then isnull(chm_sizegrouping,'') end) as sizes_1, max(case when se...
Try this: ``` select itemid,title,description,cat,fibre,washing,colours,promo, isnull(max(case when seqnum = 1 then chm_sizegrouping end),'') as sizes_1, isnull(max(case when seqnum = 2 then chm_sizegrouping end),'') as sizes_2, ........ ```
Unfortunatelly you have to use the `ISNULL` function to each field that could retrieve a `NULL` value.
Removing NULLS from conditional aggregation results
[ "", "sql", "pivot", "isnull", "" ]