Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Hi I have a weather database in SQL Server 2008 that is filled with weather observations that are taken every 20 minutes. I want to get the weather records for each hour not every 20 minutes how can I filter out some the results so only the first observation for each hour is in the results. Example: ``` 7:00:00 7:20:...
To get exactly (less the fact that it's an `INT` instead of a `TIME`; nothing hard to fix) what you listed as your desired result, ``` SELECT DISTINCT DATEPART(HOUR, TimeStamp) FROM Observations ``` You could also add in `CAST(TimeStamp AS DATE)` if you wanted that as well. --- Assuming you want the data as well, h...
You can use a formula like the following one to get the nearest hour of a time point (in this case it's `GETUTCDATE()`). ``` SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, GETUTCDATE()) / 60 * 60, 0) ``` Then you can use this formula in the `WHERE` clause of your SQL query to get the data you want.
SQL Getting data by the hour
[ "", "sql", "sql-server", "" ]
I am new to SQL. I am using SQL Server. I am writing a query to get top scores (sc) of each user (unique). I have written a query which results in a table having non-unique values of pname and pid. I have the following resultant table ``` id pid pname sc ___________________________ 1584 268 user1 99 16...
The typical approach to this problem is not `GROUP BY` but window functions. These are ANSI standard functions that include `ROW_NUMBER()`: ``` SELECT id, pid, pname, sc FROM (SELECT t.id, t.pid, u.pname, t.sc, ROW_NUMBER() OVER (PARTITION BY u.pid ORDER BY t.sc DESC) as seqnum FROM table t JOIN ...
You can try this: ``` select id,pid,pname,sc from ( select t.id,t.pid,u.pname,t.sc, DENSE_RANK() over (partition by pname order by sc desc) as rank from t,u where t.pid=t.pid=u.pid ) x where x.rank=1; ``` as I have just created one table based on your given records after running i am getting fo...
Select records based on one distinct column
[ "", "sql", "sql-server", "" ]
Is it possible to insert multiple values in a table with the same data except from the primary key (`ID`)? For instance: ``` INSERT INTO apples (name, color, quantity) VALUES of(txtName, txtColor, txtQuantity) ``` Is it possible to insert 50 red apples with different IDs? ``` ID(PK) |Name | Color | Quantity 1 ...
You can use INSERT ALL or use the UNION ALL like this. ``` INSERT ALL INTO apples (name, color, quantity) VALUES ('apple', 'red', '1') INTO apples (name, color, quantity) VALUES ('apple', 'red', '1') INTO apples (name, color, quantity) VALUES ('apple', 'red', '1') SELECT 1 FROM DUAL; ``` or ``` insert in...
You can use `SEQUENCE`. ``` `CREATE SEQUENCE seq_name START WITH 1 INCREMENT BY 1` ``` Then in your `INSERT` statement, use this ``` `INSERT INTO apples (id, name, color, quantity) VALUES(seq_name.nextval, 'apple', 'red', 1 );` ```
SQL insert same values with different IDs in 1 query
[ "", "sql", "oracle", "sql-insert", "" ]
I have a simple DB which has two tables, serie and season. Serie has this structure: ``` create table serie( name varchar2(30) not null, num_seasons number(2,0), launch date, constraint pk_serie primary key(name) ); ``` Whereas season has this other structure: ``` create table season( name_serie varchar2(3...
**The others answer are simply wrong** since they are telling you to perform an insert using a select to check how many season exists only once (at insert time). **What it would happens on Update/Delete on season table?** The answer is obvious, you will have all counter not aligned and the data will be unrielable. Fo...
You can get the number of seasons using a sub-select. No need to store it in serie at all. You could make a view for this. If you store the seasons anyway, storing the number of seasons is redundant information. You should avoid storing redundant information unless for specific performance reasons. ``` SELECT s.nam...
How to update a row on parent table after child table has been changed
[ "", "sql", "oracle", "" ]
I have a table where the first column is an integer and second column is string. What i wanted is for the first column to sort by sequence first and then second column should group itself one after another when the value is the same. To simulate my idea please see below. Not sure if this even possible? Sorting 2 colum...
This might be close to what you want: ``` SELECT t1.* FROM PlanActual AS t1 INNER JOIN ( SELECT MIN(Seq) AS minSeq, Phase FROM PlanActual GROUP BY Phase ) AS t2 ON t1.Phase = t2.Phase ORDER BY t2.minSeq ```
Your requirement can be solved by this only ``` SELECT * FROM table ORDER BY column1, column2 ``` What you fail to understand is the fact that if `column1` is sorted first then `column2` will only be sorted in manner that it does not violate `column1` sorting consider this table : ``` ------------------------------...
How to sort two columns (integer and string)?
[ "", "sql", "columnsorting", "" ]
I am using Delphi RAD Studio 9 and Firebird 2.5 I want to use the count of the number of rows that fit a certain condition. When I put ``` Select count(*) from VRDB where Lname - 'SMITH' ``` into the the SQL property , upon opening SQLQuert1, I get the error message > SQLQuery1: Unable to determine field names for ...
Using a Firebird database in Delphi 10 Seattle, the following works fine for me: ``` procedure TForm2.btnCountClick(Sender: TObject); begin SqlQuery3.Sql.Text := 'select count(*) from maimages'; SqlQuery3.Open; Caption := IntToStr(SqlQuery3.Fields[0].AsInteger); end; ``` Btw, which Delphi version do you mean by...
try to use ``` select count(*) CNT from VRDB where Lname = 'SMITH' ```
How do I access the result of a Select count(*) using an SQLQuery component in Delphi
[ "", "sql", "delphi", "firebird", "dbexpress", "" ]
I have a data a set which is already grouped by `Person` and `Class` columns and I use this query for this process: ``` SELECT Person,Class, MAX(TimeSpent) as MaxTimeSpent FROM Persons GROUP BY Person,Class ``` Output: ``` Person Class MaxTimeSpent --------|--------|-------------| MJ | 0 | 0 ...
Try this one ``` SELECT T.* FROM (SELECT Person, Class, MAX(TimeSpent) AS MaxTimeSpent FROM Persons AS P WHERE Person = 'MJ' GROUP BY Person, Class) AS T WHERE T.class = ( SELECT MAX(class) FROM Persons AS P WHERE P.person = T.person) ```
You can use cte for that. ``` declare @Persons table (person nvarchar(10),Class int ,TimeSpent int) insert into @Persons select 'MJ',0,0 union all select 'MJ',1,659 union all select 'MJ',2,515 ;with cte as( SELECT Person,Class,TimeSpent , row_number() over(partition by Person order by Class desc ) as RN FROM @P...
SQL:How do i get the row that has the max value of a column in SQL Server
[ "", "sql", "sql-server", "group-by", "greatest-n-per-group", "" ]
I'm quite new to SQL and coding generally. I have a SQL query that works fine. All I want to do now is return the number of rows from that query result. The current SQL query is: ``` SELECT Progress.UserID, Questions.[Question Location], Questions.[Correct Answer], Questions.[False Answer 1], Questions....
A simple way is to use a subquery: ``` select count(*) from (<your query here>) as q; ``` In your case, you can also change the `select` to be: ``` select count(*) ``` but that would not work for aggregation queries.
To count all of the records, use a simple subquery; subqueries must have aliases (here I've named your subquery 'subquery'). ``` SELECT COUNT(*) FROM ( SELECT Progress.UserID, Questions.[Question Location],Questions.[Correct Answer], Questions.[False Answer 1], Questions.[False Answer 2], Questions.[False Ans...
Using SQL, how do I COUNT the number of results from a query?
[ "", "sql", "vb.net", "ms-access", "oledb", "" ]
I have two tables, a and b table a ``` -------------------- |id | item | -------------------- |1 | apple | -------------------- |2 | orange | -------------------- |3 | mango | -------------------- |4 | grapes | -------------------- |5 | plum | -------------------- |6 |...
Use [**LEFT OUTER JOIN**](http://dev.mysql.com/doc/refman/5.7/en/join.html) instead of **INNER JOIN** Try this: ``` SELECT a.id, a.item, b.price FROM a LEFT OUTER JOIN b ON a.id = b.item_id AND b.user_id = 32; ```
You have to use a OUTER JOIN instead ``` SELECT a.id, a.item, b.price FROM a LEFT OUTER JOIN b ON a.id = b.item_id WHERE b.user_id = 32 ```
MySQL select statement involving join
[ "", "mysql", "sql", "select", "join", "left-join", "" ]
I'm trying to use this SQL query to generate some test data ``` INSERT INTO EVENT (ID, SOURCE, TYPE, EVENT_DATE, DESCRIPTION) VALUES (DBMS_RANDOM.Value(5000, 90000), 101, 'WARNING', (SYSDATE - 1/10 + LOOP_COUNTER/1300), DBMS_RANDOM.STRING('X', 5)) CREATE TABLE EVENT( ID INTEGER NOT NULL, SOURCE VARCHAR2(50 ),...
The Column SOURCE is a type of varchar2 but you are providing an integer
Such error appears when you use unidentified variable in `VALUES` clause. Probably your variable `LOOP_COUNTER` is not declared or is written with a typo.
SQL Error: ORA-00984: column not allowed here
[ "", "sql", "oracle", "oracle11g", "" ]
I have a TEXT column of dates and need to convert them to dates, but the two methods I'm using are not working correctly. See below. ``` SELECT CAST("12/01/2009" as date); 12 ``` This only returns the first digit before stoping at the '/'. ``` SELECT DATE("12/01/2009"); Returns nothing ``` I also tried CONVERT, but...
Try using [`STR_TO_DATE`](http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date) function ``` SELECT STR_TO_DATE('12/01/2009','%m/%d/%Y'); ``` * **[SQL FIDDLE DEMO](http://www.sqlfiddle.com/#!9/9eecb7d/38058)**
SqLite doesn't have date type. You need to do string manipulation do achieve this.
SQL: Casting text to date
[ "", "sql", "sqlite", "" ]
I am trying to accomplish the following, and I am not sure if it is possible. I have a `SELECT` Statement that contains an inner `SELECT` for two of the table columns like so: ``` SELECT col1, col2, (SELECT SUM(col1) FROM table2) AS FirstResultToAdd, (SELECT SUM(col2) FROM table3) AS SecondRes...
I believe you want to perform some logic on the result of `Sub-query` To add the two `sub-query` result ``` SELECT col1, col2, (SELECT col1 FROM table2) AS FirstResultToAdd, (SELECT col2 FROM table3) AS SecondResultToAdd, (SELECT col1 FROM tab...
just nest one more time... ``` select col1, col2, sum( FirstResultToAdd ) from ( SELECT col1, col2, (SELECT col1 FROM table2) AS FirstResultToAdd, (SELECT col2 FROM table3) AS SecondResultToAdd, FROM Table1 ) ```
In SQL can I Perform Logic on Multiple Columns, which are SELECT Statements?
[ "", "sql", "" ]
I want to do something like this: ``` SELECT SUM(COL1) / SUM(COL2) FROM table_name ``` My questions: 1. Error handling. If SUM(COL2) is 0, what will return for most database implementations? How can I return 0 in this case? 2. Performance tuning. Is it **usually** guaranteed that these 2 SUM() will be computed...
SQL: ``` DECLARE @Table TABLE (column1 INT, column2 INT) INSERT INTO @Table VALUES (0, 0) SELECT CASE WHEN SUM(Column2) > 0 THEN SUM(column1) / SUM(column2) ELSE 0 END AS [Sum Division] FROM @Table ``` Will give a 0 value if column2's sum is not greater than 0 (includes nulls). **EDIT** Thi...
Here is a SQL Server solution for Question 1. ``` SELECT COALESCE((SUM(COL1) / NULLIF(SUM(COL2),0)),0) FROM table_name ``` I don't know the answer to question 2, however I can say that I've never seen any other alternative to the way you've written the query being chosen over this way, and I find it safe to assume th...
SQL tuning: division between the sum of two columns
[ "", "mysql", "sql", "sql-server", "database", "" ]
I have an issue with the query below, in the main **SELECT** the value of **ENTITY\_ID** cannot be retrieved, as I'm using LIKE I get more than a single result back. How can I overcome this? If I place an inner SELECT such as: ``` ( SELECT SEC_NN_SERVER_T.SRV_ID FROM ...
By repeating the subquery from your where clause in your select you destroy the coupling between SEC\_USER\_PRIV.ENTITY\_ID and the subquery. Subqueries in the SELECT part should always return only one value, because the select constructs the row to be returned. I expect your problem will be solved by simply including ...
What part of the error message do you not understand? Your subquery is returning more than one row. You can fix the error by using `rownum` or aggregation: ``` (SELECT MAX(SEC_NN_SERVER_T.SRV_ID) FROM SEC_NN_SERVER_T WHERE UPPER(SEC_NN_SERVER_T.SRV_NAME) LIKE UPPER('%gen%') ) as ENTITY_ID ``` or perhaps: ``` (SELE...
PLSQL more than single row returned issue in ID field
[ "", "sql", "oracle", "plsql", "oracle11g", "ora-01427", "" ]
Actually I want to insert multiple rows to a table. The Structure of the table is ``` Create Table tbl_username (id int autoincrement, username varchar(100), Primary key(id)) ``` and I tried to insert multiple rows like ``` Declare @s as varchar(100) set @s='(''name1''),(''name2'')' insert into tbl_username(usernam...
Use dynamic SQL ``` Declare @s as varchar(100) Declare @sql as varchar(max) set @s='(''name1''),(''name2'')' set @sql = 'insert into tbl_username(username) values ' + @s; execute(@sql); ``` However I would avoid dynamic SQL where possible. The standard way to do it if your values are not in a variable is: ``` INSER...
``` insert into tbl_username(username)values ('name1'),('name2'),.....; ``` Here because username is of type varchar so it's considering @s as single value and inserting it in one row.
Inserting multiple rows through a variable
[ "", "sql", "sql-server", "sql-insert", "" ]
My update receives the following error when updating to the database: > ORA-00001: unique constraint (DONALDBURY.BARS\_ID\_PK) violated I am using the following code as my update. I am not wanting to get rid of the constraint but to find out a workaround for it. I want to stop the duplicates values being set. ``` ME...
There is an unique constraint named `BARS_ID_PK` on `image_id` column - this constraint prohibits multiple rows from having the same value in this columns. You are trying to insert a new row with `image_id` that already exists in the table. To avoid this error, simply assing to `:P3_image_id` placeholder in t...
Per the information provided, there is a primary key on the DEST table based on IMAGE\_ID so duplicate IMAGE\_IDs are not allowed. The MERGE statement checks for the existence of record based on filename (DEST\_TABLE.filename). You would need to check on the image\_id instead (or both filename and image\_id). Based on ...
Update violates primary key
[ "", "sql", "oracle", "plsql", "sql-merge", "" ]
I have a request which count the values of a field in differents cases. Here is the request : ``` SELECT SUM(CASE WHEN Reliquat_id = 1 THEN Poids END) AS NbrARRNP, SUM(CASE WHEN Reliquat_id = 2 THEN Poids END) AS NbrSTNP, SUM(CASE WHEN Reliquat_id = 3 THEN Nombre END) AS Nb...
Just add `ELSE 0`: ``` SELECT SUM(CASE WHEN Reliquat_id = 1 THEN Poids ELSE 0 END) AS NbrARRNP, SUM(CASE WHEN Reliquat_id = 2 THEN Poids ELSE 0 END) AS NbrSTNP, SUM(CASE WHEN Reliquat_id = 3 THEN Nombre ELSE 0 END) AS NbrARR, SUM(CASE WHEN Reliquat_id = 4 THEN Nombre ELSE 0 END) AS ST, SUM...
Use `IFNULL()` or `COALESCE()` function [SQL NULL Functions-W3 Schools Ref](http://www.w3schools.com/sql/sql_isnull.asp) `IFNULL(Poids,0)` or `COALESCE(Poids,0)`
How to set the SUM (CASE WHEN) function's return to 0 if there are not values found in MYSQL?
[ "", "mysql", "sql", "" ]
This is my first question here and I hope you guys can help me with this. I'm trying to make a view based on a table that has the following columns: `DAY_0`, `DAY_1`, `DAY_2`, `DAY_3`, `DAY_4`, `DAY_5`, `DAY_6`. The problem is that I only want to compare the column based on the actual day and see if it return the val...
Use the function ``` ELT(weekday(curdate())+1,DAY_0,DAY_1,..) ```
You can't use variable column names like that, but you could do something like this: ``` WHERE CASE WEEKDAY(CURDATE()) WHEN 0 THEN DAY_0 WHEN 1 THEN DAY_1 ... END CASE = 1 ``` You might also want to look into database normalization.
Is there a way to choose a different column on a comparison based on a variable?
[ "", "mysql", "sql", "" ]
If the current date is 3/12/2015, then I need to get the files from dates 2/12/2015, 3/12/2015, 4/12/2015. Can anyone tell me an idea for how to do it? ``` <% try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433/CubeHomeTra...
Use [**DATE\_ADD()**](http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add) And [**DATE\_SUB()**](http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub) functions: Try this: ``` SELECT FILE, DATE FROM ForgeRock WHERE STR_TO_DATE(DATE, '%d/%m/%Y') >= DAT...
Simplest way to get all these **dates** are as below:- **CURRENT DATE** ``` SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) ``` **NEXT DAY DATE** *(Adding 1 to the `dateadd` parameter for one day ahead)* ``` SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), 1) ``` **YESTERDAY DATE** *(Removing 1 from the `dated...
SQL query to find the previous date, current date and next date
[ "", "mysql", "sql", "date", "datetime", "select", "" ]
Is there a SQL format to remove leading zeros from the date? Like if the date is `01/12/2015` to present it as `1/12/2015`, and `01/01/2016` should be shown as `1/1/2016` etc The entire date normally contains `dd/MM/yyyy HH:mm:ss`. I need to remove those redundant leading zeroes without changing the rest of informati...
Not sure why you want to do this. Here is one way. * Use [**`DAY`**](https://msdn.microsoft.com/en-IN/library/ms176052.aspx) and [**`MONTH`**](https://msdn.microsoft.com/en-us/library/ms187813.aspx) inbuilt `date` functions to extract `day` and `month` from `date`. * Both the function's **return type** is `INT` whic...
Try this, format is a much cleaner solution: ``` declare @date datetime = '01/01/2016' SELECT FORMAT(@date,'M/d/yyyy') ``` **result:** 1/1/2016 * [DEMO](http://www.sqlfiddle.com/#!18/9eecb/54433)
How to present Date in SQL without leading zeros
[ "", "sql", "sql-server", "sql-server-2008", "date-format", "date-formatting", "" ]
I have a column with numeric values in which the last 3 digits should actually be behind the decimal point. e.g. * 89302500 * 1260840 * 218580 I need a regular expression that will put the decimal point before the last 3 digits: * 89302.500 * 1260.840 * 218.580 I'm using the `REGEXP_REPLACE` function to change the...
If you want to use regex to achieve this, then you can use a regex like this: ``` (\d*)(\d{3}) ``` **[Working demo](https://regex101.com/r/rV1bR1/1)** According to the [documentation](https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions130.htm), you can do something like this: ``` SELECT REGEXP_REPLAC...
You don't use regular expressions on numbers. If you want a *number* with a precision of 3: ``` select cast(col / 1000 as number(18, 3)) ``` If you want this expressed as a string, then use `to_char()` on `col / 1000`.
Regular expression for turning number into number with decimal precision of 3
[ "", "sql", "regex", "replace", "oracle11g", "toad", "" ]
I am looking to compare the results of 2 cells in the same row. the way the data is structured is essentially this: ``` Col_A: table,row,cell Col_B: row ``` What I want to do is compare when Col\_A 'row' is the same as Col\_B 'row' ``` SELECT COUNT(*) FROM MyTable WHERE Col_A CONTAINS Col_B; ``` sample data: ``...
This does what I was looking for: ``` SELECT COUNT(*) FROM MyTable WHERE Col_A LIKE CONCAT('%',Col_B,'%'); ```
I see You answered Your own question. ``` SELECT COUNT(*) FROM MyTable WHERE Col_A LIKE CONCAT('%',Col_B,'%'); ``` is good from performance perspective. While normalization is **very** good idea, it would not improve speed much in this particular case. We must simply scan all strings from table. Question is, if the q...
How do I search for a string in a cell substring containing a string from another cell in SQL
[ "", "mysql", "sql", "mariadb", "" ]
I am working on SQL Server. I have a table that has an `int` column `HalfTimeAwayGoals` and I am trying to get the `AVG` with this code: ``` select CAST(AVG(HalfTimeAwayGoals) as decimal(4,2)) from testtable where AwayTeam = 'TeamA' ``` I get as a result 0.00. But the correct result should be 0.55. ...
``` select AVG(CAST(HalfTimeAwayGoals as decimal(4,2))) from testtable where AwayTeam = 'TeamA' ```
If the field `HalfTimeAwayGoals` is an integer, then the `avg` function does an integer average. That is, the result is 0 or 1, but cannot be in between. The solution is to convert the value to a number. I often do this just by multiplying by 1.0: ``` select CAST(AVG(HalfTimeAwayGoals * 1.0) as decimal(4, 2)) from t...
AVG function not working
[ "", "sql", "sql-server", "" ]
For what practical purposes would I'd potentially need to add an index to columns in my table? What are they typically needed for?
**Indexing columns speeds up queries on tables with many rows.** Indexes allow your database to search for the desired row using searching algorithms like binary search. *This would only be helpful if you had a large number of rows*, for example 16 or more (this number is taken from the quicksort algorithm, which say...
Indexes are database structures that improve the speed of retrieving data from the columns they are applied on. The [wikipedia article](https://en.wikipedia.org/wiki/Database_index) on the subject gives a pretty good overview without going in to too much implementation-specific details.
What is the use of index in table columns?
[ "", "sql", "database", "indexing", "relational-database", "" ]
I'm working on ASP.NET application whose SQL backend (MySQL 5.6) has 4 tables: The first table is defined in this way: ``` CREATE TABLE `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `descr` varchar(45) NOT NULL, `modus` varchar(8) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ); ``` These ar...
Following query gives you status of each item as following (kind of checklist). I had to change some of the column names which were reserved words in my test environment. ``` select item_id, fp filepath, m_type, item_desc, modee, (select t.type from typess t where t.id = m_type) fr...
Try this: ``` SELECT files.file_path, types.type FROM files LEFT JOIN checklist ON (files.id_type = checklist.id_type ) LEFT JOIN items ON (files.id_item = items.id) AND (items.mode = checklist.mode) LEFT JOIN types ON (checklist.id_type = types .id) WHERE (items.id = 0); ```
SQL RIGHT JOIN misunderstanding
[ "", "mysql", "sql", "join", "" ]
I have problem with SQL query. I have names in column `Name` in `Table_Name`, for example: ``` 'Mila', 'Adrianna' 'Emma', 'Edward', 'Adam', 'Piter' ``` I would like to count how many names contain the letter `'A'` and how many contain the letter `'E'`. The output should be: ``` letter_A ( 5 )| letter_E (3) ``` I ...
You just need to aggregate if you only need the counts. ``` select sum(case when charindex('a',name) <> 0 then 1 else 0 end) as a_count ,sum(case when charindex('e',name) <> 0 then 1 else 0 end) as e_count from table_name ```
You can use conditional aggregation: ``` select sum(case when Nazwisko like '%A%' then 1 else 0 end) as A_cnt, sum(case when Nazwisko like '%E%' then 1 else 0 end) as E_cnt from table_name where Nazwisko like '%A%' or Nazwisko like '%E%'; ```
SQL Server - count how many names have 'A' and how many have 'E'
[ "", "sql", "sql-server", "" ]
I'm thinking about making a project in a database with a large amount of objects / people / animals / buildings, etc. The application would let the user select two candidates and see which came first. The comparison would be made by date, or course. MySQL only allow dates after `01/01/1000`. If one user were to comp...
You could take a signed BIGINT field and use it as a UNIX timestamp. A UNIX timestamp is the number of seconds that passed since January 1, 1970, at 0:00 UTC. Any point in time would simply be a negative timestamp. If my amateurish calculation is correct, a BIGINT would be enough to take you 292471208678 years into ...
Why deal with static age at time of entry and offset? User is going to want to see a date as a date anyway Complex data entry Three fields ``` year smallint (good for up to -32,768 BC) month tinyint day tinyint ``` if ( (y1\*10000 + m1\*100 + d1) > (y2\*10000 + m2\*100 + d2) )
Compare creation dates of things that may have been made before christ
[ "", "mysql", "sql", "date", "" ]
I have a table **books** which looks like this: `___BookTitle______Author 1. Sample Book AuthorA 2. Sample Book AuthorB` *Sample Book* has been written by both *AuthorA* and *AuthorB*. I want to combine them to get the following result `___BookTitle______Author 1. Sample Book AuthorA, AuthorB` I cannot figure out h...
This can be done with the [`group_concat`](http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat) aggregate function: ``` SELECT book_title, GROUP_CONCAT(author SEPARATOR ', ') FROM books GROUP BY book_title ```
I believe this will do the trick, ``` SELECT BookTitle, GROUP_CONCAT(Author) FROM books GROUP BY BookTitle ```
How to combine some attributes in two rows into one in sql?
[ "", "mysql", "sql", "select", "" ]
in mysql i can list all the meta\_values of my meta\_key `_simple_fields_fieldGroupID_6_fieldID_10_numInSet_0` with ``` select * from pm_postmeta where meta_key LIKE '%_simple_fields_fieldGroupID_6_fieldID_10_numInSet_0%' ``` its a list of user heights like 1.67 , 168 etc i want to remove the dots on the numbers......
Actually every depends on the data type you use to store people heights. You say "*they are numbers*" and I assume they're stored in a NUMERIC column (you cannot store 1.78 into an INTEGER data type). So, assuming your original table contains something like: ``` SQL> select * from people ; id| height ------...
``` SELECT p.*,REPLACE(REPLACE(p.`meta_value`, '00', ''),'.', '') AS meta_value FROM `pm_postmeta` p WHERE p.`meta_key`='_simple_fields_fieldGroupID_6_fieldID_10_numInSet_0'; ```
sql remove dots and commas from fields
[ "", "mysql", "sql", "" ]
I want to get declared `Month` and `date` by the below query, but I am getting something as `Jul 21 1905 12:00AM` I want it as `Dec 31 2015` below is my query ``` declare @actualMonth int declare @actualYear int set @actualYear = 2015 set @actualMonth = 12 DECLARE @DATE DATETIME SET @DATE = CAST(@actualYear +...
This will give you as expected output, ``` DECLARE @actualMonth INT DECLARE @actualYear INT SET @actualYear = 2015 SET @actualMonth = 12 DECLARE @DATE DATETIME; SET @DATE = CAST( CAST(@actualYear AS VARCHAR)+'-'+CAST(@actualMonth AS VARCHAR)+'-'+'31' AS DATETIME ); PRINT Convert(varchar(11),@DAT...
Actually you are actualMonth and actualYear and converting as datetime it wil give other result Try like this ``` declare @actualMonth int declare @actualYear int set @actualYear = 2015 set @actualMonth = 12 DECLARE @DATE DATETIME SET @DATE = DATEADD(dd,-1,DATEADD(YY,1,CAST(@actualYear AS varchar(20)) )) select S...
Want to print declared date and Month
[ "", "sql", "sql-server-2005", "" ]
I'm trying to make a blog system of sort and I ran into a slight problem. Simply put, there's 3 columns in my `article` table: ``` id SERIAL, category VARCHAR FK, category_id INT ``` `id` column is obviously the PK and it is used as a global identifier for all articles. `category` column is well .. category. `cate...
## Concept There are at least several ways to approach this. First one that comes to my mind: Assign a value for `category_id` column inside a trigger executed for each row, by overwriting the input value from `INSERT` statement. ## Action Here's the `SQL Fiddle` to see the code in action --- For a simple test, I...
This has been asked many times and the general idea is **bound to fail in a multi-user environment** - and a blog system sounds like exactly such a case. So the best answer is: **Don't.** Consider a different approach. Drop the column `category_id` completely from your table - it does not store any information the ot...
Custom SERIAL / autoincrement per group of values
[ "", "sql", "postgresql", "database-design", "auto-increment", "" ]
I would like to ask if it is possible to do this: For example the search string is '009' -> (consider the digits as string) is it possible to have a query that will return any occurrences of this on the database not considering the order. for this example it will return '009' '090' '900' given these exists on the ...
Use the `Like` operator. **For Example :-** ``` SELECT Marks FROM Report WHERE Marks LIKE '%009%' OR '%090%' OR '%900%' ```
Split the string into individual characters, select all rows containing the first character and put them in a temporary table, then select all rows from the temporary table that contain the second character and put these in a temporary table, then select all rows from *that* temporary table that contain the third chara...
SQL - just view the description for explanation
[ "", "sql", "string", "" ]
My table has the following columns: ``` gamelogs_id (auto_increment primary key) player_id (int) player_name (varchar) game_id (int) season_id (int) points (int) ``` The table has the following indexes ``` +-----------------+------------+--------------------+--------------+--------------------+-----------+----------...
Please consider this query: ``` SELECT t1.season_id, t1.game_id, t1.player_id, t1.player_name, AVG(COALESCE(t2.points, 0)) AS average_player_points FROM player_gamelogs t1 LEFT JOIN player_gamelogs t2 ON t1.game_id > t2.game_id AND t1.player_id = t2.player_id AND t1.se...
Your query is fine as written: ``` SELECT game_id, player_id, player_name, (SELECT avg(t2.points) FROM player_gamelogs t2 WHERE t2.game_id < t1.game_id AND t1.player_id = t2.player_id AND t1.season_id = t2.season_id ) AS avg_points FROM player_gamelogs t1 ORDE...
MySQL very slow query
[ "", "mysql", "sql", "" ]
I have this update that takes data from a view (upd\_g307) that counts members in each family and put it in another table s\_general Here is the update ``` Update s_general Set g307 = (select upd_g307.county from upd_g307 where upd_g307.id_section = s_general.Id_section and upd...
This kind of statement is often faster when re-written as a MERGE statement: ``` merge into s_general using ( select county, id_section, rec_no, f306 from upd_g307 where id_section between 14000 and 15000 ) t on (t.id_section = s_general.Id_section and t.rec_no = s_general.rec_no and t.f306 = s_general.F306)...
You may use [updatable join](http://docs.oracle.com/cd/E11882_01/server.112/e25494/views.htm#ADMIN11782) view in Oracle and I will take a look on the performance of the join anyway, because it is IMO the lower bound of the elapsed time you may expect from the update. The syntax is a follows: ``` UPDATE ( SELECT s_gen...
How to speed up this update sql statment
[ "", "sql", "oracle", "sql-update", "" ]
TL;DR: most of this post consists of example that I've included to make as clear as possible, but the core of the question is contained in the middle section "The Actual question" where examples are reduced to the bone. ## My problem: I have a database which contains data about football matches from which I am trying...
Here is one solution I came up with using dplyr: ``` library(dplyr) df <- df %>% group_by(Team) %>% mutate(cumScored = cumsum(Scored), totalScored = cumScored - ifelse(row_number() >= 7, lag(cumScored, 6), 0), cumConceded = cumsum(Conceded), totalConceded = cumConceded - ifelse(row_number() >= 7, lag(cumConceded, 6), ...
If you're not particular if you are going use `R` or not. This is easily doable in `MS SQL` using `PARTITION`. So, you can do it like this: ``` SELECT MatchID, Team, ISNULL(SUM(Scored) OVER (PARTITION BY Team ORDER BY MatchID ROWS BETWEEN 6 PRECEDING AND 1 PRECEDING),0) as TotalScored, ISNULL(SUM(Conceded) O...
Getting football(soccer) stats with R
[ "", "sql", "r", "limit", "dplyr", "" ]
My Database Table values are inserted like below. ``` Userid AttedanceDate SessionType mazhar 2016-01-02 10:37:22.397 login mazhar 2016-01-03 10:38:24.970 logout mazhar 2016-01-02 11:39:22.397 login mazhar 2016-01-02 11:40:24.970 logout mazhar ...
You can use *conditional aggregation*: ``` SELECT UserId, MAX(CASE WHEN SessionType = 'login' THEN AttedanceDate END) AS AttedanceDatelogin, MAX(CASE WHEN SessionType = 'logout' THEN AttedanceDate END) AS AttedanceDatelogout, DATEDIFF(hour, MAX(CASE WHEN SessionType = 'login' THE...
In *SQL Server* you can achieve It in following: **QUERY** ``` select userid , max(case when SessionType = 'login' then AttedanceDate end) as AttedanceDatelogin , max(case when SessionType = 'logout' then AttedanceDate end) as AttedanceDatelogout , datediff(hh, max(case when Sessi...
How to divide the SQL single column for multiple use
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
The SQL I want is something like this: ``` SELECT week_no, type, SELECT count(distinct user_id) FROM group WHERE pts > 0 FROM base_table GROUP BY week_no, type ``` But I know I can use `COUNT(DISTINCT user_id)` to count the total number of users in each group, but how can I count the number of users who meet the con...
You probably want conditional aggregation: ``` SELECT week_no, type, COUNT(DISTINCT CASE WHEN pts > 0 THEN user_id END) FROM base_table GROUP BY week_no, type; ``` `SqlFiddleDemo`
the condition for group is made with "having" clause SELECT count(user\_id) FROM group group by user\_id having pts > 0
How to select count(distinct) with condition inside groups
[ "", "mysql", "sql", "syntax", "" ]
I have a newbie question about a database I am trying to create. I have a list of publications, with this general order: UID, Author, URL, Title, Publication, start page, end page, volume, year Then I realized that there are multiple Authors and I began trying to normalize the Database for multiple Authors. Then I re...
## Database model You basically need a `many-to-many` relationship between Authors and Publications, since one author can write many publications, and one publication can be written by more than one author. This require you to have 3 tables. * Author - general info about every author (without publications\_id) * Pub...
You have many to many relationship between entity Publication and entity Author. Publication can have many authors, author can have many publications. So, you should create table for this relationship. For example table Authors\_Publications with columns: UID, author\_id, publication\_id, order
SQL Database with variable number of columns
[ "", "mysql", "sql", "sql-server", "" ]
I just wrote the following SQL query: ``` SELECT * from (SELECT voornaam, achternaam, TIMESTAMPDIFF(YEAR, geboortedatum, CURDATE()) AS Leeftijd FROM leiding) AS kolommen HAVING Leeftijd < AVG(Leeftijd) ORDER BY Leeftijd; ``` It doesn't return any results, but when I execute these queries seperately, they do giv...
The combinaion of previous answers should work: ``` SELECT voornaam, achternaam, TIMESTAMPDIFF(YEAR, geboortedatum, CURDATE()) AS Leeftijd from leiding WHERE TIMESTAMPDIFF(YEAR, geboortedatum, CURDATE()) < (select AVG(TIMESTAMPDIFF(YEAR, geboortedatum, CURDATE())) from leiding) ORDER BY ...
use `WHERE` instead `HAVING`. `HAVING` is use with `GROUP BY` keyword not single so write this query ``` SELECT * from (SELECT voornaam, achternaam, TIMESTAMPDIFF(YEAR, geboortedatum, CURDATE()) AS Leeftijd FROM leiding) AS kolommen GROUP BY Leeftijd HAVING Leeftijd < AVG(Leeftijd) ORDER BY Leeftijd; ``` > The ...
No results when comparing values in SQL
[ "", "mysql", "sql", "" ]
I'm creating an application that is essentially an integrity check between two databases - one is MSSQL and one is an old provider Btrieve. As part of the requirements all columns for every table need to be compared to ensure the data matches. Currently we loop through each table, get the basic count of the table in bo...
The most straightforward answer to me would be to convert the date or datetime fields to integers with the same format. YYYYMMDD or YYYYMMDDHHmmss work just fine as long as your formats use leading zeroes. In SQL Server, you can do something like: ``` SELECT SUM(CAST(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(20),DateTim...
Using "Except" in SQL on the lines of Numeric fields you can compare the date counts in both the tables. For the Old source you may generate the select statement using excel or in the native database and bring to the SQL Server. For demonstration purpose I have used two tables and showing Except example below. ``` IF ...
'Summing' a date field in SQL - any ideas?
[ "", "sql", "sql-server", "datetime", "integrity", "" ]
I have below sample data: `03202012` as date but the column datatype is `Varchar`. I want to convert it to `2012-03-20 00:00:00.000` as `Datetime`. I tried using ``` CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME) ``` But I get an error: > The conversion of a varchar data type to a datetime data type resulted in...
I found below script help me solved my concern. ``` SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105) Result: 2016-01-31 00:00:00.000 ``` Thanks all for the effort. :D
Use yyyyMMdd format, that always works: ``` DECLARE @myDateString varchar(10) = '03202012'; SELECT cast( substring(@myDateString, 5, 4)+ substring(@myDateString, 1, 2)+ substring(@myDateString, 3, 2) AS datetime); ```
SQL Server: how to change data entry from VARCHAR to DATETIME?
[ "", "sql", "sql-server", "" ]
I am attempting to update a set of records that are duplicates in three particular columns. The reason for this update is that there is a conflict when trying to insert this data into an updated database schema. The conflict is caused by a new constraint that has been added on `DM_ID`, `DM_CONTENT_TYPE_ID`, and `DMC_TY...
This seems much simpler to write as: ``` WITH toupdate AS ( SELECT DMC.*, ROW_NUMBER() OVER (PARTITION BY DMC.DM_ID, DMC.DM_CONTENT_TYPE_ID, DMC.DMC_TYPE ORDER BY DMC.DMC_PATH) AS ROWNUM FROM DM_CONTENT DMC ) UPDATE toupdate SET DM_CONTENT_TYPE_ID = (CASE...
Try ``` UPDATE CTE3 SET DM_CONTENT_TYPE_ID = DM_CONTENT_TYPE_ID_NEW ``` instead of what you're currently doing. Updating from a CTE works a little different that regular table joins.
SQL Update with CTEs not updating records
[ "", "sql", "sql-server", "t-sql", "" ]
I'm looking at an example in my book, *SQL Antipatterns*. The example table is ``` TreePaths ============================== ancestor | descendant ------------------------------ 1 1 1 2 1 3 1 4 1 5 1 6 1...
In this case, they really just represent the number, these are literals. Since you tagged MySql, you can check it [here](http://dev.mysql.com/doc/refman/5.7/en/literals.html). So the subquery would return ``` t.ancestor | 8 --------------------- 1 8 4 8 5 8 ``` Tak...
`x` and `y` are *expressions* which are evaluated once for each row in the table, and whose values are taken to be the corresponding columns in the current row. `8` is also an expression, *evaluated once for each row,* whose value is taken to be the constant "8". In this case, the query will return ``` t.ancestor |...
What does it mean to SELECT a number?
[ "", "mysql", "sql", "algorithm", "database-design", "tree", "" ]
This is a question from Stanford online database course exercise. Find the movie(s) with the highest average rating. Return these movie title(s) and their average rating. Use **SQLite**. I've seen solutions kindly suggested by others, e.g, 1. [fetch the row with max values](https://stackoverflow.com/questions/121387/...
You seem to use MySQL as a DBMS, which allows non-Standard syntax: When you return `mID` without adding it to `GROUP BY` MySQL returns a single row with the maximum(average) and a random value for mID. This is a generic Standard SQL solution: ``` Select mID, avg(stars) AS avg_stars From Rating Group by mID having av...
Instead of subquery try using order by and limit to first result: ``` SELECT mID, AVG(stars) AS avg_stars FROM Rating GROUP BY mID ORDER BY avg_stars DESC LIMIT 1; ```
Find the movies with the highest average rating using SQL max()
[ "", "sql", "sqlite", "" ]
I have a few million strings that relate to file paths in my database; due to a third party program these paths have become nested like below: ``` C:\files\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\thirdparty\unique_bit_here\ ``` I want update the entries so that `thirdparty\thirdparty\etc` becomes `\thi...
``` WHILE EXISTS (SELECT * FROM table WHERE Field LIKE '%\thirdparty\thirdparty\%') BEGIN UPDATE table SET Field = REPLACE(Field, '\thirdparty\thirdparty\', '\thirdparty\') END ```
So do you want something like this? ``` SELECT SUBSTRING('tables\thirdparty\%thirdparty\%\',0,CHARINDEX('\','tables\thirdparty\%thirdparty\%\',0)) + '\thirdparty\' ``` OR ``` UPDATE table SET Field = REPLACE(Field, Field, (SELECT SUBSTRING(Field,0,CHARINDEX('\',Field,0)) + '\thirdparty\')) ```
How to replace duplicate words in a column with just one word in SQL Server
[ "", "sql", "sql-server", "" ]
I have a table trans\_hist in MS Access program where time is stored in short Date format "HH:MM" ex: [![Image][1]][1] Now I have created a query which tells total time for each user (Just simply summing the time) but if the total time exceeds 24 hours then it resets and starts over again from 00:15(all time are stor...
I hope, this SQL query helps: ``` SELECT T.UID, CSTR(total_hours + INT(total_min / 60)) + ":" + CSTR(total_min Mod 60) as result FROM (SELECT UID, SUM(HOUR(TH.time_elapsed)) AS total_hours, SUM(MINUTE(TH.time_elapsed)) AS total_min ...
Use a function like this: ``` Public Function FormatHourMinute( _ ByVal datTime As Date, _ Optional ByVal strSeparator As String = ":") _ As String ' Returns count of days, hours and minutes of datTime ' converted to hours and minutes as a formatted string ' with an optional choice of time separator. ' ' Exampl...
MS Access: Summing time greater than 24 hours in query restarts from 1 again
[ "", "sql", "vba", "ms-access-2010", "" ]
Laravel Framework version 5.2.5 When I updated a record, update\_at was not changed but created\_at changed to the current timestamp. Is this correct? ``` MariaDB [moon]> show columns from users; +----------------+------------------+------+-----+---------------------+-----------------------------+ | Field |...
Looking at your database structure the problem is `on update CURRENT_TIMESTAMP` for `created_at` column. It shouldn't be obviously like this. Looking at migrations it's unlikely this migration set automatically this, so probably it has been set manually in MySQL, so you should remove `on update CURRENT_TIMESTAMP` for `...
A lot of people have had this issue recently, and you can read the discussion on Github here: <https://github.com/laravel/framework/issues/11518> > MySQL 5.7 no longer allows 0000-00-00 as a valid timestamp with > strict mode turned on (which it is by default). So either use > `->nullableTimestamps()` or `->timestamp(...
Is laravel created_at and updated_at inverse?
[ "", "sql", "laravel", "eloquent", "laravel-5", "" ]
I have two tables: ``` T1 A B C D T2 A B E F G ``` Now I want to have query that will combine those two tables but exclude same records. The output table should be like: ``` T1T2 C D E F G ``` How to do that?
Looks like you need `FULL OUTER JOIN` and exclude common part. You can simulate it with: ``` SELECT T1.col_name FROM T1 LEFT JOIN T2 ON T1.col_name = T2.col_name WHERE T2.col_name IS NULL UNION SELECT T2.col_name FROM T2 LEFT JOIN T1 ON T1.col_name = T2.col_name WHERE T1.col_name IS NULL; ``` `SqlFiddleDemo` `...
I see two possible solutions. Using `UNION ALL` together with an outer select with `GROUP BY x HAVING COUNT(x) = 1`: ``` SELECT * FROM (SELECT a FROM t1 UNION ALL SELECT a FROM t2) as t12 GROUP BY a HAVING COUNT(a) = 1 ``` Using `UNION` to combine two `SELECT`s filtered by subqueries: ``` (SELECT a FROM t1 WHERE a ...
Combine two tables, exclude same records
[ "", "mysql", "sql", "" ]
Usually I only run this loop with less than 50 and it runs fine. Now I am trying to scale up and with 5k+ it takes serveral minuts. ``` Public Shared Sub Add(type As BufferType, objIDs As List(Of Integer), userToken As String) Dim timeInUTCSeconds As Integer = Misc.UTCDateToSeconds(Date.Now) For Each objID As ...
You should always use [**SQLBULKCOPY**](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx) for inserting a large amount of data. You can have a look at [here](https://stackoverflow.com/questions/287708/best-practices-for-uploading-files-to-database#287749) which has been always *...
Best option is to move whole work to SQL side. Pass your *objIDs* list as table parameter to stored procedure and utilize MERGE..UPDATE..INSERT statement. If you require VB side code, there is number of optimization you can do. * SQL Parameters. Must do. * Check DAL.SQL class if it handles connection properly. * Cons...
5k+ SQL inserts takes a long time - how can I improve it?
[ "", "sql", "vb.net", "sql-server-2012", "bulkinsert", "sqlperformance", "" ]
How to fetch data from 3 tables with max date ``` select c.model_key, v.id, v.category_Id, v.Text1, v.Numeric1, c.Name, fx.Currency_code, fx.Rate, fx.effective_dt from aps.v_m_fxrates fx join aps.t_m_value v on fx.Currency_code = v.Text1 join aps.t_m_category c on v.Category_Id = c.Id where...
Use the ***row\_number()*** function in a subquery like this: ``` select c.model_key, v.id, v.category_Id, v.Text1, v.Numeric1, c.Name, fx.Currency_code, fx.Rate, fx.effective_dt from ( select Currency_code,Rate,effective_dt ,SeqNo = row_number() over (partition by Currency_code order ...
Try use operator **TOP 1** and corresponding **ORDER BY** For example: ``` SELECT TOP 1 C.model_key, V.id, ... FROM ... ORDER BY FX.effective_dt DESC ``` Another option that you have is using aggregate function and correlation in where clause. ``` select C.model_key, V.id, V....
How to filter data based using date column?
[ "", "sql", "sql-server-2008", "join", "" ]
I have some question in Sqlserver2012. I have a table that contains a filed that save who System Used from this information and separated by **','**, I want to set into parameter the name of Systems and query the related rows: ``` declare @System nvarchar(50) set @System ='BPM,SEM' SELECT * FROM dbo.tblMe...
Forgetting for a second that storing delimited lists in a relational database is abhorrent, you can do it using a combination of [`INTERSECT`](https://msdn.microsoft.com/en-us/library/ms188055.aspx) and [`EXISTS`](https://msdn.microsoft.com/en-GB/library/ms188336.aspx), for example: ``` DECLARE @System NVARCHAR(50) = ...
You have a problem with your data structure because you are storing lists of things in a comma-delimited list. SQL has a great data structure for storing lists. It goes by the name "table". You should have a junction table with one row per "measure catalog" and "system". Sometimes, you are stuck with other people's re...
compare some lists in where condition sql
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have legacy sql query that selects bit masks (among other data), something like: ``` 1 2 1 ``` How do I group this output like: ``` 1 or 2 or 1 ``` That should be `3`
In order to do bit-wise logic you have to do a "bit" of math. (Bad puns are free around here :-). Oracle defines the BITAND function. To get a bitwise 'or' you can define your own function as: ``` FUNCTION BITOR(n1 IN NUMBER, n2 IN NUMBER) RETURN NUMBER IS BEGIN RETURN n1 - BITAND(n1, n2) + n2; END BITOR; ``` A...
If I understand you correctly, you want an aggregate bit-or function. Oracle doesn't provide one, to my knowledge, so you have to roll your own using their ODCI (Oracle Data Cartridge Interface). Here's a working example: ``` CREATE OR REPLACE TYPE matt_bitor_aggregate_impl AS OBJECT ( result NUMBER, CONSTRUCTOR F...
How do I group "or" in pl/sql
[ "", "sql", "oracle", "plsql", "" ]
I have a database contains information for a telecommunication company with the following table: * `SUBSCRIBERS (SUB_ID , F_NAME , L_NANE , DATE_OF_BIRTH , COUNTRY)` * `LINES (LINE_ID , LINE_NUMBER)` * `SUBSCRIBERS_LINES (SUB_LINE_ID , SUB_ID "foreign key", LINE_ID "foreign key", ACTIVATION_DATE)` * `CALLS (CALL_ID , ...
The subquery must GROUP BY on SUB\_ID (not on LINE\_FROM). This will provide the total calls of a subscriber and not the top line calls. In other words move the join in the subquery and group and order by SUB\_ID. DISTINCT in the main query is too late, you will get no duplicates but less results.
Could you try adding the DISTINCT keyword to the SELECT query at the bottom? Something like this: ``` with TEMPRESULT AS ( select * from ( select CALLS.LINE_FROM , count(*) totalcount from CALLS where (((END_DATE_CALL-START_DATE_DATE)*24*60*60)<=60 and to_char(S_DATE,'YYYY-MM-DD')='2015-12-12') group by CA...
prevent query from return duplicate results
[ "", "sql", "oracle", "" ]
I have this piece in my SELECT portion of my TSQL query: ``` CAST(DATEPART(HOUR,s.Arr) AS VARCHAR) + CAST(DATEPART(MINUTE,s.Arr) AS VARCHAR), ``` The original `s.Arr` field looks like: ``` 2016-01-04 04:43:00.000 ``` The goal is to make it look like: ``` 0443 ``` But right now my SQL makes it look like: ``` 443 ...
With `SQL Server 2012+` you can use `FORMAT`: ``` DECLARE @d DATETIME = '2016-01-04 04:43:00.000'; SELECT FORMAT(@d, 'HHmm'); -- 0443 ``` `LiveDemo` --- `SQL Server 2008` Without padding with `0`: ``` DECLARE @d DATETIME = '2016-01-04 04:43:00.000'; SELECT REPLACE(LEFT(CONVERT(VARCHAR(100), @d, 14),5), ':', ''); ...
Padding with 00 and take right two ``` RIGHT('00' + CAST(DATEPART(HOUR,s.Arr) AS VARCHAR),2) + RIGHT('00' + CAST(DATEPART(MINUTE,s.Arr) AS VARCHAR),2) ```
How to get leading zeroes with DatePart?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I want to get all the detail about my purchase from the following tables, ``` 1) tbl_track 2) tbl_album 3) tbl_purchase ``` tbl \_purchase table :- ``` item_id type price ``` tbl\_track table :- ``` id title description ``` tbl\_album table :- ``` id title description ``` Now based on type of tbl\_purchase I wa...
With `UNION`: ``` SELECT p.type, t.id, t.title, t.description FROM tbl_purchase p JOIN tbl_track t ON t.id = p.item_id AND p.type = 0 UNION SELECT p.type, a.id, a.title, a.description FROM tbl_purchase p JOIN tbl_album a ON a.id = p.item_id AND p.type = 1 ```
I think you need left join both tables in any case. So you can use next query for example ``` SELECT P.*, T.id AS track_id, A.id AS album_id FROM tbl_purchase AS P LEFT JOIN tbl_track AS T ON P.item_id = T.id AND P.type = 0 LEFT JOIN tbl_album AS A ON P.item_id...
Left Join based on field value
[ "", "mysql", "sql", "select", "join", "left-join", "" ]
I have something like this: `UPDATE users SET credits=credits-1000 WHERE id=1` How do I make this fail if credits goes negative? I want to avoid having to query the database twice just to check for that. I need it to FAIL/return false if it goes negative, not set the credits to zero.
What about adding the condition ? ``` UPDATE users SET credits=credits-1000 WHERE id=1 AND credits > 1000 ```
I think you have to use stored procedure for this purpose. For example ``` CREATE procedure UpdateUserCredit @user_id INT, @credits INT, @op_status BIT OUTPUT AS BEGIN SET @op_status = 0 UPDATE Users SET credits = credits - @credits WHERE id = @user_id AND credits - @cred...
How can I make SQL not execute the query if the field goes negative?
[ "", "mysql", "sql", "" ]
I am trying to find the very first row where a certain field is null but the caveat is there cannot be a non-null coming after. If there isn't a null value or a non-null comes after the null then I do not want to return that one at all. I am using Teradata SQL and the following mock dataset should illustrate what I am ...
Does this give you what you want? ``` SELECT T1.ID, MIN(T1.some_date) AS some_date FROM My_Table T1 WHERE T1.some_column IS NULL AND NOT EXISTS (SELECT * FROM My_Table T2 WHERE T2.ID = T1.ID AND T2.some_date > T1.some_date AND T2.some_column IS NOT NULL) GROUP BY T1.ID ``` Alternatively: ``` ...
You can do this with a difference of row number or using subqueries. The latter method results in a query like this: ``` select id, min(date) from t where t.field_of_interest is null and not exists (select 1 from t where t2.id = t.id and t2.date > t.date and ...
Find the first instance of a null value in a group as long as no non null comes after - Teradata SQL
[ "", "sql", "teradata", "" ]
I know about Dateadd and datediff, but I cannot find any information how to use these functions on an actual date column rather than something like today's date with SQL Server. Say I have the following Column ``` Dated 06/30/2015 07/31/2015 ``` Now I want to add the following derived column that subtracts one month...
The short answer: I suspect this is what you want: ``` dateadd(day, -datepart(day, Dated), Dated) ``` However, if you want "regular" subtract one month behavior in tandem with sticking to the end of month, having June 30 fall back to May 31 is slightly trickier. There's a discrepancy between the title or your questio...
Why don't you just get the last day of the previous month? If this solve your problem, here's the sql server syntax, just replace the variable @yourDate with your column name. ``` DECLARE @yourDate DATE = '20160229' select DATEADD(MONTH, DATEDIFF(MONTH, -1, @yourDate)-1, -1) ```
How to subtract one month from a Date Column
[ "", "sql", "sql-server", "dateadd", "" ]
I have a table named jos\_user\_usergroup\_map that has 2 columns: user\_id and group\_id A user can be a member of several groups and thus has several rows in this table, each with the group ID, e.g. ``` user_id|group_id 62 | 1 62 | 4 62 | 12 108 | 1 ``` I want to find all the user\_id's where that i...
Try this: ``` SELECT DISTINCT A.user_id FROM jos_user_usergroup_map A LEFT OUTER JOIN jos_user_usergroup_map B ON A.user_id = B.user_id AND B.group_id = 12 WHERE B.user_id IS NULL; ```
Use post aggregation filtering ``` SELECT user_id FROM jos_user_usergroup_map GROUP BY user_id HAVING SUM(group_id=12)=0 ```
SQL Query to find users not having specific group id in join table
[ "", "mysql", "sql", "select", "join", "" ]
I have a query : ``` select channel, status, sum(quantity::integer) from sale group by channel,status; ``` this is giving the following output: ``` channel status quantity Arham Return 1801 Arham DISPATCHED 49934 Arham CANCELLED 1791 Arham DELIVERED 22 ``` But I want this output li...
Exploit Boolean to integer conversion giving either 0 or 1, then multiply by that: ``` select channel , sum((status = 'Return') :: int * quantity :: int) as return , sum((status = 'DISPATCHED') :: int * quantity :: int) as DISPATCHED , sum((status = 'CANCELLED') :: int * quantity :: int) as CANCELLED ...
If you don't want to use the `crosstab` function you can do this using filtered aggregates: ``` select channel, sum(quantity) filter (where status = 'Return') as return_amount, sum(quantity) filter (where status = 'DISPATCHED') as dispatched, sum(quantity) filter (where status = 'CANCELLED') as ca...
Arrange select query in postgresql?
[ "", "sql", "postgresql", "pivot", "crosstab", "" ]
I am trying to implement a query like below ``` SELECT * FROM emp WHERE LOWER (ename) IN LOWER ('A', 'b', 'C', 'd','eF','GG','Hh'); ``` but getting error ``` ORA-00909: invalid number of arguments. ``` Is there any specific function by which I can compare multiple arguments in the 'IN' c...
@Muhammad Muazzam has it right, but if for some reason you really need to user LOWER on the right hand side with a list of values then you could do this: ``` select ename from emp where lower(ename) in (select lower(column_value) from table(SYS.KU$_VCNT('A','B','C','D')) ); ``` `SYS.KU$_VCNT` is a table of VARCH...
Change query to: ``` SELECT * FROM emp WHERE LOWER (ename) IN ('a', 'b', 'c', 'd'); ```
comparing using multiple arguments in the Lower/Upper function
[ "", "sql", "oracle", "" ]
I'm currently working on a Postgres SQL query that will check for rows that match a space separated string (3 words) in any random order. For example I want to look for a row that matches "lorem ipsum dolor" it should return row id 0. ``` +----+-------------------+ | id | sentence | | 0 | lorem dolor ipsum ...
The method, which Clodoaldo Neto described, is good for sorting the words. If performance is crucial for you, you can even create an index for that to improve lookup speed. Create a custom function `sortwords` first: ``` CREATE OR REPLACE FUNCTION sortwords (words text) RETURNS text AS $$ SELECT string_agg(lower(s...
``` with t(s) as (values ('lorem dolor ipsum'), ('lorem ipsum'), ('ipsum dolor'), ('ipsum dolor') ) select * from t where ( select string_agg(lower(s), ' ' order by s) from regexp_split_to_table(s, '\s+') s(s) ) = ( select string_agg(lower(s), ' ' order by s) ...
Find rows in Postgres where string is in any random order
[ "", "sql", "postgresql", "" ]
**MY TABLES:** ``` USERS_1: USERS_2: +------------+---------+ +------------+---------+ | id |username | | username |claimedBy| +------------+---------+ +------------+---------+ | 4 | pitiqu | | myUsername | NULL |<- thi...
You could use a update query like this: ``` update USERS_2 set claimedBy = (SELECT username FROM USERS_1 WHERE id=4) where username="myUsername" ``` if you want a join, the correct syntax is like this however on this particular context it doesn't make much sense and I would suggest you to use the first query: ...
That's a wrong syntax. You should use a update join like ``` UPDATE UL u JOIN USERS_2 US ON US.id = 4 SET u.claimedBy = US.username where u.username='myUsername'; ```
SQL Syntax error on JOIN
[ "", "mysql", "sql", "" ]
I am new in sql i am facing one problem I need to create stored procedure which return start and end date of any quarter by passing Quarters as string string and year ex : when i pass `exec spname '2014-15','jul-sep'`, it should start date of july and end date of September
It is unclear why you do not provide only year and quarter as input parameters. The following procedure should return the quarter beginning and end: ``` alter procedure spQuarter ( @yearStr VARCHAR(7), @QuarterStr VARCHAR(20) ) AS BEGIN DECLARE @year INT = CAST(SUBSTRING(@yearStr, 1, 4) AS INT) DECLAR...
You need to just pas year parameter like this '2014-2015' instead of 2014-15 and below sp will work ``` create proc spQuarter ( @YEAR VARCHAR(10), @Quarter VARCHAR(10), ) AS BEGIN DECLARE @QuarterId INT = (CASE WHEN @Quarter = 'jan-mar' THEN 1 WHEN @Quarter = 'apr-jun' THEN 2 WHEN @Quarter = ...
Finding sql date with account year and Quarter
[ "", "sql", "sql-server", "t-sql", "sql-date-functions", "sqldatetime", "" ]
I would like to know that how to select when using stored procedure with filter as combobox in website have more than 3 value Exp: I would like to select match listing. and filter is "IsFinish" with value (All, Yes, No) ``` DECLARE @IsFinish INT -- 1: All 2: Yes 3: No SELECT * FROM MATCH WHERE [Status] = ? ``` Sta...
Prepare Data ``` CREATE TABLE [Match] ([Status] CHAR(1) PRIMARY KEY, [Wording] VARCHAR(50)); INSERT INTO [Match] ([Status], [Wording]) VALUES ('F', 'Finished'), ('C', 'Canceled'), ('L', 'Live'), ('N', 'Non-Live'), ('P', 'Pause'), ('X', '(Close) Waiting Confirm'); ``` Prepare Procedure ``` CR...
In *SQL-Server* you can achieve It in following: ``` where [status] LIKE (case @IsFinish when 1 then '%' end) or [status] = (case @IsFinish when 2 then 'F' end) or [status] = (case @IsFinish when 2 then 'X' end) or [status] = (case @IsFinish when 3 then 'N' end) or [status] = (case @IsFinis...
How to select on stored procedure with filter have more than 3 value
[ "", "sql", "select", "stored-procedures", "" ]
Using "SELECT [Users],[Stars] FROM [Table]", here is an example result set returned: ``` <table border="1"> <th>Users</th> <th>Stars</th> <tr> <td>Admin</td><td>3</td> </tr> <tr> <td>Worker</td><td>4</td> </tr> <tr> <td>Student</td><td>2</td> </tr> </table> ``` How would I show the Admi...
This should cover it just using a Where clause ``` SELECT [Users], [Stars] FROM [Table] WHERE [Users] != 'Admin' OR [Stars] > 3 ```
This will exclude any user Admin with stars less than 3: ``` SELECT [Users],[Stars] FROM [Table] WHERE NOT ([Users] = 'Admin' AND [Stars] <= 3) ```
Filtering a result set to show or hide specific result in SQL Server
[ "", "sql", "sql-server", "" ]
Is there any way to write below SQL query in Single Select query, ``` SET @T1 = COUNT(1) FROM @TableVar SET @T2 = COUNT(1) FROM @TableVar WHERE bit1 = 1 AND bit2 = 0 SET @T3 = COUNT(1) FROM @TableVar WHERE bit1 = 0 AND bit2 = 1 SELECT @T1 AS Col1, @T2 AS Col2, @T3 AS Col3 ```
``` SELECT T1 = COUNT(1), T2 = COUNT(CASE WHEN bit1 = 1 AND bit2 = 0 THEN 1 END), T3 = COUNT(CASE WHEN bit1 = 0 AND bit2 = 1 THEN 1 END) FROM @TableVar ```
Try: [SQL Fiddle](http://sqlfiddle.com/#!3/9eecb7/6723) **MS SQL Server 2008 Schema Setup**: **Query 1**: ``` DECLARE @TableVar TABLE (bit1 bit, bit2 bit) INSERT INTO @TableVar Values(0,0) INSERT INTO @TableVar Values(1,1) INSERT INTO @TableVar Values(1,0) INSERT INTO @TableVar Values(1,0) INSERT INTO @TableVar V...
Single Select query to Select 3 different variable based on 3 different condition
[ "", "sql", "sql-server", "" ]
I have a table, which has a column(orderid), which its IDENTITY is set to true. Now I would like to set it off. How can I do that with ALTER COLUMN?some thing like this? ``` ALTER TABLE MyTable ALTER Column MyColumn SET IDENTITY OFF ```
Once the identity column is set you **cannot remove** it or you cannot set it to OFF. You probably have to drop the column by first copying the data into some other column(*which does not have the identity*). So it would be like add a new column to your table and copy the values of your existing identity column to it....
You have to use SET IDENTITY\_INSERT TO ON. If you set it as ON then you should explicitly pass values to the ID Column. Why should you switch off the Identity? May be you are trying to pass some explicit values. Please refer the sample demo here. ``` -- Create tool table. CREATE TABLE dbo.Tool ( ID INT IDE...
Alter table to set the IDENTITY to off
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I need to measure the execution time of query on Apache spark (Bluemix). What I tried: ``` import time startTimeQuery = time.clock() df = sqlContext.sql(query) df.show() endTimeQuery = time.clock() runTimeQuery = endTimeQuery - startTimeQuery ``` Is it a good way? The time that I get looks too small relative to when...
**Update:** No, using `time` package is not the best way to measure execution time of Spark jobs. The most convenient and exact way I know of is to use the Spark History Server. On Bluemix, in your notebooks go to the "Paelette" on the right side. Choose the "Evironment" Panel and you will see a link to the Spark Hist...
To do it in a spark-shell (Scala), you can use `spark.time()`. See another response by me: <https://stackoverflow.com/a/50289329/3397114> ``` df = sqlContext.sql(query) spark.time(df.show()) ``` The output would be: ``` +----+----+ |col1|col2| +----+----+ |val1|val2| +----+----+ Time taken: xxx ms ``` Related: [On...
How to measure the execution time of a query on Spark
[ "", "sql", "time", "apache-spark", "ibm-cloud", "" ]
I need stats on orders, week by week, so I have done this: ``` SELECT YEAR(orders.date), WEEKOFYEAR(orders.date), COUNT(*) FROM orders GROUP BY YEAR(orders.date), WEEKOFYEAR(orders.date) ``` It worked for one year, but just now (new year) it does not count the last days of 53rd week (jan 1st, 2nd, 3rd). How can I up...
You need to switch to [`YEARWEEK(orders.date,3)`](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_yearweek) to get the ISO weeks as a single column. Using `WEEK(orders.date,3)` (which is exactly the same as `WEEKOFYEAR`) will return the correct week number, but `YEAR(orders.date)` will ret...
As Strawberry mentioned in the comments you're looking for the `WEEK` function. I just checked the documentation at the MySQL website. **Week(date [,mode])** > This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether...
Group by weekofyear MySQL for the end of the year
[ "", "mysql", "sql", "" ]
I have this table in my postgresql database: ``` purchase userid | date | price --------------------------- 1 | 2016-01-06 | 10 1 | 2016-01-05 | 5 2 | 2016-01-06 | 12 2 | 2016-01-05 | 15 ``` I want the sum of the last purchase price of all users. For user 1 the last purchase is...
All proposed solutions are good and work but as my table contains millions of records I had to find the more efficient way to do what I want. And it seems that the better way is to use the foreign key between the tables `purchase` and `user` (which I didn't mention in my question, my apologies) which is `purchase.user ...
You can use windowed functions to get rank number and then use normal aggregation with `SUM`: ``` WITH cte AS ( SELECT *, RANK() OVER(PARTITION BY userid ORDER BY "date" DESC) AS r FROM purchase ) SELECT SUM(price) AS total FROM cte WHERE r = 1; ``` `SqlFiddleDemo` Keep in mind that this solution calculates ti...
Sum of last value from users
[ "", "sql", "postgresql", "sum", "greatest-n-per-group", "" ]
I have a situation where I need to work with EAV data in an existing application where refactoring is not an option, so I can't change the structure of the data. That said, I have a query that returns data like so ``` | account | field | value | group | |---------|-------|-------|-------| | 1 | A | 1 | 1...
I have solved the problem using part of the suggestion by @Hogan ``` WITH hashes AS (SELECT group, SUM(Ora_hash(Concat(Concat(account,field), value))) AS hash FROM table GROUP BY group) SELECT account, field, value, group FROM table WHERE group IN (SELECT group FROM (SELE...
New answer based on comments: ``` WITH Prior AS ( -- First find matches to Prior groups SELECT A.account, A.field, A.value, A.group, MIN(B.group) as Prior_Group FROM TABLE A LEFT JOIN TABLE B ON A.account=B.account AND A.Field = B.field AND A.value = B.value ...
How to get distinct sets of rows using SQL (Oracle)?
[ "", "sql", "oracle", "" ]
There are some columns that i want to fecth under the conditions. **Columns are :** point\_id, weight(row currentness index 0 to 7, 0 is the most current row), localdate (YYYYmmdd), tmin(minimum temperature), tmax (maximum temperature) and precip\_amount (precipitation amount mm). **The conditions are :** (localdat...
Try this query. I have moved calculation on minimum weight to subquery. ``` SELECT a.point_id as point_id, (SELECT MIN(A2.weight) FROM Table A2 WHERE A2.point_id = A.point_id AND A2.localdate >= 20151201 AND A2.localdate <= 20160104 AND (A2.tmin < 0 or ...
``` select * from ( select a.point_id as point_id , a.weight as min_weight,a.localdate as local_date, a.tmin as temp_min, a.tmax as temp_max, a.precip_amount as precipitation , row_number() over (partition by point_id order by weight asc) as rn from table1 a where (a.localdate >= 20151201 and a.locald...
Is there a way to optimize my bigquery sql in order to run faster?
[ "", "sql", "optimization", "google-bigquery", "" ]
On applying abs on divisible data, whole number quotient is converted to decimal. ``` create table #data ( ConditionValue money, ConditionRateNbr real) insert into #data values(9665.77,37.61) select abs(conditionvalue/conditionrateNbr) Using_Abs ,* from #data --Using_Abs ...
What I have seen using money is more reliable than decimal. Here is another example. Why on earth decimal considers 3/1.5 as 1.5, I do not know !!! ``` declare @real real = 1.5, @realup money=3 select @realUp numerator, @real denominator, @realup /cast (@real as money) money, @realup /cast(@real as decimal) decimal ...
It has to do with the "real" data type being an "approximate-number", see <https://msdn.microsoft.com/en-us/library/ms173773.aspx>. My knowledge of SQL is not deep enough to give a detailed explanation but I do have a solution, use the decimal data type i/o real: ``` create table #data ( ConditionValue money, Conditio...
SQL ABS() is returning unexpected decimal when applied on divisible data
[ "", "sql", "" ]
In Oracle, I have column named Create\_date with data returning as 1400003659, 1400072380, and 1403796514 as examples. The column type is NOT NULL NUMBER(15). I'm trying to edit my SELECT statement to return these values as dates (or are these dates and times?). **I've tried the below, but all are returning errors**: ...
This looks like a unix timestamp which is the number of seconds since 1/1/1970. If you want just the date, you need to calculate the number of days and add it to 1/1/1970 like so: ``` to_date('1970-01-01','YYYY-MM-DD') + numtodsinterval(1400003659,'SECOND') ``` If you want to retain the timestamp, you can do so like...
The answers are not precise! UNIX time is seconds since 1970-01-01 00:00:00 **UTC!** So, unless your database server runs on UTC you should do it like this: ``` SELECT (TIMESTAMP '1970-01-01 00:00:00' AT TIME ZONE 'UTC' + 1400003659 * INTERVAL '1' SECOND) AT LOCAL FROM dual; ``` or ``` SELECT (TIMEST...
Convert number to date
[ "", "sql", "oracle", "date", "select", "" ]
I am trying to compare data between two ORACLE tables with different table structure, different column names. I need a ORACLE SQL query that compares the data and returns the unmatched data with their IDs. Both the tables have same ID column which can be used as the comparison link. Could anyone please guide me on this...
You should be able to do this with a `FULL OUTER JOIN`: ``` SELECT A.id, A.qty_a, B.qty_b, A.date_a, B.date_b FROM Table_A A FULL OUTER JOIN Table_B B ON B.id = A.id WHERE ( A.qty_a <> B.qty_b OR (A.qty_a IS NULL AND B.qty_b IS NOT NULL) OR (A.qty_a IS NOT NULL AND B...
``` ( (select id_a as id, qty_a as qty, date_a as date from table_a) minus (select id_b as id, qty_b as qty, date_b as date from table_b) ) union ( (select id_b as id, qty_b as qty, date_b as date from table_b) minus (select id_a as id, qty_a as qty, date_a as date from table_a) ) ```
Need to compare data between two ORACLE tables with different table structure and return the discrepancies
[ "", "sql", "oracle", "compare", "" ]
I am trying to rank my students by their points that I've calculated before but the problem is if students have same points they both should be in same rank E.g Student 1 has full points Student 2 has full points they both have to be rank as 1; [![enter image description here](https://i.stack.imgur.com/IZyNy.png)](h...
This is just a fix of Gordon solution using variables. The thing is your rank function isnt the way rank should work. (student 4 should be rank 4) **[SQL Fiddle Demo](http://sqlfiddle.com/#!9/ff872c/1)** *You can add more student to improve the testing.* ``` select er.*, (@rank := if(@points = points, ...
You want a real rank, which is calculated by the ANSI standard `rank()` function. You can implement this in MySQL using this logic: ``` select er.*, (select 1 + count(*) from examresults er2 where er2.points > er.points ) as ranking from exampleresults er; ``` For larger tables, you can ...
Rank users in mysql by their points
[ "", "mysql", "sql", "sorting", "ranking", "mysql-variables", "" ]
I got a mySQL table, that holds the configuration of my project, each configuration change creates a new entry, so that i have a history of all changes, and who changed it. ``` CREATE TABLE `configurations` ( `name` varchar(255) NOT NULL, `value` text NOT NULL, `lastChange` datetime NOT NULL, `changedBy` bigin...
Your method is documented to return indeterminate results (because you have columns in the `select` that are not in the `group by`). Here are three alternatives. The first is standard SQL, using an explicit aggregation to get the most recent change. ``` SELECT c.* FROM configurations c JOIN (SELECT `name`, MAX(...
If we want to avoid SUBQUERY the only other option is JOIN ``` SELECT cc.name, cc.value, cc.lastChange FROM configurations cc JOIN ( SELECT name, value, lastChange FROM configurations ORDER BY lastChange ASC ) c on c.value = cc.value GROUP BY cc.name DESC ```
MySQL Query Fixing/Optimisation for my configuration table
[ "", "mysql", "sql", "performance", "" ]
I've have the following data. ``` WM_Week POS_Store_Count POS_Qty POS_Sales POS_Cost ------ --------------- ------ -------- -------- 201541 3965 77722 153904.67 102593.04 201542 3952 77866 154219.66 102783.12 201543 3951 70690 139967.06 94724.6...
Pretty sure this will get you what you want.. Im using cross apply after ordering the data to apply the SUMS ``` Create Table #WeeklyData (WM_Week Int, POS_Store_Count Int, POS_Qty Int, POS_Sales Money, POS_Cost Money) Insert #WeeklyData Values (201541,3965,77722,153904.67,102593.04), (201542,3952,77866,154219.66,10...
You can use `SUM()` in combination with the [OVER Clause](https://msdn.microsoft.com/en-us/library/ms189461.aspx) Something like: ``` SELECT WM_Week. , SUM(POS_Store_Count) OVER (ORDER BY WM_Week ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) FROM Table ```
Calculate Sum From Moving 4 Rows in SQL
[ "", "sql", "sql-server", "azure-synapse", "" ]
Ok so I have a table with, amongst other, columns: name, c\_id, date. Certain entries in that table obey a certain criteria, which I can effectively select using WHERE, so this is not a problem. What I would like, then, is a way to group by, in addition to the name and c\_id columns, a *group* of three dates: date - ...
Updated for new sample data: ``` SELECT t.name, t.c_id, t.date pivot_date, COUNT(*) count FROM record t JOIN record t2 ON t2.name = t.name AND t2.c_id = t.c_id AND t2.date >= t.date - INTERVAL 1 DAY AND t2.date <= t.date + INTERVAL 1 DAY WHERE t.other_stuff = 'relevant criteri...
This is a way: ``` @dt := '2015-12-10' SELECT Name , c_id, MAX(`date`) maxdate, COUNT(*) countof FROM table1 WHERE date >= @dt - INTERVAL 1 DAY AND `date` < @dt + INTERVAL 2 DAY GROUP BY Name , c_id ``` Note the date column could be MIN(date) as an alternative
SQL Group By set of dates
[ "", "mysql", "sql", "group-by", "" ]
In SQL Server 2014 I try to count a value per game per row like this: [![enter image description here](https://i.stack.imgur.com/Hqs7x.png)](https://i.stack.imgur.com/Hqs7x.png) Does anybody know if this is possible and how?
An old solution for this is to use a query like this: ``` SELECT t1.id, t1.Game, t1.Points, SUM(t2.Points) [Points (Add)] FROM yourTable t1 JOIN yourTable t2 ON t1.Game = t2.Game AND t1.id >= t2.id GROUP BY t1.id, t1.Game, t1.Points ```
You can use a cumulative sum: ``` select [Order], Game, Points, sum(Points) over (partition by Game order by [Order]) as CumePoints from t; ``` You should avoid using reserved words and keywords for table or column names. In other words, `Order` is a bad name for a column name, because it needs to be escaped.
Add per row the total value in SQL
[ "", "sql", "sql-server", "sql-server-2014", "" ]
I am trying to query through my db to receive all posts which contain a certain user\_id as owner or participant of the post. My DB structure is as following: ``` id: INT media_id: INT owner_id: INT participants: STRING eg. [1,2] comments: TEXT eg. [{},{}] ``` Here are two example entries: ``` id: 1, media_id: 2, o...
If you are willing to change your data structure for `participants` field to a comma separated value e.g. `1,2` or `2,1`, you can then use: `SELECT * FROM posts WHERE owner_id = 1 OR FIND_IN_SET(1, participants);`
**This will do the trick:** ``` SELECT * FROM posts WHERE owner_id = 1 OR participants like "%,1]" OR participants like "[1,%" OR participants like "%,1,%" ```
mySQL WHERE clause with column = val1 OR coumn IN values
[ "", "mysql", "sql", "" ]
Can a WHERE clause return NULL instead of TRUE or FALSE? According to the exercise below it is possible, but i can't imagine an example that returns NULL, Is it really possible? ``` 4. Which of the following values can NOT be returned after evaluation of WHERE clause condition? A. UNKNOWN B. TRUE C. FALSE D. NULL ...
In SQL, all logical operators evaluate to TRUE, FALSE, and UNKNOWN ([Oracle docs](https://docs.oracle.com/cd/B19306_01/server.102/b14200/conditions004.htm)) in MySQL UNKNOWN result calls NULL ([MySQL docs](https://docs.oracle.com/cd/E17952_01/refman-5.5-en/logical-operators.html)). According to oracle documentation: ...
> Not even a NULL can be equal to NULL. 1. The correct way to understand NULL is that it is not a value. Not “this is a NULL value” but “this NULL is not a value.” Everything either is a value, or it isn’t. 2. When something is a value, it is “1,” or “hello,” or “green,” or “$5.00″ etc – but when something is...
Can a WHERE clause predicate evaluate to NULL?
[ "", "sql", "oracle", "null", "where-clause", "clause", "" ]
I can't connect to SQL Server and connection string of my project is: ``` <add name="Teleport_DEVEntities" connectionString="metadata=res://*/Data.Model.AdvertisingModel.csdl|res://*/Data.Model.AdvertisingModel.ssdl|res://*/Data.Model.AdvertisingModel.msl;provider=System.Data.SqlClient;provider connection string=&quot...
That connection string is only supported by Entity Framework. (To be fair, the keyword "entities" is in the key name!) If you want to use the connection string in an ADO raw connection, remove anything outside the `&quot;` string parts, including the `&quot;`s: Change it to: ``` <add name="Teleport_DEVEntities" co...
It seems the connectionString is of EntityFramework Type. **Possible way could be skipping metaData** and then **getting the complete connectionString.** > The below code saved my time !! ``` if (connectionString.ToLower().StartsWith("metadata=")) { System.Data.Entity.Core.EntityClient.EntityConnectionStringBuild...
How do I solve "Keyword not supported: 'metadata' "?
[ "", "sql", "sql-server", "database-connection", "connection-string", "" ]
I have the following records in my database table: ``` Date Credit Debit Description --------------- ------- ------- --------------- 12-24-2015 5 Purchased credit 12-20-2015 1 Consumed credit 12-15-2015 3 Purchased credit 12-08-2015 ...
To produce balance use `sum()` in analytical version. ``` select tdate, credit, debit, sum(nvl(credit, 0)-nvl(debit, 0)) over (order by rn) balance, description from ( select tdate, credit, debit, row_number() over (order by tdate) rn, description from test) order by rn desc ``` If your table c...
You should be able to use the `LAG` analytic function for this to look at the previous row's data. ``` SELECT Date, Credit, Debit, LAG(Balance, 1, 0) OVER(ORDER BY Date) - Debit + Credit AS Balance, Description FROM sometable ``` The `1` argument means that it looks 1 row previous, t...
Calculate balance from Credit and Debit records
[ "", "sql", "database", "oracle", "oracle11g", "" ]
I have two columns, an ID, and the other a value which is either 0 or 1. I am trying to select all Rows for the ID where it has a 0 and a 1, for example, ``` RowNumber ------------- ID ------- value 1 ------------------- 001 ------- 1 2 ------------------- 001 ------- 1 3 ------------------- 001 ...
You can use window version of `COUNT`: ``` SELECT RowNumber, ID, value FROM ( SELECT RowNumber, ID, value, COUNT(CASE WHEN value = 1 THEN 1 END) OVER (PARTITION BY ID) AS cntOnes, COUNT(CASE WHEN value = 0 THEN 1 END) OVER (PARTITION BY ID) AS cntZeroes FROM test WHERE value IN (0,1) ) AS t WH...
`DISTINCT` is indeed not allowed in a windowed version of the `COUNT`, so you can use `MIN` and `MAX` instead. ``` DECLARE @T TABLE(RN int, ID int, value int); INSERT INTO @T (RN, ID, value) VALUES (1, 001, 1), (2, 001, 1), (3, 001, 1), (4, 002, 1), (5, 002, 0), (6, 003, 1), (7, 003, 1), (8, 004, 1), (9, 004, 0), (10...
select rows where ID has variation of values
[ "", "sql", "sql-server", "" ]
My executed SQL query is as follow : ``` update elements E set E.END_I = (select n.node_num from nodes N where abs(E.X_I - N.XI) < 0.001 and abs(E.Y_I - N.YI) < 0.001 and abs(E.Z_I - N.ZI) < 0.001 ) ``` It t...
Your query is slowed down by the `abs()` function as the index on bare column doesn't work with expressions. Try changing the query to at least give the db a chance to use an index ``` update elements E set E.END_I = (select n.node_num from nodes N where N.XI < E.X_I + 0.001 ...
Create indices on columns X\_I, Y\_I, Z\_I, then run statement: ``` MERGE INTO elements dst USING ( SELECT e.x_i, e.y_i, e.z_i, n.node_num FROM nodes N JOIN elements E ON abs(E.X_I - N.XI) < 0.001 and abs(E.Y_I - N.YI) < 0.001 and abs(E.Z_I - N.ZI) < 0.001 ) src ON dst.X_I = src.X_I AN...
Slow query execution in Firebird
[ "", "sql", "performance", "firebird", "" ]
I am new to ORACLE SQL and I am trying to learn it quickly. I have following table definition: ``` Create table Sales_Biodata ( Saler_Id INTEGER NOT NULL UNIQUE, Jan_Sales INTEGER NOT NULL, Feb_Sales INTEGER NOT NULL, March_Sales INTEGER NOT NULL ); Insert into Sales_Biodata (SALER_ID,JAN_SALES,Feb_Sales,March_Sales...
Your data model is wrong. The first thing I would do is to unpivot data using this query: ``` select * from sales_biodata unpivot ( val for mon in ( JAN_SALES,FEB_SALES,MARCH_SALES ) ) ; ``` and after this, getting two top values is relatively easy: ``` SELECT * FROM ( SELECT t.*, dense_rank() ov...
Getting the maximum value is simply: ``` select greatest(jan_sales, feb_sales, mar_sales) ``` If you want the second value: ``` select (case when jan_sales = greatest(jan_sales, feb_sales, mar_sales) then greatest(feb_sales, mar_sales) when feb_sales = greatest(jan_sales, feb_sales, mar_sal...
Case statement not supporting horizontal search with column name in query
[ "", "sql", "oracle", "" ]
I have a table like this: ``` id | name | surname | city| ------------------------------- '1', 'mohit', 'garg', 'delhi' '2', 'mohit', 'gupta', 'delhi' '3', 'ankita', 'gupta', 'jaipur' '4', 'ankita', 'garg', 'jaipur' '5', 'vivek', 'garg', 'delhi' ``` I am looking for a query that returns (id,city) grouped by city, ...
Perhaps the only way without subqueries is to use a trick with `substring_index()` and `group_concat()`: ``` select city, substring_index(group_concat(id), ',', 2) from t group by city; ``` This puts the ids in a comma-delimited list, rather than in separate rows. Also, you have to be careful about the size of the in...
You can do this with a `LEFT OUTER JOIN`, although using a subquery will probably be clearer and might be faster. Here's a method using the `JOIN`: ``` SELECT T1.id, T1.city FROM My_Table T1 LEFT OUTER JOIN My_Table T2 ON T2.city = T1.city AND T2.id <= T1.id GROUP BY T1.id, T1.city HAVING COUNT...
SQL: Find top n in groupby data
[ "", "mysql", "sql", "" ]
Yesterday I asked a question about ranking students by their points. [[Rank users in mysql by their points](https://stackoverflow.com/questions/34637943/rank-users-in-mysql-by-their-points) ] I actually solved my problem with the help I've recieved from other question (thanks to everyone who helped me). Meanwhile I...
Many people think of `NULL` as meaning `no value` or `non-existent`. Even [Wikipedia](https://en.wikipedia.org/wiki/Null_%28SQL%29) explains it this way. Think of it as `unknown value` and everything will make more sense. One cannot compare two `unknown values` because, well, they are not known. They are not equal bu...
You compare `@points = points` which results in `@points=NULL`. But any comparison to `NULL` results in `UNKNOWN`: ``` value= NULL -> UNKNOWN value<>NULL -> UNKNOWN value< NULL -> UNKNOWN value> NULL -> UNKNOWN ``` Even `NULL=NULL` results in `UNKNOWN`. Of course there are exceptions: `DISTINCT` and `GROUP BY` con...
Why null values are not ranking same in mysql?
[ "", "mysql", "sql", "database", "null", "ranking", "" ]
``` SELECT b.first_name, b.last_name, SUM(t.price_total) FROM brokers b LEFT OUTER JOIN trades t ON b.broker_id=t.broker_id GROUP BY b.broker_id ``` My problem question asks to 'Display the total value of each broker's trades'. The answer groups by `b.first_name||' '||b.last_name`, but I think the group by should be d...
try this: ``` SELECT b.broker_id, b.first_name, b.last_name, SUM(t.price_total) FROM brokers b LEFT OUTER JOIN trades t ON b.broker_id=t.broker_id GROUP BY b.broker_id, b.first_name, b.last_name ``` When you use GROUP BY, select clause can have only the columns specified in GROUP BY and aggregated/calculated fields f...
A slightly different approach is to group the trades by broker ID, then join the result of that to the brokers table: ``` SELECT b.first_name, b.last_name, price_sum FROM brokers b LEFT OUTER JOIN ( SELECT broker_id, SUM(price_total) AS price_sum FROM trades GROUP BY broker_id ) t ON b.broker_id=t.broker_id ```...
Oracle SQL using group by: Can you group by a field used to join two tables?
[ "", "sql", "oracle", "group-by", "outer-join", "" ]
A Tenis database I'm working with contains rows as matches. The row has the player name and a condition (win or loss). I need to display a table with ALL the players showing the player name, total games, number of wins, number of losses and win percentage. I haven't figured out how to properly set up the SELECT statem...
Realistically, you should only be asking for player, TotalGames, and Wins. Everything else should be done in your code, but here it is in case you absolutely want to stray from good design: ``` SELECT player, COUNT(*) AS TotalGames, SUM(CASE WHEN condition='win' THEN 1 ELSE 0 END) AS Wins, COUNT(*)-SUM(CASE WHE...
Probably the simplest way to write this code in MySQL is: ``` SELECT player, COUNT(*) AS TotalGames, SUM(condition = 'win' ) AS NumWins, SUM(condition = 'lose') AS NumLosses, AVG(condition = 'win') AS WinPercentage FROM tenis_table GROUP BY player; ``` This uses a MySQL extension of treat...
SQL SELECT statement that displays number of wins/losses based off a value ("win" or "loss")
[ "", "mysql", "sql", "select", "" ]
I have a table where I need to get the oldest date from a group and be able to return all rows. I'm finding it difficult since I need to return the system\_id field. ``` AssignedProfsHistory MatterID EffectiveDate 1 33434-3344 08/22/2005 2 33434-3344...
Since you want to keep the ties, I'd do it like this: ``` SELECT t2.AssignedProfsHistory, m.MatterID, t2.EffectiveDate FROM ( SELECT MatterID, MIN(EffectiveDate) med FROM AssignedProfsHistory WHERE AssignedType = 'Originating' GROUP BY MatterID ) t1 INNER JOIN AssignedProfsHistory t2 ON t2.MatterID = t1....
``` select AssignedProfsHistory, MatterID, EffectiveDate from ( SELECT aph.AssignedProfsHistory, m.MatterID, aph.EffectiveDate, row_number() over(partition by m.MatterID order by aph.EffectiveDate) as rn from AssignedProfsHistory aph INNER JOIN Matters m ON aph.Matters = m.Matters WHERE aph.AssignedType = 'Originati...
How do I find the oldest date in Group
[ "", "sql", "sql-server", "" ]
I have a table that looks like the following - ``` ╔═════════╦════════════════════════╦════════════════╗ ║ QueueID ║ AttributeName ║ AttributeValue ║ ║ 123 ║ Domain ║ Azure ║ ║ 123 ║ Area ║ EMEA ║ ║ 123 ║ ContractType ║ Contract1 ...
I haven't tested this, but please give it a try: ``` SELECT QueueID FROM MyTable WHERE ( AttributeName = 'Domain' AND AttributeValue = '.NET' ) OR ( AttributeName = 'Area' AND AttributeValue = 'Asia-Pacific' ) OR ( AttributeName = 'ContractType' AND AttributeValue = 'Contract2' ) OR ( Attribut...
``` SELECT queueid FROM yourtable WHERE AttributeName = 'Domain' AND AttributeValue = '.NET' intersect SELECT queueid FROM yourtable WHERE AttributeName = 'Area' AND AttributeValue = 'Asia-Pacific' intersect SELECT queueid FROM yourtable WHERE AttributeName = 'ContractType' AND Attr...
SQL - How to return rows with a common column value and also based on other conditions?
[ "", "sql", "sql-server", "" ]
I want to get statistics with sql query. My table is like this: ``` ID MATERIAL CREATEDATE DEPARTMENT 1 M1 10.10.1980 D1 2 M2 11.02.1970 D2 2 M3 18.04.1971 D3 ..................... ..................... ..................... ``` How can I get a range of data count like this ``` DEPARTMENT AGE<10...
Assuming that CREATEDATE is a date column, in PostgreSQL you can use the [AGE](http://www.postgresql.org/docs/8.2/static/functions-datetime.html) function: ``` select DEPARTMENT, age(CREATEDATE) as AGE from Materials ``` and with date\_part you can get the age in years. To show the data in the format that you want, y...
You can use `extract(year FROM age(createdate))` to get the exact age i.e ``` select extract(year FROM age(timestamp '01-01-1989')) age ``` will give you Result: ``` age --- 27 ``` so you can use following select statement to get your desired output: ``` SELECT dept ,sum(CASE WHEN age < 10THEN 1 END) "age...
SQL query to group by age range from date created
[ "", "sql", "postgresql", "" ]
This Code does not work: ``` SELECT ( SELECT [T_Licence].[isInstalled] FROM [T_Licence] WHERE [T_Licence].[System] = [T_System].[ID] AND [T_Licence].[Software] = 750 ) AS [IsInstalled] ,* FROM [T_System] WHERE [IsInstalled] = 1 ``` I have to do it this way, but this makes the whole code ...
Try this one - ``` SELECT * FROM wf_subj_it.T_System s CROSS APPLY ( SELECT /*TOP(1)*/ t.isInstalled FROM wf_subj_all.T_Licence t WHERE t.[System] = s.ID AND t.Software = 750 ) t WHERE t.isInstalled = 1 ```
Just wrap the query with an outer select and it should work. ``` SELECT * FROM ( SELECT ( SELECT [T_Licence].[isInstalled] FROM [T_Licence] WHERE [T_Licence].[System] = [T_System].[ID] AND [T_Licence].[Software] = 750 ) AS [IsInstalled], * FROM [T_System] ) As tbl1 WHERE [IsInstal...
WHERE Clause does not accept just defined column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
first of all i have 3 schema as follow ( MEDICINE, MEDICINE1 ,MEDICINE2) . **MEDICINE** and **MEDICINE1** have same tables, **MEDICINE** have updated data and **MEDICINE1** have old data. and i have **MEDICINE2** with no tables so i want to create table in **MEDICINE2** as select from **MEDICINE** where not in **MEDICI...
this is working fine ``` SET SERVEROUTPUT ON; Declare v_dml_str VARCHAR2 (400); cursor c1 is SELECT owner,table_name from SYS.all_tables where global_stats='YES' and owner = 'MEDICINE'; BEGIN FOR i in c1 LOOP v_dml_str := 'Create table MEDICINE2.' ||i.table_name||'...
Use the following code. It will execute without any errors ``` CREATE OR REPLACE PROCEDURE SYSTEM.create_table_from_schema IS v_dml_str VARCHAR2 (400); v_own_array VARCHAR2(128); v_tab_array VARCHAR2(128); cursor c1 is SELECT owner,table_name from SYS.all_tables where global_stats='YES' An...
Create table as select statement using procedure
[ "", "sql", "oracle", "plsql", "procedure", "" ]
I have an SQL table with a structure similar to the following: ``` Name Value (varchar) (bit) __________________ Val1 1 Val2 1 Val3 0 Val4 0 Val1 0 Val2 0 Val3 0 Val4 1 ``` So basically, I have two instances of the same row but with a different bit value....
Observing that "bitwise OR" has the same function as the aggregate function `MAX` (assuming all inputs are either 0 or 1, if any input is 1, the result is 1, otherwise 0) and accounting for the fact that we can't directly aggregate `bit`, this seems to work: ``` declare @t table (Name varchar(17) not null,Value bit no...
You can try this, hoping that value is numeric field with values 0 and 1. ``` SELECT Name, MAX(Value) FROM [table] GROUP BY Name ```
How to perform bitwise OR operation between two rows in same SQL table?
[ "", "sql", "sql-server", "bitwise-operators", "" ]
I ran the following query on a previous years data and it took 3 hours, this year it took 13 days. I don't know why this is though. Any help would be much appreciated. I have just tested the queries in the old SQL server and it works in 3 hours. Therefore the problem must have something to do with the new SQL server I...
If you look at the execution plan the time is in the actual update Look at the log file Is the log file on a fast disk? Is the log file on the same physical disk? Is the log file required to grow? Size the log file to like 1/2 the size of the data file As far as indexes test and tune this If the join column...
Create Index on ABCJan2014 table as it is currently a heap
SQL Server Update query very slow
[ "", "sql", "sql-server", "" ]
I have a table like so ![enter image description here](https://i.stack.imgur.com/np4co.png) I want to get the first date (column "dt") of the final "id" sequence. According to this example the final "id" sequence is 6 I Want to get the date of the first appearance **"2015-01-04"**
This approach utilizes two ROW\_NUMBERs, both will increment similar for the first *n* rows with the same `id`: ``` SELECT MIN(id), MIN(dt) FROM ( SELECT tab.*, ROW_NUMBER () OVER (ORDER BY dt DESC) AS rn, ROW_NUMBER () OVER (PARTITION BY id ORDER BY dt DESC) AS rn2 FROM tab ) AS dt WHERE RN ...
This is a bit of a pain. One method using standard SQL: ``` select min(t.date) from t cross join (select top 1 id from t order by date desc ) tt where not exists (select 1 from t t2 where t2.date >= t.date and t2.id <> tt.id ); ``` Another met...
Get the first line of the final sequence
[ "", "sql", "sql-server", "" ]