Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a query (in SAP, specifically). ``` SELECT T1.[Name], sum(T0.[U_pptQuota]) AS [Quota] FROM OHEM T0 INNER JOIN OUBR T1 ON T0.[branch] = T1.[Code] ``` It returns (correctly) the following info: ``` # Branches Name 1 Main 11.40 Y 2 Mesa 24.70 Y 3 Phoenix 24.90 Y ...
@phroureo Based on the additional information that you added and the assumptions in my last comment... The query should look something like this: ``` SELECT T1.[Name], sum(T0.[U_pptQuota]) AS [Quota], sum (T4.Total) as Total FROM OHEM T0 INNER JOIN OUBR T1 ON T0.[branch] = T1.[Code] LEFT JOIN (Select T2.OwnerCode, ...
This happens because your joins are incorrect. Not sure what the meaning of the tables are but ON T0.[empID] = T2.[OwnerCode] multiplies entries because you have many T2 records with the same ownerCode and/or ON T2.[DocEntry] = T3.[DocEntry] multiplies entries because you have multiple same docEntry values in T3.
When I add more JOINs in a SQL query, it returns a different amount, even though nothing else changes
[ "", "sql", "sql-server", "" ]
I am working on a database and one of the final tasks left is to create user accounts. For some reason I can't seem to get it to work. In fact, none of the commented code works when uncommented. Our primary concern is being able to automate the creation of user accounts rather than creating them manually. I am hoping s...
Seems funny that i am answering my own question but i solved the issue. The code i used to create apex users is the following. ``` APEX_UTIL.CREATE_USER( p_user_name => :new.USERNAME, P_web_password => 'Password123', p_change_password_on_first_use => 'Y'); ``` The error above was solved by changing the se...
You cannot execute create statements directly from PLSQL. change this to: ``` IF INSERTING THEN :NEW.SRN := seq_SRN.nextval; execute immediate 'CREATE USER '||:new.USERNAME ||' IDENTIFIED BY PASSWORD PROFILE app_user PASSWORD EXPIRE'; ```
PL/SQL trigger: can't create apex user
[ "", "sql", "database", "oracle", "plsql", "oracle-apex", "" ]
I have a a few `left join` and so I would like to add/merge this `sql` inside my other query: ``` SELECT A.ID FROM Table1 as A LEFT JOIN (SELECT T.ID, T.TRF_TAKEN, SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 THEN CAST([TRF_TAKEN] AS FLOAT) ELSE ...
Remove `;` from `GROUP BY ID;)`, add `T.TRF_TAKEN` to `GROUP BY` clause and add the table alias `Transfc` that you joined on. ``` SELECT A.ID, Transfc.UNT_TRNSFER FROM Table1 AS A LEFT JOIN ( SELECT T.ID, T.TRF_TAKEN, SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 THEN CAST([TRF_TAKEN] AS FLOAT) ...
You just need to put your non aggregated fields into the GROUP BY. You are asking it to group by EMPLID but you are only selecting t.ID and t.TRF\_Taken. ``` select A.ID from Table1 as A LEFT JOIN ( SELECT T.ID, T.TRF_TAKEN, SUM(CASE WHEN CAST([UNT_TRNSFER] AS FLOAT) = 0 THEN CAST([TRF_TAKEN] AS FLOA...
How to do a left or subquery with this SQL statement?
[ "", "sql", "sql-server", "" ]
We are using procedural approach (while loop) for inserting records into a particular table. the insert syntax is like below, ``` DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01', @FLAG INT CREATE TABLE #Tmpdata (officeId int,id smallint, weekDate date,startsOn varchar(10),endsOn varchar(10),flag bit); WHILE (@CNT <7...
This is making a number of assumption because you didn't post ddl or any consumable sample data. Also, there is a variable @lvCounter not defined in your code. This is perfect opportunity to use a tally or numbers table instead of a loop. ``` declare @lvCounter int = 42; DECLARE @CNT INT = 0, @WEEK DATE = '2015-11-01...
Please can you provide sample data? You can do something like: ``` SELECT DateIncrement = SUM(DATEADD(D,@CNT,@WEEK)) OVER (ORDER BY officeID) FROM... ``` This gets an incremented date value for each record which you can then check against your start and end dates.
Convert Procedural Approach into Set Based Approach in Sql-Server
[ "", "sql", "sql-server", "t-sql", "" ]
I have a similar table: ``` ID | Name | Time -------|---------|----------------------------- 111 | AAA | 2015-11-05 15:39:24.000 222 | BBB | 2015-11-04 11:29:11.000 111 | AAA | 2015-11-02 13:12:10.000 333 | CCC | 2015-11-05 15:39:24.000 111 | AAA | 2015-11-01 15:39:24.000 ``` ...
If there are more columns you want to keep you could use a CTE with `ROW_NUMBER` function: ``` WITH CTE AS ( SELECT Id, Name, Time, OtherColumns..., RN = ROW_NUMBER() OVER (PARTITION BY ID Order By Time DESC) FROM dbo.TableName ) SELECT Id, Name, Time, OtherColumns... FROM CTE WHERE RN = 1 ``` If i...
Use `MAX` function to find the latest time. **Query** ``` SELECT ID, Name, MAX(Time) AS [Time] FROM your_table_name GROUP BY ID, Name; ```
Query max time (latest) by id SQL Server
[ "", "sql", "sql-server", "" ]
Imagine a table with two columns as follows: ``` Account_ID (integer) Product_ID (integer) ``` Other columns are not material. This lists products bought by accounts. I want to create an output with three columns like so: ``` Account_ID_1 | Account_ID_2 | Count(distinct product_ID) ``` The result should have a comb...
this works for me: ``` select t1.Account_ID, T2.Account_ID, count(t1.Product_ID) count_product_id from MYTABLE t1 join MYTABLE t2 on t1.Product_ID = t2.Product_ID where t1.Account_ID <> t2.Account_ID group by t1.Account_ID, t2.Account_ID order by 1,2 ```
Here I calculate how many product both account have in comon. ``` SELECT T1.Account_ID as Account_ID_1, T2.Account_ID as Account_ID_2, COUNT(distinct T1.product_id) From YourTable as T1 JOIN YourTable as T2 ON T1.Account_ID < T2.Account_ID AND T1.product_ID = T2.product_ID GROUP BY T1.Acco...
Find distinct count of common accounts between products
[ "", "sql", "distinct", "combinations", "google-bigquery", "" ]
This question is quite vague so I will just give an example If I have a DB with for example a country attribute, where the country can appear more than once, how could I check that another attribute, called building, is null in all instances of that country? And how would you do this for all countries? i.e. check tha...
Checked in Postgres: `select country from countries where country not in (select country from countries where building is not null) group by country order by country;` Where `countries` is the table name.
Here's another one, using group by: ``` SELECT country FROM countries group by country having sum(building) is null; ``` I've tested this in MySql and SQL Server.
How to use a where clause on all instances of an attribute
[ "", "sql", "where-clause", "" ]
I have a question ! I need to make a university project, and in this project i will have one database table like this : [![enter image description here](https://i.stack.imgur.com/Agz4B.png)](https://i.stack.imgur.com/Agz4B.png) This table will have a LOT of records !!!!!! And for manage this i need to create a valid...
Your question does not have enough information to provide a real answer. Here is some guidance on how to think about the situation. Which approach depends on the nature of your application and especially on what "validation" means. One reasonable interpretation is that "validation" is part of a work-flow process, so i...
Here, there is no need to have a separate "buffer table". You can just properly index the `valid` field. So the following index would essentially automatically create a buffer table: ``` create unique index x on y (id) include (all columns) where (valid = 0) ``` This index creates a copy of the yet invalid data. ...
Buffer table in a database, Good or not?
[ "", "sql", "database", "database-schema", "" ]
I apologise for the terribly-worded question, I tried to phrase it more clearly, but couldn't think of a way to do so. My problem is this: I've got a table with ~20 columns. I need to find all rows which have a particular value in one of the columns, and within that set have the same value in another column as at leas...
Use `EXISTS` to return a person if another person has same surname and DOB but a different phone number (or other unique data). ``` select * from personal_details pd1 where pd1.surname = 'Jones' and exists (select 1 from personal_details pd2 where pd2.surname = pd1.surname and pd2.DOB =...
TRY LIKE BELOW CODE. I have used Self Join to Get the Result. ``` DECLARE @dd AS TABLE (name VARCHAR(1), dob date) INSERT INTO @dd VALUES ('A', '2015-11-04'), ('B','2015-11-04'),('C','2015-05-05'),('D','2015-11-04'), ('E','2015-11-04'),('F','2015-12-04') SELECT *FROM @dd SELECT DISTINCT d.name ,d.dob FROM @dd d IN...
How do I select data from a table where I need to return rows which have a repeat value in one field and a specified value in another?
[ "", "sql", "sql-server", "" ]
I'm doing an analysis using SQL and R, I want to join two tables like below listed: Table 1: ``` ID date a11 20150302 a11 20150302 a22 20150303 a22 20150304 a33 20150306 a44 20150306 a55 20150307 a66 20150308 a66 20150309 a66 20150310 ``` Table 2 ``` ID date a11 20150303 a22 20150304 a22 20150305 a44 20150306 a66...
``` SELECT ID, Date1, Date2 FROM ( SELECT joined.ID, joined.Date1, joined.Date2, ROW_NUMBER() OVER (PARTITION BY ID, Date1 ORDER BY Date2 ASC) AS RowNumber FROM( SELECT t1.ID, t1.[Date] as Date1, CASE WHEN t2.[Date] >= t1.[Date] THEN t2.[Date] ELSE NULL END as [Date2] FROM Table1 t1 LEFT JOIN Table2 t2 ON t1.ID = t2...
I get the same result as markmanguy in R with `dplyr`. For a22, the closest callback for the 20150304 initial call is 20150304, not 20150305. You need a time component to distinguish this. ``` library(dplyr) inner_join(table1,table2,"ID")%>% group_by(ID,date1)%>% filter(date1<=date2)%>% filter(row_number() == 1) > So...
many to many join (same ID with different date)
[ "", "sql", "r", "many-to-many", "match", "seq", "" ]
I have a field that holds an account code. I've managed to extract the first 2 parts OK but I'm struggling with the last 2. The field data is as follows: ``` 812330/50110/0-0 812330/50110/BDG001-0 812330/50110/0-X001 ``` I need to get the string between the second "/" and the "-" and after the "-" .Both fields h...
You can use `CHARINDEX` and `LEFT/RIGHT`: ``` CREATE TABLE #tab(col VARCHAR(1000)); INSERT INTO #tab VALUES ('812330/50110/0-0'),('812330/50110/BDG001-0'), ('812330/50110/0-X001'); WITH cte AS ( SELECT col, r = RIGHT(col, CHARINDEX('/', REVERSE(col))-1) FROM #tab ) SELECT col, r, sub1 =...
...Or you can do this, so you only go from left side to right, so you don't need to count from the end in case you have more '/' or '-' signs: ``` SELECT SUBSTRING(columnName, CHARINDEX('/' , columnName, CHARINDEX('/' , columnName) + 1) + 1, CHARINDEX('-', columnName) - CHARINDEX('/' , columnName, CHARINDEX('/' , co...
Extract string between after second / and before -
[ "", "sql", "sql-server", "t-sql", "" ]
I have two tables, `Show`, `Character`. Each Show has\_many Characters. ``` class Show < ActiveRecord::Base has_many :characters class Character < ActiveRecord::Base belongs_to :show ``` What I want to do is return the results of a Show that is associated with multiple Characters that fit certain criteria. For ...
Using plain SQL, one solution is : ``` select s. * from shows as s join characters as c1 on (s.id=c1.show_id) join characters as c2 on (s.id=c2.show_id) where c1.name='Batman' and c2.name='Robin'; ``` Using Arel, I would translate as : ``` Show.joins('join characters as c1 on shows.id=c1.show_id').joins('join...
So you'll have to get a little fancy with SQL here; especially if you want it to be performant and handle different types of matchers. ``` select count(distinct(characters.name)) as matching_characters_count, shows.* from shows inner join characters on characters.show_id = shows.id and (characters.name = 'Batman' or...
Can I query a record with multiple associated records that fit certain criteria?
[ "", "mysql", "sql", "ruby-on-rails", "ruby", "" ]
``` SELECT .... FROM table_name WHERE a_column is null OR b_column is null OR c_column is null ......; ``` This is my SQL query. I took SELECT result but I dont know which column is empty and I took this result. However my table name and column names are dynamic. I can compile with EXECUTE IMMEDIATE. I need...
Another way to find out all the columns which are completely having NULL values, then you could query **[DBA|ALL|USER]\_TAB\_COLUMNS** view and check `NUM_DISTINCT = 0`. **NOTE :** The statistics must be gathered up to date to get an accurate result. For example, Lets say I have table "**T**" which has two columns, ...
Use `case` in select clause and output null column names as columns like below. ``` select case when o1+o2+o3 = 7 then 'a_column,b_column,c_column' when o1+o2+o3 = 6 then 'b_column,c_column' when o1+o2+o3 = 5 then 'a_column,c_column' when o1+o2+o3 = 4 then 'c_column' when o1+o2+o3 = 3 then 'a_column,b_column' when o1+...
How can I find which column is empty?
[ "", "sql", "oracle", "select", "" ]
> Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement > has 0 parameters. Android doesn't recognise `?` character in `?%` I try to achieve this: ``` String selectQuery = "SELECT * FROM config WHERE Directory Like '?%';"; SQLiteDatabase db...
Use `||` to concat parameter and wildcard: ``` SELECT * FROM config WHERE Directory Like ? || '%'; ```
``` SELECT * FROM config WHERE Directory Like '?' || '%'; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, new String[] {parent}); ``` using `||` solves this issue
Cannot use Like statement in Android SQLite with argument and % character
[ "", "android", "sql", "sqlite", "" ]
For example, I've got a table ``` name | ability kevin|say kevin|scream nike |say ``` I wanna get only kevin in response, when looking for `say` and `scream`. Count of parameters may change.
You can do this with `group by` and `having`: ``` SELECT name FROM t WHERE ability in ('say', 'scream') GROUP BY name HAVING COUNT(*) = 2; ```
One way to do it is: ``` SELECT * FROM YourTableName WHERE name='kevin' AND ability IN ('say','scream'); ``` Another way to do it: ``` SELECT * FROM YourTableName WHERE name='kevin' AND (ability='say' || ability='scream'); ``` Good luck!!
how to select row when column must satisfy multiple value?
[ "", "mysql", "sql", "" ]
I am trying to use a field of a table as parameter of the contains method, but I don't know how to do it. I am trying this: ``` SELECT * FROM tableA AS t1 WITH(UPDLOCK), TableB AS t2 WHERE CONTAINS(t1.FieldX, '"' + t2.FieldY + '"') AND t2.ID IN(1,2,3,4,5); ``` However I get an error that says that is expected a ...
You could do it without *contains* and *full-text-search*, I mean using *like* operator: ``` select * from tableA as t1 with(UPDLOCK), TableB as t2 where t1.FieldX like '%"'+t2.FieldY+'"%' and t2.ID IN(1,2,3,4,5); ```
The function you are looking for is CHARINDEX or PATINDEX... > where CHARINDEX('"' + t2.FieldY + '"', t1.FieldX) <> 0 not sure if you need the '"' If you want to use wildcards then use the PATINDEX function Let me know if this works.
how to use a field of a table in the parameter of the contains function?
[ "", "sql", "sql-server", "full-text-search", "" ]
I am trying to create a view that will give me a total usage,total amount and a nickname for a client. if nothing was found it will leave the other columns null but display the client name and nickname. I simplified my query and changed the table name and column for convenience. Any help will be appreciated. Thanks in ...
Since you don't have the table for users, and you have a huge case/when expression... You really SHOULD create the users table! It would be a nightmare to maintain the 2 large when/case expressions correctly! If you still prefer to opt out from creating users table, just like Sami suggested, you should create an inlin...
Since the database doesn't have rows for that, you cannot do it this way. If you have a separate table for users, you can use an OUTER join to get this. Surely you have that and don't have a huge CASE WHEN thing in the query itself? If it's only for two users, you can also have an OUTER join with a simple select/unio...
How to Have an empty row if query result couldn't find anything with one assigned value under one column?
[ "", "sql", "sql-server", "t-sql", "plsql", "database-administration", "" ]
I have an `employee` and a `supervisor` table. A supervisor is an employee. The `employee` table looks like this: ``` employee_id | employee_name 1 | Freeman 2 | Manfred ``` The `supervisor` table looks like this (fields are foreign keys to `employee` table): ``` supervisor_id | employee_id 1 ...
If there is no user interface that needs to be notified then the event the validation fails, siride's solution using triggers is a good one, Gordon Linoff solution would also work. A simpler solution, that would also be able to notify a user interface that the data failed validation would be be to update the table usin...
This isn't easily possible purely with primary keys or check constraints. * Primary keys are unique constraints that specify that no row may have the same primary key as any other row. But it doesn't say that certain combinations are invalid. * Check constraints can use more complex logic, but only about values of col...
is primary key (a,b) different from primary key (b,a)?
[ "", "sql", "sql-server", "primary-key", "" ]
I have the following table called `Tracking`: ``` +----------+------------+-----------+---------+ | DeviceID | DeviceName | PageCount | JobType | +----------+------------+-----------+---------+ | 1 | Device1 | 22 | print | | 2 | Device2 | 43 | copy | | 1 | Device1 | ...
The easiest way I can think for this is: ``` SELECT DeviceName, SUM(CASE WHEN JobType = 'copy' THEN PageCount ELSE 0 END) AS Copy, SUM(CASE WHEN JobType = 'print' THEN PageCount ELSE 0 END) AS Print FROM Tracking GROUP BY DeviceName ```
what you need to do is: 1. get sum of pageCount for copy 2. get sum of pageCount for print 3. join the two results getting the sums is easy, just need to: ``` 1) select DeviceName, sum(pageCount) as copy from Tracking where jobType = 'copy' group by deviceName 2) select DeviceName, sum(pageCount) as print from Track...
SQL - Multiple queries on same table
[ "", "sql", "" ]
I have a specific request to do on my database (PostgreSQL v9.4.5), and I don't see any elegant solution in pure SQL to solve it (I know I can do it using Python or other, but I have several billions lines of data, and the calculation time would be greatly increased). I have two tables : *trades* and *events*. These t...
Here is my example with row\_number. Also, SQL Fiddle: [SO 33608351](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/4351) ``` with trades AS ( select 201 as id, 32400.524 as time, 53 as price, 2085 as volume, 'xxx' as foo union all select 202, 32400.530, 53, 1162, 'xxx' union all ...
Try this and let me know if. We can also you `row_number() over(partion by)` clause but I am not sure if it will work on postgreSQL. Anyways try this. ``` SELECT min(t.id) as trade_id,min(e.id) as event_id, min(t.time) as time,min(t.price) as price, min(t.volume) as volume, min(e.bar) as bar, min(t.foo) as f...
SQL Select Inner join one by one
[ "", "sql", "inner-join", "" ]
I'm trying to calculate the age of a user based on the current year and his year of birth, but something in my syntax appears to be incorrect and I can't spot it. ``` CREATE TABLE Normal_Users( first_name varchar(20), last_name varchar(20), date_of_birth date, age int = year(CURRENT_TIMESTAMP) - year(date_of_birth) ...
Use `AS`: ``` CREATE TABLE Normal_Users( first_name varchar(20), last_name varchar(20), date_of_birth date, age int AS (year(CURRENT_TIMESTAMP) - year(date_of_birth)) ); ``` **[`Generated columns in MySQL`](http://mysqlserverteam.com/generated-columns-in-mysql-5-7-5/)** > < type> [ GENERATED ALWAYS ] **AS ( < expres...
How do you do it in your brain? You subtract the year of birth from current year, Then you if the birthday already happen this year. If Yes fine, else it means he will have this year the age (so -1 yearold) diff of the years is easy. how to compare month and day to know if we are before or after month\*100+day w...
Calculating age derived from current date and DOB
[ "", "sql", "" ]
I'm trying to get distinct values from a table. When I ran `select distinct count(id) from table` I got over a million counts. However if I ran `select count(distinct id) from table` I've got only around 300k counts. What was the difference of the two queries? Thanks
When you do `select distinct count(id)` then you are basically doing: ``` select distinct cnt from (select count(id) as cnt from t) t; ``` Because the inner query only returns one row, the `distinct` is not doing anything. The query counts the *number of rows* in the table (well, more accurately, the number of rows w...
If id is the pk the count with `distinct count(id)` will match the no of rows returned with `count(distinct id)`. If id is not the pk but has a unique constraint(on id alone, not in combination with any other column), the no of rows returned with `count(distinct id)` will be equal to the count with `distinct count(id)...
select distinct count(id) vs select count(distinct id)
[ "", "mysql", "sql", "" ]
I have this error. I am new to SQL and can't figure what is wrong with my syntax. I changed my INTERSECT statement to inner join realizing SQL does not accept such syntax. However I continue to get an error. ERROR: ``` ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your...
Try this: ``` Select has_property.userId From has_property hp JOIN hasRatings_Rate hRR ON hp.propertyId = hRR.propertyId JOIN House h ON h.id = hRR.id JOIN has_weather hw ON hw.homeAddId = h.homeAddId JOIN weather_year wy ON hw.weatherId = wy.weatherId WHERE hRR.ratingId = 5 AND wy.avgTemp > 55 ``` No need for any s...
Try this: ``` Select has_property.userId From has_property INNER JOIN ( SELECT id FROM ( Select hRR.propertyId as id From hasRatings_Rate hRR Where hRR.ratingId = 5 ) a INNER JOIN ( Select h.propertyId as id From House h, has_weather hw, weather_year wy Where hw.weathe...
SQL inner join syntax error
[ "", "mysql", "sql", "" ]
I'm porting some Postgres SQL to MySQL and am trying to set the starting values of three columns to specific values. The table is as follows: ``` CREATE TABLE ITEM ( ORDID NUMERIC(4) NOT NULL, ITEMID NUMERIC(4) NOT NULL, PRODID NUMERIC(6), ACTUALPRICE NUMERIC(8,2), QTY ...
MySQL uses [AUTO\_INCREMENT](https://dev.mysql.com/doc/refman/5.6/en/example-auto-increment.html) for that purpose. Rather than making new sequence types, you apply it to an existing integer column. [Unfortunately you can only have one per table.](https://dev.mysql.com/doc/refman/5.6/en/create-table.html) > There can...
You can use table with AUTO\_INCREMENT key to emulate sequences: ``` CREATE TABLE ORDID (id INT PRIMARY KEY AUTO_INCREMENT) AUTO_INCREMENT = 622; CREATE TABLE PRODID (id INT PRIMARY KEY AUTO_INCREMENT) AUTO_INCREMENT = 200381; CREATE TABLE CUSTID (id INT PRIMARY KEY AUTO_INCREMENT) AUTO_INCREMENT = 109; ``` Each of t...
Postgres Sequence Port to MySQL
[ "", "mysql", "sql", "postgresql", "" ]
I have a table in my database which contains a column called DateTimes. This column has DateTime data inside it which I would like to select the different hours for which this table has data for. For example, if the column has these entries: ``` 2015-05-03 01:06:45 2015-05-03 04:51:09 2015-05-03 05:08:11 2015-05-03 09...
Try this. Test Data: ``` DECLARE @MyTable AS TABLE(DateTimes DATETIME) INSERT INTO @MyTable(DateTimes) VALUES('2015-05-03 01:06:45') ,('2015-05-03 04:51:09') ,('2015-05-03 05:08:11') ,('2015-05-03 09:33:35') ,('2015-05-03 13:46:38') ``` Query: ``` SELECT Hourly FROM (SELECT DATEADD(HOUR, DATEDIFF(HOUR, 0, Dat...
Try the following: ``` SELECT DateTimes FROM MyTable GROUP BY DATEPART(hh, DateTimes), DateTimes; ``` You were simply missing the DateTimes field directly in your group by. Also, from the rest of your question, you may want to do the following: ``` SELECT FORMAT(DateTimes, 'dd-MM-yyyy hh:00:00', 'en-US') FROM MyTab...
Grouping DateTime by hour in SQL
[ "", "sql", "sql-server", "" ]
I want to count the number of different sheep, and I want it in one table. Like this; ``` Ewes | Rams | Lambs 8 | 5 | 12 ``` The query I try is this, but it doesn't work; ``` SELECT COUNT(e.EweID) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb' FROM Sheep s INNER JOIN Ewe e ON s.SheepID = ...
I don't think you need a `FROM` here at all: ``` select (select count(*) from Ram where Famerid = 123) as RamCount, (select count(*) from Ewe where Famerid = 123) as Count, (select count(*) from Lamb where Famerid = 123) as LambCount ``` (There is no relationship between the rows you are counting, do don't try ...
I think that the problem here is that you don't need an INNER JOIN but an OUTER JOIN ... ``` SELECT COUNT(CASE WHEN e.EweID IN NOT NULL THEN e.EweID ELSE 0 END) AS 'Ewe', COUNT(r.RamID) AS 'Ram', COUNT(l.LambID) AS 'Lamb' FROM Sheep s LEFT OUTER JOIN Ewe e ON s.SheepID = e.EweID LEFT OUTER JOIN Ram r ON s.S...
Using the COUNT with multiple tables
[ "", "sql", "sql-server", "" ]
How do I split a row with ``` Start Date : 02-OCT-2015 End Date : 31-DEC-2015 ``` into rows below in Oracle? ``` 02-OCT-2015 31-OCT-2015 01-NOV-2015 30-NOV-2015 01-DEC-2015 31-DEC-2015 ```
Your desired **DATE arithmetic** could be done using following: * **ADD\_MONTHS** * **LAST\_DAY** * **TRUNC** * **CONNECT BY** i.e. typical row generator * **CASE** expression Let's say you have two dates as **start** and **end** dates, the following query would **split the dates into multiple rows** based on the **M...
``` SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one, SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two FROM YOUR_TABLE t ``` **Alternatively** You could use regex or the substring function. It won't be super fast on very large datasets, but it'll get the job done. as - ``` SELECT REGEX...
How to split a row into multiple rows between two given dates?
[ "", "sql", "oracle", "date-arithmetic", "" ]
I need to write SQL query in order to extract some data. i have this data in my table: ``` ID Store Value 1 9921 NOK 2 9921 NOK1 3 9921 OK3 ``` what i need is to get data from select query like this form: ``` 9921 NOK,NOK1,OK3 ``` Any help please ?
Go through this below example [**Demo: [SQLFiddle]**](http://sqlfiddle.com/#!3/349d3/5) The SQL I used is as below, ``` SELECT store, STUFF( (SELECT DISTINCT ',' + value FROM SampleData WHERE store = a.store FOR XML PATH ('')) , 1, 1, '') AS CombineValues FROM SampleData AS a GROUP BY...
Try to accomplish your excepted output by using `COALESCE`; Create a sample table for testing purpose ``` CREATE TABLE SampleData (id INT ,store INT ,value NVARCHAR(50)) INSERT INTO SampleData VALUES (1 ,9921 ,'NOK') INSERT INTO SampleData VALUES (2 ,9921 ,'NOK1') INSERT INTO SampleData VALUES (3 ,9921 ,'NOK2') ``` ...
Different SQL Select query
[ "", "sql", "sql-server-2012", "" ]
I've got a table with certain attributes such as name and address. In a search field I want to let users of a system type in whatever they know about these people and return the results in a table. Obviously I do want the results that are fitting best to be on top. 1. Should the ranking be done in the SQL command or a...
You might want to check the full text indexes and searches - they have options for ranking that might do the job for you: * [Fulltext index creation info](https://msdn.microsoft.com/en-us/library/ms187317.aspx?f=255&MSPPError=-2147217396) ... and searching functionality info: * [FREETEXTTABLE](https://msdn.microsoft...
Sounds like you are asking for a string comparison function, such as Jaro-Winkler. This is a built in function for Oracle (<http://docs.oracle.com/cd/E18283_01/appdev.112/e16760/u_match.htm>) and I would imagine many other RDBMs. Jaro-Winkler is pretty good at recognizing strings are just in the wrong order, and the s...
SQL Sorting with multiple attributes (order by conformity)
[ "", "sql", "sql-server", "" ]
I have a query that needs to return a single row if there are `more than 2` rows with a certain `ID.` I figured the best way to do this was to add a counter in my query to count the instances of `x` and then return the results `if x >=2` but I'm not sure how in `Oracle`. My query now returns all of the instances of `x...
If you want to get the playlists with 2 or more songs of a certain artist, something like this might help you out: ``` SELECT * FROM playlist p WHERE (SELECT COUNT(1) FROM playlist_songs ps JOIN song s ON ps.song_id = s.song_id JOIN artists art ON s.artist_id = art.artist_id WHERE ps.playlist_id =...
Here's the concept of having and a group by to get songs with count > 1. Note field 1,2,3,4 in this case must not cause the records you want to combine to be unique. Otherwise, pablomatico's approach could work ``` Select Field1, Field2, Field3, Field4 from PLAYLIST p left join PLAYLIST_SONGS ps on p.PLAYLIST_ID = ps....
Add if statement to Oracle query
[ "", "sql", "oracle", "" ]
I am trying to join a company and their details, as well as transactions even if they don't exist. I am counting the transactions to guage how many users are going to a course, if there's no transactions I still want to join the company and details, but the count would be 0, in my query below the training\_company tab...
As Gordon Linoff suggested in the first comment, move the conditions involving the `training_transactions` from the `WHERE` clause into the `LEFT JOIN`. Of course, you should also list the columns explicitly instead of `*` and add a corresponding `GROUP BY` for the `COUNT` to work. ``` SELECT training.course_id ...
I would suggest going a different route altogether and not use left joins. Since you want all data from the training table and you want an aggregate (count in your case) from a different table, I would suggest breaking the aggregate out into a separate subquery. Here's what I mean (note I added aliases to your tables t...
Left join isn't working when I am selecting count from another table
[ "", "mysql", "sql", "" ]
I have some sql statements, which i am using for Oracle. This sql statements are used by a programm from me. I want to support Oracle and SQL-Server with my program without having different sql statements for Oracle and SQL-Server. Which alternative can i use for the specific Oracle SQL-Statements: * to\_char(FIELDNA...
Even if at a first glance the SQL implementation from two different vendors looks similar, when working with real life enterprise applications you will stumble upon a large number of differences, and I am only talking about SQL, when comparing PL/SQL with T-SQL there is hardly any resemblance left. When trying to redu...
Finally i found a solution. Maybe its useful some other people too. You can set the input format for a date... Oracle: `ALTER SESSION SET NLS_DATE_FORMAT = 'DD.MM.YYYY'` SQL-Server: `SET DATEFORMAT dmy`
SQL: to_char alternative for Oracle AND SQL-Server
[ "", "sql", "sql-server", "oracle", "to-char", "" ]
Hi I have problems trying to reach the value of 3 because my query does not recognize the selection of two countries using the clause 'IN' a) This is my simple table source: **id | country** 1 | CL 2 | BR b) this is my sql query: ``` SELECT ( CASE WHEN country ='CL' THEN 1 WHEN country = 'BR' THEN 2 ...
It seems you want something like the following: ``` SELECT CASE WHEN cntAll = 2 THEN 3 WHEN cntCL >= 1 THEN 1 WHEN cntBR >= 1 THEN 2 ELSE 0 END AS result FROM ( SELECT COUNT(DISTINCT country) AS cntAll, COUNT(CASE WHEN country = 'CL' THEN 1 END) AS ...
The [CASE ... END expression](https://dev.mysql.com/doc/refman/5.6/en/control-flow-functions.html#operator_case) uses shortcut evaluation: > ``` > CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END > > CASE WHEN [condition] THEN result [WHEN [condition] THEN result ......
I try to use IN in mysql 'CASE WHEN' condition
[ "", "mysql", "sql", "case", "conditional-statements", "" ]
I'm not particularly familiar with Ruby on Rails, but I'm troubleshooting an issue we're experiencing with a rake job that is supposed to be cleaning database tables. The tables grow very large very quickly, and the query generated by ActiveRecord doesn't seem to be efficient enough to handle it. The Ruby calls looks ...
From the [fine manual](http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_all): > **delete\_all(conditions = nil)** > > Deletes the records matching `conditions` without instantiating the records first, and hence not calling the `destroy` method nor invoking callbacks. This is a single SQL D...
Another option is to use raw Arel syntax, similar to a simplified version of what [ActiveRecord::Relation#delete\_all](https://github.com/rails/rails/blob/f4538aa5865da5f16b707d34aa733a5e2353f2fd/activerecord/lib/active_record/relation.rb#L577) does. ``` relation = Model.where(...) arel = relation.arel stmt = Arel::De...
Raills: Get SQL generated by delete_all
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "rails-activerecord", "" ]
I need a oracle query which returns every minute between given two timestamps. I referred [this](https://stackoverflow.com/questions/22680617/oracle-query-with-every-minute-a-day) Stack Overflow question. Can we improve the same query?
To get all the minutes between two datetime elements using [**Row Generator**](http://lalitkumarb.com/2015/04/15/generate-date-month-name-week-number-day-number-between-two-dates-in-oracle-sql/) technique, you need to convert the difference between the dates into the **number of minutes**. Rest remains same in the **CO...
You can create like this if you want all minutes from sysdate to 15 NOV: ``` SELECT to_char(TRUNC(sysdate) + numtodsinterval(level - 1, 'minute'), 'dd.mm.yyyy hh24:mi') min FROM dual CONNECT BY LEVEL <= (trunc((TO_DATE('16-NOV-2015','dd-mon-yyyy')) - sysdate) * 24 * 60); ```
Oracle query to fetch every minute between two timestamps
[ "", "sql", "oracle", "date-arithmetic", "" ]
In R, I have a data frame called **df** such as the following: **A**      **B**      **C**      **D** a1    b1    c1     2.5 a2    b2    c2     3.5 a3    b3    c3     5 - 7 a4    b4    c4     2.5 I want to split the value of the third row and **D** column by the dash and create another row for the second ...
One option would be to use `sub` to paste 'min' and 'max in the 'D" column where `-` is found, and then use `cSplit` to split the 'D' column. ``` library(splitstackshape) df1$D <- sub('(\\d+) - (\\d+)', '\\1,min - \\2,max', df1$D) res <- cSplit(cSplit(df1, 'D', ' - ', 'long'), 'D', ',')[is.na(D_2), D_2 := ''] setnames...
Here's a dplyrish way: ``` DF %>% group_by(A,B,C) %>% do(data.frame(D = as.numeric(strsplit(as.character(.$D), " - ")[[1]]))) %>% mutate(E = if (n()==2) c("min","max") else "") A B C D E (fctr) (fctr) (fctr) (dbl) (chr) 1 a1 b1 c1 2.5 2 a2 b2 c2 3...
Split value from a data.frame and create additional row to store its component
[ "", "sql", "r", "dataframe", "dplyr", "" ]
Suppose I have this table: named = **the\_table** whose structure is: postgreSQL: ``` create table the_table (col3 SERIAL, col2 varchar, col1 varchar, PRIMARY KEY(col3)); ``` MySQL: ``` create table the_table ( col3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, col2 varchar(20), col1 varchar(20) ) ``` Then I inserted ...
You need to use [AGGREGATE FUNCTION](http://www.postgresql.org/docs/current/static/functions-aggregate.html): > Aggregate functions compute a single result from a set of input > values. ``` SELECT col2, MIN(col3) AS col3, MIN(col1) AS col1 FROM the_table GROUP BY col2; ``` **[db<>fiddle demo](https://dbfiddle.uk/?r...
Alternatively on the MySQL answer: It wouldn't work in 5.7 version onwards. You can use `ANY_VALUE()` function as stated in MySQL documentation. Sources: <https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_any-value> Example: ``` SELECT MIN(col1), col2, ANY_VALUE(col3) FROM the_table GROU...
Group by clause in mySQL and postgreSQL, why the error in postgreSQL?
[ "", "mysql", "sql", "postgresql", "group-by", "" ]
I am dealing with an issue that I have to backtrack as the entire project is already in production and system has been used for a while. I need to backtrack all the data with the following parametars. `Select * from table where bundle = 5 and count(bundle) >= 3` This will be a joined table so technically I need coun...
If I understand correctly, you want to find transactions where there are more than 3 with that transaction code for a bundle of 5 and with online = 1, and then bring back all the rows from the 2 tables for that transaction with a bundle of 5 and with online = 1 If so, a sub query to get the transactions with a count o...
I'm a little confused by the wording of your question, but try this: ``` SELECT ti.id, ti.transaction, count(ti.bundle) FROM table_i as ti JOIN table_r as tr ON tr.id = ti.id WHERE ti.type_id = x AND ti.bundle = 5 AND ti.online = 1 AND count(ti.bundle) >=5 ```
MySQL count rows where column value is same and select them where count is greater than 2
[ "", "mysql", "sql", "" ]
Explaining by example: ``` UPDATE Table SET value=(22,55,99) WHERE id IN (2,5,9) ``` So the row with `id=2`, `value` is set to `22`. And the row with `id=5`, `value` is set to `55`. Etc.
You can use derived table: ``` update t set value = a.value from Table as t inner join (values (22, 2), (55, 5), (99, 9) ) as a(id, value) on a.id = t.id ``` For me this is the most elegant way to do this and it's also easily extandable (you can add more columns if you like)
Yes, but not like you have: ``` UPDATE Table SET value=case when id=2 then 22 when id=5 then 55 when id=9 then 99 end WHERE id in (2,5,9) ``` If you have to do this for a large number of fields/records, you'd be better off just issuing a bunch of dedicated `update` queries.
Is it possible to update rows from a key/value pair?
[ "", "sql", "sql-server", "" ]
As shown in the figure, I have four tables. Only `TableB` and `TableBChild` have a foreign key relationship. What I want to achieve here is to determine whether `TableBChild.MemberID` matches `TableA.memberNo` where `TableB.isgood` is true If not batch update `isvalid` to false where condition is not satisfy. But I ...
Try to use `NOT IN` instead of `!=` like this: ``` Update TableB Set IsValid = 0 From TableA as A INNER JOIN TableB as B ON A.TableBNo = B.TableBNo And IsGood = 1 INNER JOIN TableBChild as BC ON B.TableBID = BC.TableBID AND BC.MEMBERID NOT IN ( SELECT Membe...
What I would do: ``` UPDATE TableB SET IsValid = 0 WHERE TableBID NOT IN ( -- this will select TableBID's satisfying: -- TableB.IsGood is true, -- and corresponding TableBChild has memberID that exists in TableA.MemberNo SELECT tbc.TableBID FROM TableBChild tbc INNER JOIN TableB tb ON tb.TableBID = tbc.TableBID INNE...
SQL update based on value from other table
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
iReport does not seem to accept the normal SQL SUM function and I am having a hard time figuring out a way around this. I am trying to use `SUM(qtytofulfill.SOITEM - qtyfulfilled.SOITEM) AS qty` and it does not seem to like that or me simply adding the variables and saying `SUM(qtytofulfill - qtyfulfilled) AS qty`. T...
This will work fine, > In standard SQL (but not MySQL), when you use GROUP BY, you must list > all the result columns that are not aggregates in the GROUP BY clause. ``` SELECT SOITEM.'QTYFULFILLED' AS QTYFULFILLED, SOITEM.`QTYTOFULFILL` AS QTYTOFULFILL, SOITEM.`SOID` AS SOITEM_SOID, ...
I believe it's treating the 2 column names inside sum as variables, not table columns
iReport not accepting SQL SUM function
[ "", "mysql", "sql", "jasper-reports", "ireport", "" ]
I have two tables **Table\_1:** ``` ╔══════╦══════════╦═════════╗ ║ Name ║ Date ║ Revenue ║ ╠══════╬══════════╬═════════╣ ║ A ║ 1/1/2001 ║ 20 ║ ║ A ║ 1/2/2001 ║ 20 ║ ║ B ║ 1/1/2001 ║ 40 ║ ╚══════╩══════════╩═════════╝ ``` **Table\_2:** ``` ╔══════╦══════╗ ║ Name ║ Task ║ ╠══════╬══════╣ ...
Use this query: ``` SELECT Name, SUM(Revenue) FROM Table_1 GROUP BY Name ``` I don't see any point in joining `Table_1` to `Table_2` since you are not making use of the `Task` column.
The root of your problem is that the join is not doing what you expect it to do. By doing the join between the two tables on the 'name', you are creating duplicates. Remove the group by clause in your query and you will see exactly what I mean. As mentioned in a previous answer, the join (in this case) is superfluous....
SQL Query Summing In Join
[ "", "sql", "" ]
I have table called `DataFile`. This keeps all my data records that get stored in a daily bases. Data in this table looks like the below: ``` Id ConfigAccountId Shelf FileIdentifier Created 5356341 23 BSAS020006 C200094 28/01/2013 5356342 23 BSAS020006 C200095 2...
If I understand your problem correctly, I think a combination of distinct and min before counting will work for you: ``` SELECT COUNT(Shelf) AS UniqueCodesForShelf, FirstMonthForShelf AS Month FROM ( SELECT Shelf, MIN(AllMonthsForShelf) AS FirstMonthForShelf FROM ( SELECT DISTINCT Shelf...
Try this, ``` Declare @To Datetime='2013-02-28 23:59:59' DECLARE @t TABLE ( Id INT ,ConfigAccountId INT ,Shelf VARCHAR(20) ,FileIdentifier VARCHAR(20) ,Created DATETIME ) INSERT INTO @t VALUES (5356341, 23,'BSAS020006','C200094','01/28/2013') ,(5356342, 23,'BSAS020006','C200095','01/28/2013')...
Find Distinct Records over a period of a month
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Where I am working I have been recently told that using distinct in your queries is a bad sign of a programmer. So I am wondering I guess the only way to not use this function is to use a **group by** . It was my understanding that the distinct function works very similarly to a group by except in how its read. A dist...
Databases are smart to recognize what you mean. I expect both of your queries to perform equally well. It is important for someone else maintaining your query to know what you meant. If you really meant to retrieve distinct records, use `DISTINCT`. If your intention was to do aggregation, use `GROUP BY` Take a look at...
The answer provided by @zedfoxus is useful to understand the context. However, I don't believe your query should require distinct records if the data is designed correctly. It appears you are selecting the primary key of table `spriden`, so all that data *should* be unique. You're also joining onto the `spraddr` tabl...
Should I use distinct in my queries
[ "", "sql", "oracle", "distinct", "" ]
I have a table and I want to check the datetime format of records according to `YYYYMMDD,HH24MISS`. If the datetime format of my records is incorrect, write an error message. How can I make a function or procedure in PL/SQL?
You can write a function like this: ``` CREATE OR REPLACE FUNCTION CheckDateString(str IN VARCHAR2) RETURN DATE IS BEGIN RETURN TO_DATE(str,'YYYYMMDD,HH24MISS'); EXCEPTION WHEN OTHERS THEN RETURN NULL; END CheckDateString; ``` and use it like this ``` SELECT * FROM my_table WHERE CheckDateString(DAT...
In case your column is VARCHAR2 and you need to check that the values inside it can be transformed to date using your desired format, this could be a solution: ``` declare v_foo_date date; begin for r_date in ( select date_col from my_table ) loop begin v_foo_date := to_date(r_date.date_col, '...
How can I check the format of my date?
[ "", "sql", "oracle", "date", "plsql", "" ]
I have data on locations that include a Location ID and a set of 3 0 or 1 flags that indicate whether or not the latitude, longitude, or address of a location has changed as well as the month end in which the change occurred. So I am looking at something like this: ``` +------------+-------------+--------------+-----...
You could do something like this. Note although it's an "evil" cursor. I personally feel when you're performing complex business logic, it keeps things clear. ``` DECLARE @LOCATIONID INT DECLARE @XCOORDHANGE INT DECLARE @YCOORDCHANGE INT DECLARE @ADDRESSCHANGE INT DECLARE @REPORTPERIOD DATETIME CREATE TABLE #Temp1 (...
Since you are only concerned if (x or y) and address is not 0 for a period, I used `SUM` on them in the inner query ``` SELECT LocationID ,SUM(Xcoord) AS x ,SUM(Ycoord) AS y ,SUM(Address) AS a FROM myTable WHERE Period BETWEEN '2010-01-01' AND '2010-12-31' GROUP BY LocationID ``` Then included a...
How do I identify records that have certain flags equal to 1 within a year of each other?
[ "", "sql", "sql-server", "" ]
I have a table: `Employee` ``` columns: 1. id 2. name 3. city1 4. city2 ``` I want to `GROUP BY` the combination of `city1` and `city2` so that e.g. * an employee with city1: `'Bangalore'` and city2: `'Chennai'` * and another employee with city1: `'Chennai'` and city2: `'Bangalore'` comes in a single group when don...
The easiest way is to use `least()` and `greatest()`: ``` select least(city1, city2) as city1, greatest(city1, city2) as city2, count(*) from employees group by least(city1, city2), greatest(city1, city2); ``` The logic is slightly more complex if you have `NULL` values. The question says nothing about `NULL` values....
You can build a ordered key with your city and group it, using a `CASE WHEN`; ``` SELECT CityKey, Id, Name, count(CityKey) FROM (SELECT CASE WHEN City1 > City2 THEN Concat(City1,City2) WHEN City1 <= City2 THEN Concat(City2,City1) END AS CityKey, Sample.City1, Sample.City2, Id,...
mysql group by on unique combination of 2 columns
[ "", "mysql", "sql", "group-by", "" ]
I want to do a special request on my database (PostgreSQL v9.4.5), but I don't manage to do it. In order to simply, let's say I have the following table **AvgTemperatures**, representing different averages of temperature taken in different cities, and calculated on different length of time (counted in months) : ``` ...
**[All-at-once operation:](http://social.technet.microsoft.com/wiki/contents/articles/20724.all-at-once-operations-in-t-sql.aspx#All-at-Once)** > "All-at-Once Operations" means that all expressions in the same > logical query process phase are evaluated logically at the same time. And great chapter **Impact on Window...
The simplest solution is to use the [`bool_or` aggregate function](http://www.postgresql.org/docs/current/static/functions-aggregate.html) ``` select id, city, avg, months from avttemperatures where city in ( select city from avttemperatures group by 1 having bool_or(avg > 19) ) order by 2, 4 ; id | ...
SQL Condition on Window function
[ "", "sql", "postgresql", "window-functions", "" ]
I have a query where I want to display the owner and the number of times they took the car, bus or train to work. so the table should look like this; ``` Owner | Car | Bus | Train ------------------------- Joe | 1 | 2 | 4 ``` This is my query; ``` Select owner, vehicle From MyTable INNER JOIN(select co...
First, use `sum()` rather than `count()`. Second, you don't need a subquery. Third, you need to group by `owner`, not `vehicle`: ``` Select owner, sum(case when vehicle = 'Car' then 1 else 0 end) AS [Car], sum(case when vehicle = 'Bus' then 1 else 0 end) AS [Bus], sum(case when vehicle = 'Train' t...
Try this: ``` select owner ,count(case when vehicle = 'Car' then 1 end) as [Car] ,count(case when vehicle = 'Bus' then 1 end) as [Bus] ,count(case when vehicle = 'Train' then 1 end) as [Train] from dbo.MyTable where year([CreatedOn]) = 2015 group by owner ```
Sql - Count table query error
[ "", "sql", "sql-server", "" ]
I would like to know if it's possible to create a not null constraint for either column `name` OR column `surname`. ex : ``` create table football_players ( id VARCHAR(36) PRIMARY KEY, name VARCHAR(20), surname VARCHAR(20) ); ``` Sometimes we know the name or the surname but not both. I don't want a playe...
The standard SQL method would be: ``` create table football_players ( id VARCHAR(36) PRIMARY KEY, name VARCHAR(20), surname VARCHAR(20), constraint chk_name_surname check (name is not null or surname is not null) ); ``` This does not work in MySQL (the question was not originally tagged MySQL). Doing ...
MySQL doesn't support check constraints, but you can do something similar [with a trigger](https://stackoverflow.com/q/9734920/4794).
How define column a OR column b NOT NULL?
[ "", "mysql", "sql", "check-constraints", "" ]
I want to check whether all the tables in my Database has clusterd index on which type of column(eg:int) and whether the clustered index is on a single/multipe columns. I was not able to figure out which DMvs or Views to retreive this information. Please help.
below sql will give you list of the clusterd indexes and table name with few more detail. you can modified this to get to you results. ``` SELECT 'ClusteredIndexName' = SI.Name, 'TableName' = SO.Name, 'ColumCount' = IK.IndexColumnCount, 'IsUnique' = CASE WHEN SI.is_unique = 0 THEN 'N' ELSE 'Y' E...
SELECT \* FROM sys.indexes (I think, its been a while since I used SQL Server).
DMVs to get index configuration information
[ "", "sql", "sql-server", "indexing", "" ]
I have a table like this: ``` Employee | id | name | department | | 01 | Joe | Network | | 02 | Sam | Quality | | 03 | Mark | Network | | 04 | Pete | Quality | ``` And other table like this: ``` Hours | id | date | hours | | 01 | 1/1/11 | 7 | | 02 | 1/2/11 | 15 | | 03 | 1/5/11 | 13 | | ...
``` select id, name, department, total from ( SELECT e.id, e.name, e.department, t.total, rank() over(partition by e.department order by t.total desc) as rnk FROM ( SELECT id, SUM(hours) AS total FROM hours GROUP BY id ) t JOIN employee e ON e.id = t.id ) t where rnk = 1 order by total desc ```
This will show more than 1 row for a department if there is a tie. Probably what you do want. ``` SELECT EachEmp.name, EachEmp.department, MAXES.maxTotal AS total FROM (SELECT e.name, -- sum up each employees totals e.department, SUM(h.hours) AS total FROM employ...
SQL want to avoid repeated rows
[ "", "sql", "database", "postgresql", "" ]
I am trying to make two columns auto increment but this column shows an error `[user_id] as id + 0 PRIMARY KEY NOT NULL` saying > Only UNIQUE or PRIMARY KEY constraints can be created on computed columns What I am trying to do is, if id = 1, make user\_id= 1 as well. ``` CREATE TABLE [dbo.TBL_TXN_USER] ( [id] ...
the error message is because you put the `NOT NULL` constraint on the computed column. on sql server 2012 the complete error message is: > Only UNIQUE or PRIMARY KEY constraints can be created on computed > columns, while CHECK, FOREIGN KEY, and NOT NULL constraints require > that computed columns be persisted. her...
Sorry for my misunderstanding, So you want to add auto increments two column in one table. Actually that is not accept at SQL-server so I am going to give you another option below ``` CREATE TRIGGER [dbo].[insert_triger] ON [dbo].[TBL_TXN_USER] FOR INSERT AS update TBL_TXN_USER set [user_id] = id where id = ( select...
Can one table have two identity columns in SQL Server?
[ "", "sql", "sql-server", "" ]
I’ve recently moved companies and they do something in SQL Server that I have not seen before. I am used to using a primary key column as an int that increments on inserts, very occasionally I've seen the use of guids but here they use both, see below. ``` PrimaryID | GUID | RestOfColumns ``` I can't get my head roun...
If somebody looks at your website's html source, they might see that they are submitting a form and passing their ID which is "1003". So from there, they could construct a form that passes the ID of "1002" and see somebody else's data. It's not exactly "SQL Injection", it's more like parameter-guessing. But if they se...
The main benefit would be: We already have a bunch of code that uses PrimaryID, including ORM code that maps PrimaryID as the primary key column. The only other reason I can see to keep PrimaryID is for human readability. Also, I should let you know that GUID doesn't always protect you from data scraping. You could ve...
SQL Server Int primary key and Guid
[ "", "sql", ".net", "sql-server", "" ]
I am trying to create a table for suppliers group and when I try to create it it throws an error. Here's the code : ``` CREATE TABLE GROUPS_PLUS_SUPPLIERS ( PRODUCT_GROUP_SUPPLIER_ID NUMBER(3), GROUP_ID NUMBER(4), GROUP_NAME VARCHAR2(255), SUPPLIER_ID NUMBER(4), CONSTRAINT PRODUCT_GR...
Since your `GROUP_ID` column is not unique, and foreign key constraints cannot be made to non-unique values (which single row does it relate to?), and given that your `GROUPS_PLUS_SUPPLIERS` table also uses `SUPPLIER_ID`, then you have to have a composite foreign key: ``` CREATE TABLE GROUPS_PLUS_SUPPLIERS ( PRODU...
The error message says what you are missing. The foreign key to `GROUPS_PLUS_SUPPLIERS(GROUP_ID)` means you need to add a unique index on this column. ``` CREATE TABLE GROUPS_PLUS_SUPPLIERS ( PRODUCT_GROUP_SUPPLIER_ID NUMBER(3), GROUP_ID NUMBER(4), GROUP_NAME VARCHAR2(255), SUPPLIER_ID NUMBER(...
SQL Primary key struggle
[ "", "sql", "oracle", "" ]
this is my first question in this site, I want to know, if I have a table like this one in SQL * Value * a * a * a * a * a * b * b * b * c * c * a * a * b * b How can I generate a list of sequential numbers or ID's in a query in such a way that it will change according to the value column, this is what I want: * Val...
You can do this with a series of queries. 1. Start with a table containing an auto increment field and a text field, nothing else. Put no records in it. 2. Write an aggregate query against your table that groups by your value field. 3. Write an append query that appends record from the query in step 2 into the table fr...
Gordon Linoff is correct regarding no ordering, so it is not possible to do exactly what you ask for But if you have an additional column to sort in SQL Server you can use DENSE\_RANK to assign numbers: ``` --create table Test(col varchar(100)) --insert into Test values('a'),('a'),('a'),('b'),('b'),('c'),('d') select...
Same index/ID based on another column value
[ "", "sql", "sql-server", "ms-access", "" ]
I've got this table `supp_props`: ``` supp_id | supp_dry_weight | supp_price | supp_date --------+-----------------+------------+------------ 22 | 88.00 | 27.50 | 2015-06-25 x delete 22 | 89.00 | 28.00 | 2015-10-18 < don't delete, while 22 | 89.00 | 29....
Thanks to all the great help and examples from Alex, Mike Brent and xQbert I've managed to create this query: ``` DELETE sp FROM supp_props sp LEFT JOIN ( SELECT supp_id, MAX( supp_date ) AS max_date FROM supp_props WHERE supp_date < NOW() GROUP BY supp_id ) max ON sp.supp_id = max.supp_id WHERE sp.supp_d...
This should do the trick: ``` DELETE sp FROM supp_props AS sp LEFT JOIN ( SELECT supp_id, MAX(supp_date) AS max_date FROM supp_props WHERE supp_date <= DATE(NOW()) ) AS max ON sp.supp_id = max.supp_id AND sp.supp_date = max.max_date WHERE max.supp_id IS NULL AND sp.supp_date < DATE_SUB(NOW(), INTER...
Delete all rows but the latest date
[ "", "mysql", "sql", "sql-delete", "" ]
I am using Oracle sql developer.And I have to categorize some data into each `Date` from a table. I used `TO_CHAR` function to change the date format. ``` select to_char(txn_date, 'dd-mon-rrrr') my_day, some_coloums from mwt_wallet_transactions order by my_day; ``` It's ok with upper one. But I want to get it with ...
> where my\_day like '08-feb-2015' I think you got confused between **SELECTION** and **FILTER PREDICATE**. Also, remember, `''08-feb-2015'` is NOT a **DATE**, it is a **string**. You want to filter the rows based on a DATE value. So, convert the literal on the R.H.S. into **DATE** using `TO_DATE` or use **ANSI Date...
You can't use select list column aliases in the `WHERE` clause. Use derived table to access it: ``` select * from ( select *some_computed_value* as my_day, some_colomns from mwt_wallet_transaction ) where *my_day conditions* order by my_day ```
How to categorize data for each date in sql?
[ "", "sql", "database", "oracle", "date", "date-arithmetic", "" ]
I have a table where I want to filter all rows that have a Code,Life and TC equal to the results of a select query on the same table filtered by ID ``` ID Code|Life|TC|PORT 62 XX101 1 1 1 63 XX101 1 1 2 64 AB123 1 1 1 65 AB123 1 1 2 66 AB123 1 1 3 67 CD321 1 1 1 68 CD321 1...
Here is the query you need: ``` select t2.* from #table t1 join #table t2 on t1.Code = t2.Code and t1.Life = t2.Life and t1.TC = t2.TC and t1.PORT = t2.PORT where t1.id = @Port1 ``` With `cross apply`: ``` select ca.* from #table t1 cross apply (select * fro...
You could use an EXIST statement for this scenario ``` SELECT ID FROM #table t1 WHERE EXISTS ( SELECT * FROM #table t2 WHERE t2.ID = @Port1 AND t2.Code = t1.Code AND t2.Life = t1.Life A...
SQL: Select rows in a table by filtering multiple columns from the same table by a 3 column select result
[ "", "sql", "sql-server", "" ]
Suppose I have table 1 and table 2 with same column. I want to combine them and sort in order by column3 and column4, as well as preserved the table column order. How could it be done? I got the following error: > ORDER BY items must appear in the select list if the statement > contains a UNION, INTERSECT or EXCEPT o...
Using sub query Example : ``` SELECT * FROM ( SELECT COLUMN1, COLUMN2, COLUMN3, COLUMN4 FROM TABLE1 UNION SELECT COLUMN1, COLUMN2, COLUMN3, COLUMN4 FROM TABLE2 ) ResultTABLE ORDER BY ResultTABLE.COLUMN2, ResultTABLE.COLUMN3 ``` This method can help you avoid ambiguous column and order your whole results.
When you use UNION or UNION ALL result set get the column names from the first query by default. So make sure at the end of the query when you write ORDER BY you give the names from the first query(in your case table1). I guess in your case table1 and table2 don't have same column. So you need to write query1 (table1) ...
Sorting in sql union
[ "", "sql", "sql-server", "select", "sql-order-by", "union", "" ]
I would like to know how to solve this problem, I have these two tables: ``` TABLE FRIENDSHIP Name | Friend -------------- John | Mark Peter | Paul Simon | Mary TABLE SCHOOL Name | School -------------- John | SchoolA Mark | SchoolA Peter | SchoolB Paul | SchoolC Simon | SchoolC Mary | SchoolD ``` How do I select th...
You can try joining the `SCHOOL` table to the `FRIENDSHIP` twice, once for each friend in the pair. Then you can restrict your result set by retaining only friend pairs whose respective schools are *not* the same. ``` SELECT f.Name, f.Friend FROM FRIENDSHIP f INNER JOIN SCHOOL s1 ON f.Name = s1.Name INNER JOIN SCHOOL ...
There are 2 type of people on your example. Let's call the first one as `Name` and the second one as `Friend`. Both `Name` and `Friend` has `School`. We need to compare that their `School` is different, so we need to get their `School` first. Let's get `School` for `Name` by joining `Friend.Name` to `School.Name` ...
SQL Query Common Value after count
[ "", "mysql", "sql", "database", "" ]
I am working on cleaning up a customer list from an ecommerce site. The customer list has a many to many relationship between customer ID and customer email. For example, a customer could place an order with the same email while logged in or anonymous, and the result would be two customer records with the same email bu...
OLDTABLE - is your table NEWTABLE - will have result [![enter image description here](https://i.stack.imgur.com/EUwon.jpg)](https://i.stack.imgur.com/EUwon.jpg) ``` CREATE TABLE #NEWTABLE ( NEW_CUST_KEY int not null , CUST_ID int not null, CUST_EMAIL nvarchar(100) null ) ------------------------------...
I think you could use row\_number..... Something like this...... ``` SELECT DISTINCT CUST_ID, CUST_EMAIL ROW_NUMBER() OVER(PARTITION BY CUST_ID, CUST_EMAIL) AS New_Cust_Key FROM YOUR TABLES ```
SQL Server: Generate unique customer key based on two columns
[ "", "sql", "sql-server", "" ]
I have two tables: `@CATS` and `@NEWCATS` ``` declare @CATS table (_Group int, _Name nvarchar(50)) declare @NEWCATS table (_Name nvarchar(50)) insert into @CATS (_Group, _Name) values (1, 'Siamese'), (1, 'Japanese'), (2, 'Siamese'), (2, 'Japanese'), (2, 'Russian') insert into @NEWCATS (_Name) values ('Siamese'), ('Ja...
This is one way to do it: ``` select CATS._Group from CATS left join NEWCATS on NEWCATS._Name = CATS._Name group by CATS._Group having sum(case when NEWCATS._Name is null then 1 else 0 end) = 0 ``` If they were real tables and there were indexes, other ways using different access plans could produce faster resul...
You can use `EXCEPT`: ``` SELECT DISTINCT _group FROM @CATS EXCEPT SELECT c._group FROM @CATS c LEFT JOIN @NEWCATS nc ON nc._Name = c._Name WHERE nc._Name IS NULL; ``` `LiveDemo` **EDIT:** ``` WITH cte AS ( SELECT * FROM (SELECT DISTINCT _Group FROM @CATS) AS c CROSS JOIN @NEWCATS nc ) SELECT DISTINCT _gro...
Get parent ID from two tables
[ "", "sql", "sql-server", "" ]
I'm working with a table in MySql that has an int indexed column called "serial". This table has around 2 million rows. If I apply a select statement with this column in this way: ``` SELECT serial FROM Table WHERE Serial=12345 ``` this returns the data in around < 1 sec. However, if I use a SELECT \* query in thi...
There is part answer for your question. <https://stackoverflow.com/a/3211164/2957840> But also, maybe you should consider partitioning your table: <https://dev.mysql.com/doc/refman/5.7/en/partitioning.html>
It is rather unlikely that the columns are causing the problem. This could happen if one (or more) of the columns are really, really large objects. To get to 78 seconds, you need to be thinking in terms of many megabytes or gigabytes, although even 1 Gbyte might not take that long in many environments. The use of the ...
MySql, SELECT * FROM with Indexed columns
[ "", "mysql", "sql", "database", "performance", "indexing", "" ]
Here is the SQL Puzzle to challenge you: Write a query that would select top 5 records in three different categories. Something like this: ``` select top 5 name, age from table1 where category = 22 order by age desc union all select top 5 name, age from table1 where category = 27 order by age desc union all select t...
Classic `top-n-per-group`, isn't it? Using SQL Server syntax. `ROW_NUMBER()` should be in all decent databases in 2015. ``` WITH CTE AS ( select name ,age ,ROW_NUMBER() OVER (PARTITION BY category ORDER BY age desc) AS rn from table1 where category IN (22, 27, 53) ) SELECT nam...
If you truly want top 5 then you'll probably need a tie-breaker. Is `name` unique per `age`? ``` select t.name, t.age from T t where t.category in (22, 27, 53) and 5 >= ( select count(*) from T t2 where t2.category = t.category and (t2.age >= t.age or t2.age = t.age and t2.name >= t.name) ) ```
SQL Puzzle - UNION ALL without UNION ALL
[ "", "sql", "intersystems-cache", "" ]
I have implemented multiple conditions in case statement as below, ``` select officied from budgettable where budgetid = case @budgetid when 7 then 7 when 7 then 8 when 7 then 10 when 8 then 6 end ``` but it didn't give me any result. If I pass budget-Id as `...
I suspect that you want something like this: ``` where budgetid = @budgetid or (@budgetid = 7 and budgetid in (7, 8, 10)) or (@budgetid = 8 and budgetid = 6) ``` Your query is failing because for all values of `@budgetid` other than 7 or 8, the `case` returns `NULL` -- which is treated as false.
This is no answer. I just want to show how CASE WHEN works, so you see your mistake. Your query evaluates `case @budgetid`as follows: 1. when 7 then 7 => take a 7 for a @budgetid 7 2. when 7 then 8 => ignored, because we already said to take 7 for a @budgetid 7 3. when 7 then 10 => ignored, because we already said to ...
Use Multiple conditions in Case Statement
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table like this: ``` id | col1 | col2 | col3 | ------------------------- 1 | ab | ab | | 2 | bc | ab | cd | 3 | bc | cd | cd | ``` And i want to produce the count of each of the names in each column like this: ``` name | col1 | col2 | col3 | ------------------------- ab | 1 | 2...
``` select name, sum(cnt1), sum(cnt2), sum(cnt3) from ( select col1 as name, count(*) as cnt1 , null as cnt2 , null as cnt3 from t group by col1 union all select col2, null, count(*), null from t group by col2 union all select col3, null, null, count(*) from t group by col3 ) as dt ```
perhaps this would work ``` select colcounts.col, sum(colcounts.cnt) from ( (select col1 as col, count(*) as cnt from TableLikeThis group by col1) union (select col2 as col, count(*) as cnt from TableLikeThis group by col2) union (select col3 as col, count(*) as cnt from TableLikeThis group by col3) ) ...
Count of ID in Each Column by ID
[ "", "mysql", "sql", "database", "union", "aggregate", "" ]
Having issues getting rid of this error. I'm trying to use Digital Ocean to deploy my Django app. I configured Postgres, but when I'm trying to register a new user in my app, I get this problem. I've tried running `python manage.py makemigrations` and `python manage.py migrate` and they work fine. The SQL migrations ...
Try add this to your imports: ``` from django.utils import timezone ``` Then wherever you grab the `user`'s data to `save` the new `user` add before the `save` procedure: ``` <user_object>.last_login = timezone.now() ```
I was upgrading from django 1.7 to django 1.10 when I ran into this. What it ended up being was I needed to run `python manage.py migrate` to update the database tables and columns.
null value in column "last_login" violates not-null constraint
[ "", "sql", "django", "postgresql", "null", "" ]
***UPDATED :*** I am try to achieve this, ``` TBL1 PK AK TOT1 1 1 100 2 2 200 3 3 300 TBL2 PK AK TOT2 1 1 50 2 1 50 3 2 150 ``` First of, I aggregate the TBL2 which is, all of the TBL2.AK(1) is summed. Then use JOIN to display them. Th...
The query is performing an inner join; it's returning only rows that have matching values. You are correct, to also get rows from one table that do *not* have a matching row in the other table, you would need an "outer" join. To get the result you describe: 1) add the keyword `FULL` before the `JOIN` keyword, and 2...
I'm not sure what would you want to display because you sum data in only a table but I suggest like this. For query all of record in both table. Just like this. ``` SELECT * -- Display as you want FROM TBL1 t1 FULL OUTER JOIN TBL2 t2 ON t1.AK = t2.AK ``` If you need to merge data of AK in both table as a column. yo...
SQL After aggregation and join. Display the Not Equal value and The NULLs
[ "", "sql", "oracle", "join", "aggregate", "" ]
I need to Search a String in multiple Column With OR Condition & also want to split String by SPACE. Ex. If User Search 'Software Developer' then a simple Query will be like ``` Select * from TableName Where Col1 LIKE '%Software%' OR Col2 LIKE '%Software%' OR Col3 LIKE '%Software%' OR Col1 LIKE '%Developer%' OR Col2 L...
Do you thin you can use the query like > Select \* from Table where ( col1 + col2 + col3 like '%Software%') OR (col1 + col2 + col3 like '%Engineer%')
``` SELECT dbo.JD_tblJob.EmployerID, dbo.JD_tblJob.PostDate, dbo.JD_tblJob.JobID, dbo.JD_tblJob.JobTitle, dbo.JD_tblJob.JobDescr, dbo.JD_tblJob.MinWorkExp, dbo.JD_tblJob.MaxWorkExp, dbo.JD_tblJob.MinSalary, dbo.JD_tblJob.MaxSalary, dbo.JD_tblJob.HideSalary, dbo.JD_tblJob.NoOfVacancies, ...
Procedure to Search String with split
[ "", "sql", "sql-server", "string", "stored-procedures", "split", "" ]
First I want you to show my tables: Table Users ``` CREATE TABLE Users( EMAIL VARCHAR(40) NOT NULL); ``` Table Actions ``` CREATE TABLE Actions IDACCION INT NOT NULL, ACCION VARCHAR(100) NOT NULL); ``` Table UserAction ``` CREATE TABLE UserAction( EMAIL VARCHAR(40) NOT NULL, IDACCION INT NOT NU...
You really need to structure your tables, your Users table does not have a Primary key and don't seem to have any purpose on an application, for this query doesn't even need Users table. ``` SELECT a.ACCION, ua.DATETIME FROM Actions a INNER JOIN UserAction ua on a.IDACCION = ua.IDACCION ```
``` select a.accion, ua.datetime from users u, actions a, useraction ua where u.email=ua.email and ua.idaccion=a.idaccion; ```
SQL query from 3 different tables.
[ "", "mysql", "sql", "database", "" ]
I have written a stored procedure, my table contains 2 foreign keys from same table, `DISTRICTS`. Scenario: I am passing a person's job record, which should contain his initial working city and district and then current city and district. Now I want to show district names of both but I am confused in joins because it ...
I think you need to join on the districts table a second time. Join once with the working city and once with the current city. Try this: ``` select ServiceInfo.pk_ServiceInfo_ServiceInfoID, ServiceInfo.fk_Districts_ServiceInfo_CurrentDistrictID, currentdistrict.DistrictName, ServiceInfo.fk_Districts_...
Try the following: ``` select s.pk_ServiceInfo_ServiceInfoID, s.fk_Districts_ServiceInfo_CurrentDistrictID, s.fk_Districts_ServiceInfo_InitialDistrictID, d1.DistrictName as CurrentDistrictName, d2.DistrictName as InitialDistrictName from ServiceInfo si join PersonalInfo p on p.pk_Per...
How to apply inner join in this case?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I'm having hard times with grouping; I'm working on ISTAT (Italian Institute of Statistics) data about my region's population; they give me data for each city and each age (0, 1, 2 and so on) and I need to group ages in class of 10 years (0-9, 10-19, and so on) for EACH city. Example of the first few rows: ``` | ID | ...
E.g.: ``` SELECT CodiceComune , CONCAT(FLOOR((Eta+0.5)/10)*10,'-',(CEILING((Eta+0.5)/10)*10)-1) Age_group , SUM(TotMaschi) m , SUM(TotFemmine) f FROM my_table GROUP BY CodiceComune , FLOOR(Eta/10); ```
This will count the number of males for the 10 year range in MySQL ``` SELECT COUNT(TotMaschi) FROM tablename WHERE CodiceComune = 42001 AND eta IN (0,1,2,3,4,5,6,7,8,9) ```
Group ages by city
[ "", "mysql", "sql", "excel", "group-by", "" ]
All I'm trying to do is verify a query. ``` 'SELECT * from table_that_does_not_exist' ``` Without that erroring out, I'd like to know it failed so I can return a response that states "Error: table does not exist" or the generic error.
The simplest way to catch any `sql` syntax or query errors is to catch an `Illuminate\Database\QueryException` after providing closure to your query: ``` try { $results = \DB::connection("example") ->select(\DB::raw("SELECT * FROM unknown_table")) ->first(); // Closures include ->first(), ->get(), ->pl...
Wrap the lines of code you wish to catch an exception on using try-catch statements ``` try { //write your codes here } catch(Exception $e) { dd($e->getMessage()); } ``` Do not forget to include the Exception class at the top of your controller by saying ``` Use Exception; ```
How do I catch a query exception in laravel to see if it fails?
[ "", "sql", "laravel-5", "" ]
How do I filter column with particular value? This works fine `>` ``` scala> dataframe.filter("postalCode > 900").count() ``` but `==` fails ``` scala> dataframe.filter("postalCode == 900").count() java.lang.RuntimeException: [1.13] failure: identifier expected postalCode == 900 ##Error line ``` I know I am missi...
Expression string you pass to `filter` / `where` should be a valid SQL expression. It means you have to use a single equal operator: ``` dataframe.filter("postalCode = 900") ``` And example ``` val df = sc.parallelize(Seq(("foo", 900), ("bar", 100))).toDF("k", "postalCode") df.where("postalCode = 900").show // +---...
In `python` it may be approached this way (using @zero323 data): ``` df = sqlContext.createDataFrame(sc.parallelize( [("foo", 900), ("bar", 100)]), StructType([ StructField("k", StringType(), True), StructField("v", IntegerType(), True) ]) ) filtered_df = df.where(df.v == 900) filtered_d...
Spark dataframe checking equality and filtering
[ "", "sql", "apache-spark", "apache-spark-sql", "" ]
# Context: I have an update query for a Microsoft Access DB that keeps failing. The query works when executed from within my DB, but fails when executed from my CodeFile for my .aspx page. I have ensured that: * My App\_Data folder has write permissions (via IUSR) * My DB is not 'Read Only' * My query syntax is corr...
Shout-out to @Steve for being such a big help on this. I had several issues here. While I'm sure there are many issues which could produce the error I was experiencing, here's what resolved it for me: * Created a new application pool in IIS and gave this new pool write permissions to my App\_Data folder * Assigned th...
This help page addresses the error you are receiving: <https://support.microsoft.com/en-us/kb/175168> It looks like either youre not opening the connection in the right mode (Mode 3 in this case) or the "table" you are updating has conditions which prevent you from updating it. I'd bet though that changing your Mode ...
Update Query from ASP.NET to .MDB Failing
[ "", "sql", "asp.net", "vb.net", "ms-access", "" ]
I'm looking to get distinct rows with a start and end date from a table with structure below. I dont want duplicate rows with same start and end month. Please note that start and end date are NUMBER type here, not date. ``` tbl_app_ranges: rg_id start_month end_month 105 200401 200409 105 200401...
``` select distinct rgid,start_month,end_month from tbl_app_ranges; ```
You can use `GROUP BY rg_id, start_month, end_month` in your query.
How to select distinct date ranges with Oracle SQL
[ "", "sql", "oracle", "" ]
So I am attempting my very first sub query and ran into a small problem... Why is the query not taking into account my WHERE clause? My query: ``` SELECT * FROM Product WHERE stdUnitPrice < 5* (SELECT MIN(stdUnitPrice) FROM Product WHERE discontinued = 'A') ``` But in the results I am still getting values in the di...
Try this: ``` select * from Product where stdUnitPrice < (5 * (select min(stdUnitPrice) from Product ) ) and discontinued = 'A' ```
So the reasoning for this not working the way you want it to is because you are missing the where clause in your first query. Let me break it down a little for you. ``` select * from Product where stdUnitPrice < 5* (select min(stdUnitPrice) from Product where discontinued = 'A') ``` so in this query the sub query g...
MySQL: Sub-query troubles
[ "", "mysql", "sql", "" ]
The upper limit for any `int` data type (excluding `tinyint`), is always one less than the absolute value of the lower limit. For example, the upper limit for an `int` is 2,147,483,647 and ABS(lower limit) = 2,147,483,648. Is there a reason why there is always one more negative int than positive int? **EDIT: Changed...
The types you provided are signed integers. Let's see one byte(8-bit) example. With 1 byte you have `2^8` combinations which gives you 256 possible numbers to store. Now you want to have the same number of positive and negative numbers (each group should have 128). The point is `0` doesn't have `+0` and `-0`. There i...
This question isn't really related to databases. As lad2025 points out, there are an even number of values. So, by including 0, there would be one more positive or negative value. The question you are asking seems to be: "Why is there one more negative value than positive value?" Basically, the reason is the sign-bit...
Why is there one more negative int than positive int?
[ "", "sql", "binary", "int", "signed", "" ]
Currently I've gotten as far as ``` SELECT DESCRIPTION, LEFT(DESCRIPTION, CASE WHEN CHARINDEX(',', DESCRIPTION) = 0 THEN LEN(DESCRIPTION) ELSE charindex(',', DESCRIPTION) - 1 END) AS LEFTDESCRIPTION, RIGHT(DESCRIPTION, CASE WHEN CHARINDEX...
Since you know how to get the contents `LEFT` of the comma, you can leverage the same manipulation logic on the `REVERSE`'d value to grab what would be to the `RIGHT` of the original string, ``` DECLARE @Var VARCHAR(50) = 'example,this' SELECT @Var , LEFT(@Var, CHARINDEX(',', @Var) - 1) ...
I would be inclined to use `stuff()` for this: ``` select description, left(description, charindex(',', description) - 1) as leftdescription, stuff(description, 1, charindex(',', description), '') as rightdescription ``` If you are concerned about `,` not being there, then use `case`: ``` select desc...
How do I Select characters to the left of a ',' and then characters to the right of a ','?
[ "", "sql", "sql-server-2008-r2", "" ]
I want to create a query for project listings that would give the number of registered applications, excluding the ones for which the user does not exist. In this case, considering user 10 does not exist, I should have the query results as folows: RESULTS ``` +----+------------+--------------+ | id | project ...
Your query looks overly complicated. This should do: ``` select id, name as project, ( select count(*) from applications a where a.project_id = p.id and a.user in (select id from users) ) as applications from projects p; ```
I think you want `left join` and `group by`: ``` select p.id, p.name, count(u.id) from projects p left join applications a on p.id = a.project_id left join users u on a.user_id = u.id group by p.id, p.name; ``` However, you might want to think about fixing the data. It seems like there should be f...
Count rows from one tables of users in another table
[ "", "mysql", "sql", "" ]
what is the SQL WHERE clause which checks if a column TopicID('1,5,14,18') has the value '1'? ``` SELECT TOP 10 * FROM topics WHERE {TopicID has the value '1'} ``` thanks.
May be I just interpret your question incorrectly. I think you need `like`: ``` SELECT TOP 10 * FROM topics WHERE TopicID like '1,%' or TopicID like '%,1' or TopicID like '%,1,%' or TopicID = '1' ```
If TopicId is a numeric field then: ``` SELECT TOP 10 * FROM topics where TopicId = 1 ```
SQL - check if a value is in column list
[ "", "sql", "" ]
I have a table called `notes` and there I have three fields: ``` id | start_time | duration 1 | 2015-10-21 19:41:35 | 15 2 | 2015-10-21 19:41:50 | 15 3 | 2015-10-21 19:42:05 | 15 4 | 2015-10-21 19:42:35 | 15 etc. ``` `id` is INT field `start_time` is a TIMESTAMP field `durat...
The `BETWEEN` clause matches the end dates exactly. With your sample data, once you add the duration of 15 seconds and the fixed duration, also of 15 seconds, it matches your last sample data that is 30 seconds on, and hence rules out. Modify your query to ``` SELECT (a.start_time + INTERVAL a.duration SECOND) AS free...
Short answer: Because you can't just add `TIMESTAMP` to `INT`. See for example: [How to add an offset to all timestamps/DATETIME in a MySQL database?](https://stackoverflow.com/questions/9077074/how-to-add-an-offset-to-all-timestamps-datetime-in-a-mysql-database) Long answer: As a general rule when debugging a compl...
A query for finding the nearest free time slot in mysql - why it doesn't work?
[ "", "mysql", "sql", "" ]
I want to create table from some metadata of another table in hive. I'm using hive. I know from [this](https://stackoverflow.com/questions/22532419/sql-query-for-searching-column-name-in-database) question that the metatdata can be retrieved from the table by `INFORMATION_SCHEMA.COLUMNS` in sql: Does `HIVE` have a si...
You can try `CTAS` syntax: ``` CREATE TABLE new_table_name AS SELECT * FROM old_table_name WHERE 1 = 2; ```
You can use `LIKE` so the new table gets the structure but not the data. [Hive documentation](http://archive.cloudera.com/cdh4/cdh/4/hive/language_manual/data-manipulation-statements.html) ``` CREATE TABLE yourtable LIKE table2; ```
Create table in HIVE with same columns as another table?
[ "", "sql", "hadoop", "hive", "" ]
When view is created including an `ORDER BY` clause, will that order be maintained when using `SELECT * FROM VIEW`? Or is it necessary to state `SELECT * FROM VIEW ORDER BY` ?
You would need an `order by` on the outer query to guarantee that the rows are returned in the order you want. If you run a `select * from view` query against the view without a `where` clause, it is likely that the rows would be returned in the order defined in the `order by`. But that's not something that you should...
Oracle 19 definitely supports writing "create view ... as select ... from ... order by ...". As for why would anyone do it, Oracle may be using this as a hint to return the results sorted as specified, but I'd never recommend writing "order by" in the view definition, because ordering should always be done by the clien...
Does a select on a view keep the order by from the view?
[ "", "sql", "oracle", "" ]
There is an SQL query I'm after (in SQL Server). I need to get the count of instances where company Y is more expensive than company X. How would I start to tackle this? I've looked through various examples, but I cannot find anything similiar. I see PARTITION BY could be helpful, but not sure how to start from there -...
One method is conditional aggregation. For each product: ``` select product, max(case when company = 'Y' then price end) as Yprice max(case when company = 'X' then price end) as Xprice from t group by product; ``` For a count, you can then do: ``` select count(*) from (select product, max(...
This query, tho not efficient, will give you the details of what you need: ``` Select CompanyY.*, CompanyX.* FROM ( select * from OrderDetails where Company = 'Y' ) CompanyY JOIN ( select * from OrderDetails where Company = 'X' ) CompanyX ON CompanyX.Product = CompanyY.Product WHERE CompanyY.Price > Comp...
SQL query to compare subsets of rows between each other
[ "", "sql", "sql-server", "" ]
[![enter image description here](https://i.stack.imgur.com/u0uQK.jpg)](https://i.stack.imgur.com/u0uQK.jpg) SAMPLE DATA: ``` CREATE TABLE poly_and_multipoly ( "id" SERIAL NOT NULL PRIMARY KEY, "name" char(1) NOT NULL, "the_geom" geometry NOT NULL ); -- add data, A is a polygon, B is a multipolygon INSERT INTO p...
The use of ST\_Azimuth function at aengus example is giving an error because you can't use two generate\_series as parameters for a single function. If you use ep / sp values in another subquery then you won't have any trouble. Here is my solution: ``` -- 3.- Create segments from points and calculate azimuth for each...
I needed the internal angles for only polygons. The accepted solution by vamaq did not consistently give me the internal angles, but sometimes external angles, for an arbitrarily shaped polygon. This is because it calculates the angle between two lines without any consideration of which side of those two lines is inter...
Calculate the angle of exterior rings PostGIS (polygons & multipolygons)
[ "", "sql", "postgresql", "postgis", "" ]
This is a follow up to my previous question [A query for finding the nearest free time slot in mysql - why it doesn't work?](https://stackoverflow.com/questions/33688658/a-query-for-finding-the-nearest-free-time-slot-in-mysql-why-it-doesnt-work/) Basically I have a table: ``` id | start_time | duration ...
A simple solution for this would be to use date\_sub with an order by statement, limiting the results to show only 1 record. This is the result: ``` SELECT date_sub(start_time, interval duration second) as free_before FROM `notes` where start_time>'2015-10-21 16:00:00' order by start_time asc limit 1 ``` **Bonus for...
Would this work for you? Given: ``` select * from notes; +----+---------------------+----------+ | id | start_time | duration | +----+---------------------+----------+ | 1 | 2015-11-17 10:10:10 | 15 | | 2 | 2015-11-17 10:20:40 | 15 | | 3 | 2015-11-17 10:30:00 | 15 | +----+---------------...
I have an sql query for finding a nearest free time after specific date. How can I make it to also look for a date BEFORE this date?
[ "", "mysql", "sql", "" ]
I have a function written in plpythonu. ``` CREATE OR REPLACE FUNCTION temp(t_x integer[]) RETURNS void AS $BODY$ . . . x=plpy.execute("""select array_to_string(select id from A where id=any(array%s) ), ',')"""%t_x) ``` On some cases when t\_x is empty I get an error: > ERROR: cannot determine type of empty array ...
## if-else statement Pseudocode: ``` if t_x is empty x=null else x=plpy.execute.... ``` ## cast ``` x=plpy.execute("""select array_to_string(select id from A where id=any(array%s::integer[]) ), ',')"""%t_x) ``` **Why cast help?** ``` postgres=# select pg_typeof(array[1,2]); pg_typeof ----------- integer[] ...
Maybe this can help someone in future. Table function may receive NULL or Empty Array in that case (equivalent to ALL): ``` CREATE OR REPLACE FUNCTION temp(t_x integer[]) RETURNS void AS $BODY$ . . . x=plpy.execute("""select array_to_string(select id from A where id=any(array%s) or cardinality(coalesce(array%s,array[]...
How to handle cases where array is empty in PostgreSQL?
[ "", "sql", "arrays", "database", "postgresql", "types", "" ]
For example i have the table called 'Table1'. and column called 'country'. I want to count the value of word in string.below is my data for column 'country': ``` country: "japan singapore japan chinese chinese chinese" ``` expected output: in above data we can see the japan appear two time, singapore once and chinese...
Firstly, it is a bad design to store multiple values in a single column as delimited string. You should consider **normalizing** the data as a permanent solution. With the denormalized data, you could do it in a single SQL using **REGEXP\_SUBSTR**: ``` SELECT COUNT(DISTINCT(regexp_substr(country, '[^ ]+', 1, LEVEL)))...
Did you store that kind of string in a single entry? If not, try ``` SELECT COUNT(*) FROM (SELECT DISTINCT T.country FROM Table1 T) ``` If yes, I would write an external program to parse the string and return the result you want. Like using java. Create a String set. I would use JDBC to retrieve the record, a...
How to count number of words in delimited string in Oracle SQL
[ "", "sql", "oracle", "count", "split", "csv", "" ]
I have two tables, a question table, and an answer table. I then have a comments table, so that comments can be attached to a question or an answer. There an be many comments for each question or answer. Should I create two comments tables? Or relate both question and answer table to a single comments table. I would ...
It depends. In general, you would like to have foreign key relationships. If there is only one comment allowed per question/answer, then it is easy. A `commentId` goes in each of the tables, `Questions` and `Answers`. There is an easy foreign key relationship. To maintain the foreign key relationships and allow multip...
Create comments table with two foreign keys from question and answer tables. Its enough.
Can a single table be a child to two parent tables
[ "", "sql", "sql-server", "" ]
i have a table like this on a mysql database: ``` id | item ----------- 1 | 2 2 | 2 3 | 4 4 | 5 5 | 8 6 | 8 7 | 8 ``` i want the result to be 3 record with the highest Item value select max(item) returns only 1 value how can i select multiple max values? thank you
You can use a derived table to get the maximum value and `join` it back to the original table to see all rows corresponding to it. ``` select t.id, t.item from tablename t join (select max(item) as mxitem from tablename) x on x.mxitem = t.item ``` Edit: ``` select t.co_travelers_id, t.booking_id, t.accounts_id fro...
If you use an 'aggregate function' without `GROUP BY` only one row will be returned. You may use GROUP BY , with aggregate functions. Here is **[SQLFiddle Demo](http://sqlfiddle.com/#!9/60f92/1)** ``` SELECT id,max(item) AS item FROM table_name GROUP BY id ORDER BY item DESC LIMIT 3 ``` Hope this helps.
selecting multiple max values
[ "", "mysql", "sql", "" ]
My use case is an admin view to see all the messages in the db. I would like a list of message ordered by conversations and beginning dates, the idea is to be able to see each message in its context. A conversation is a list of interactions between two users. I don't have a `conversation` table, only a `message` tab...
You can use the following query to get the `id` of the first message of each conversation: ``` SELECT MIN(id), IF(sender > recipient, sender, recipient) AS participantA, IF(sender > recipient, recipient, sender) AS participantB FROM message GROUP BY participantA, participantB ``` Now use the above que...
**[SqlFiddle Demo](http://sqlfiddle.com/#!9/fc66b/35)** ``` SELECT m.*, CASE WHEN sender <= recipient THEN concat(sender,'-',recipient) ELSE concat(recipient,'-', sender) END as conversation FROM message m ORDER BY conversation, id ``` **OUTPUT** ``` | id | sender | reci...
List messages ordered by conversations for all users
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I'm using Oracle 10.g. I have a table, LIB\_BOOK, containing a listing of books in a library. There are multiple copies of many of the books. I'd like to produce a report that lists all the books with more than one copy. I've constructed a query that lists the books, but I can't find a way to get only one row for the r...
Try this ``` Select title , copy_number , isbn_10 , category , book_pk , copy_number From LIB_BOOK lib join (select title,max(copy_number) as maxcopynumber from LIB_BOOK group by title) maxcopy on lib.title = maxcopy.title and lib.copy_number = maxcopy.maxcopynumber Order by lib.copy_number desc ; ...
You need to remove `copy_number()` and `book_pk` from the `group by`: ``` Select title, isbn_10, category, max(copy_number) From LIB_BOOK Group by title, isbn_10, category Order by max(copy_number) desc; ``` I'm not sure what you want for `book_pk`, so I just removed it from the `select`.
Produce one row in an Oracle sql query using group_by
[ "", "sql", "group-by", "oracle10g", "" ]
Assuming a table ``` source_document_id BIGINT NOT NULL, target_document_id BIGINT NOT NULL, similarity DOUBLE NOT NULL, ``` If I wanted to determine the frequency of occurrence of a documents in the source\_document\_id column, my query would run something like this: ``` select count(source_document_id) as c1, sour...
There is a chance that aggregating the data twice will have better performance: ``` select id, sum(cnt) as n_docs from ((select source_document_id as id, count(*) as cnt from similarity group by source_document_id ) union all (select target_document_id as id from similarity grou...
You can merge your two columns into a single column using a `union all`, then perform your count on this aggregate column: ``` select doc_id, count(*) n_docs from ( select source_document_id as doc_id from similarity union all select target_document_id as doc_id from similarity ) group by doc_id ```
Find count of item that occurs in multiple columns
[ "", "sql", "postgresql", "" ]
Consider the following regex ``` @(.*\..*){2,} ``` Expected behaviour: ``` a@b doesnt match a@b.c doesnt match a@b.c.d matches a@b.c.d.e matches and so on ``` Testing in regexpal it works as expected. Using it it in a mysql select doesn't work as expected. Query: ``` SELECT * FROM `users` where mail regexp '@(.*\...
You can use: ``` SELECT * FROM `users` where mail REGEXP '([^.]*\\.){2}' ``` to enforce at least 2 dots in `mail` column.
I think the answer to your question is here. > Because MySQL uses the C escape syntax in strings (for example, “\n” > to represent the newline character), you must double any “\” that you > use in your REGEXP strings. [MYSQL Reference](http://dev.mysql.com/doc/refman/5.7/en/regexp.html "12.5.2 Regular Expressions") ...
MySQL regex matching at least 2 dots
[ "", "mysql", "sql", "regex", "" ]
I have 140,000 INSERT statements I need to run. I am trying to insert the record's into a database table, and then input the created PK's into a temp table which I then return. It looks something like this: ``` CREATE PROCEDURE sp_MassInsertProcedure @PassInVariable int AS CREATE TABLE #TempTable(OriginalID in...
Thanks everyone for the answers...I ended up with the following solution: From the script that was calling my stored procedure I created the #TempTable ``` CREATE TABLE #TempTable (OriginalID int IDENTITY(1,1), NewID int); EXEC sp_InsertMassRecords 777; ``` And then in my stored procedure I had: ``` CREATE PROCEDUR...
The GO statement in MS SQL releases resources and clean out your session; that is why the temp table is gone as well your variables. In your stored proc or at least the SQL script above, you don't need the go statement. The GO statements that you see in other's scripts are to prevent the parser from stop execution af...
Temp table in stored procedure is unavailable after first GO
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2014", "" ]
Consider 2 or more tables: ``` users (id, firstname, lastname) orders (orderid, userid, orderdate, total) ``` I wish to delete all **users** and their **orders** that match first name '**Sam**'. In mysql, I usually do left join. In this example userid is unknown to us. What is the correct format of the query?
<http://www.postgresql.org/docs/current/static/sql-delete.html> ``` DELETE FROM orders o USING users u WHERE o.userid = u.id and u.firstname = 'Sam'; DELETE FROM users u WHERE u.firstname = 'Sam'; ``` You can also create the table with `ON delete cascade` <http://www.postgresql.org/docs/current/static/ddl-const...
Arranging proper cascading deletes is wise and is usually the correct solution to this. For certain special cases, there is another solution to this that can be relevant. If you need to perform multiple deletes based on a common set of data you can use [Common Table Expressions (CTE)](https://www.postgresql.org/docs/c...
Postgresql delete multiple rows from multiple tables
[ "", "sql", "database", "postgresql", "relational-database", "sql-delete", "" ]
seems it is too long ago that I needed create own SQL Statements. I have a table (GAS\_COUNTER) with timestamps (TS) and values (VALUE). There are hundreds of entries per day, but I only need the latest of the day. I tried different ways but never get what I need. **Edit** Thanks for the fast replies, but some do not...
This one would give you the very last record: ``` select top 1 * from GAS_COUNTER order by TS desc ``` Here is one that would give you last records for every day: ``` select VALUE from GAS_COUNTER where TS in ( select max(TS) from GAS_COUNTER group by to_date(TS,'yyyy-mm-dd') ) ``` Depending on the database yo...
Select the max value for the timestamp. ``` select MAX(TS), value -- or whatever other columns you want from the record from GAS_COUNTER group by value ```
SQL Statement Only latest entry of the day
[ "", "sql", "h2", "greatest-n-per-group", "" ]
I am almost a newbie to writing SQL queries. In the context of SQL Server, how to get list of 2nd and 4th Saturday dates in the year 2016?
Done as a derived table simply to show the logic but you can reduce if you prefer: ``` select * from ( select d2016, datename( weekday, d2016 ) as wkdy, row_number( ) over ( partition by datepart( month, d2016 ), datename( weekday, d2016 ) order by d2016 ) as rn_dy_mth from ( sel...
**You can get any Saturday of a month using the Following Query in SQL. Here I'm Getting on Current Date, You can set your own selected date to get a Specific month Saturday** ``` select DATEADD(dd, (14 - @@DATEFIRST - DATEPART(dw, DATEADD(MONTH, DATEDIFF(mm, 0,getdate()), 0))) % 7, DATEADD(MONTH, DATEDIFF(mm, 0, getd...
How to get list of 2nd and 4th Saturday dates in SQL Server?
[ "", "sql", "sql-server", "date", "" ]