Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to create a table in my database and it gives me the following error. > ``` > ERROR: type "tbl_last_alert" already exists > HINT: A relation has an associated type of the same name, so you must use a name that doesn't conflict with any existing type. > ``` Then I thought that the table must exist so I r...
Postgres creates a composite (row) type of the same name for every table. That's why the error message mentions "type", not "table". Effectively, a table name cannot conflict with this list from [the manual on `pg_class`](https://www.postgresql.org/docs/current/catalog-pg-class.html): > `r` = ordinary table, `i` = ind...
If you can't drop type, delete it from pg\_type: ``` DELETE FROM pg_type where typname~'tbl_last_alert'; ```
Cannot create a table due to naming conflict
[ "", "sql", "postgresql", "database-administration", "" ]
I am trying to create a .bacpac file of my SQL 2012 database. In SSMS 2012 I right click my database, go to Tasks, and select Export Data-tier Application. Then I click Next, and it gives me this error: ``` Error SQL71564: Element Login: [myusername] has an unsupported property IsMappedToWindowsLogin set and is not s...
I found this post referenced below which seems to answer my question. I wonder if the is a way to do this without having to delete my user from my local database... > "... there are some features in on premise SQL Server which are not > supported in SQL Azure. You will need to modify your database before > extracting....
[SQL Azure doesn't support windows authentication](http://msdn.microsoft.com/en-us/library/windowsazure/ff394108.aspx) so I guess you'll need to make sure your database users are mapped to SQL Server Authentication logins instead.
Can't Export Data-tier Application for Azure
[ "", "sql", "azure", "sql-server-2012", "ssms-2012", "bacpac", "" ]
I'm not very good with sql so I'm not sure if this is possible. Or maybe even in excel?? I'm trying to select the very first value and ignore duplicates from Product\_ID and then add that first value for that row to the Title column. Also note that my product list is over 25,000+ items. So take this: ``` +----------...
You can use `PARTITION` to window the `ProductIds` and then identify the first row in each partition with [`ROW_NUMBER()`](http://technet.microsoft.com/en-us/library/ms186734.aspx): ``` SELECT ProductID, Product_Count, CASE WHEN rn = 1 THEN ProductID else null END AS Title, Color_Name, Size FROM ( S...
try this, ``` Declare @t table (col1 int,col2 int,col3 int) insert into @t values(2,3,null),(2,4,null),(5,3,null),(5,4,null) ;with CTE as (select *,ROW_NUMBER()over(partition by col1 order by col1)rn from @t ) select a.col1,a.col2,case when a.rn=1 then b.col1 end col3 from CTE a left join (select col1 from cte wher...
SQL select first value in a row then insert that value into another column
[ "", "sql", "sql-server", "excel", "sql-server-2008", "" ]
I have the following data : ``` Party Balance Month --------------------- ABC 500 Aug 2013 ABC 300 Sep 2013 ABC 200 Nov 2013 ABC 400 Dec 2013 ABC 100 Jan 2013 ``` I tried this query: ``` select ahead as Party, [Nov 2013], [Dec 2013], [Jan 2014] from (select a...
``` DECLARE @MyTable TABLE ([Party] varchar(max), [Balance] money, [Date] date) INSERT @MyTable VALUES ('ABC',500,'Aug 2013'), ('ABC',300,'Sep 2013'), ('ABC',200,'Nov 2013'), ('ABC',400,'Dec 2013'), ('ABC',100,'Jan 2014'); WITH t AS ( SELECT [Party],[Balance],[Date], SUM(CASE WHEN [Date] < 'Nov 2013' THEN [B...
## [SQL Fiddle](http://sqlfiddle.com/#!3/69c9e/1) **MS SQL Server 2008 Schema Setup**: ``` CREATE TABLE Test_Table(Party VARCHAR(10),Balance INT,[Month] VARCHAR(20)) INSERT INTO Test_Table VALUES ('ABC',500,'Aug 2013'), ('ABC',300,'Sep 2013'), ('ABC',200,'Nov 2013'), ('ABC',400,'Dec 2013'), ('ABC',100,'Jan 2...
Month Wise Data using Pivot with previous months sum of Balance Required
[ "", "sql", "sql-server", "t-sql", "" ]
I googled the solution online and most of the result comes back with BULK INSERT, I don't have the access to this role at this point so this is not an option. Is there any other generic way to import .csv file into MS SQL SERVER?
what I end up doing is go to task--->import, this is the original DTS functionality and it does give me option to import excel file.
Solution I've done the last few times I've needed to do this was save the CSVs as .XLS in excel and then pull it in from SSMS. Edit: [Here's a SO answer that shows how to do it](https://stackoverflow.com/questions/3474137/how-to-export-data-from-excel-spreadsheet-to-sql-server-2008-table)
how to import csv file into table of sql server other than BUIK INSERT
[ "", "sql", "csv", "import", "" ]
I am trying to perform a SQL query that removes all the rows where people have less then 10 people or more then 100 people in their network. ``` SELECT * FROM table1 Where inNetwork > 10 AND < 1000, ``` Basically, by this query what I mean is only show people with more then 10 and less then 1000 people in their netwo...
You can use `BETWEEN` to achieve this ``` SELECT * FROM table1 WHERE inNetwork BETWEEN 10 AND 1000; ``` Otherwise you will need to express both condition for your column ``` SELECT * FROM table1 WHERE inNetwork > 10 AND inNetwork < 1000; ```
``` SELECT * FROM table1 Where inNetwork > 10 AND inNetwork < 1000; ```
SQL query that removes all rows with certain value?
[ "", "sql", "" ]
I have a lookup table where one of the columns contains each date between 2000 and 2030. Problem is that the generated dates here all have milliseconds at the end, eg: ``` 2000-01-01 00:00:00.000 2000-01-02 00:00:00.000 2000-01-03 00:00:00.000 2000-01-04 00:00:00.000 ``` My other datetime columns in my data don't ha...
``` update table set Calendar_Date=convert(datetime,(convert(date,Calendar_Date))) ```
I believe that you have mis-disagnosed the problem, it's not the data, it appears to be the SQL. Let me show you some issues with your query. ``` SELECT a12.Calendar_Year AS Calendar_Year, a11.dt AS datetime, (sum(a11.mc_gross) - sum(a11.mc_fee)) AS WJXBFS1 FROM shine_orders AS a11 JOIN C...
How to update all rows to truncate milliseconds
[ "", "sql", "sql-server", "datetime", "" ]
I followed this post [How do I perform an accent insensitive compare (e with è, é, ê and ë) in SQL Server?](https://stackoverflow.com/questions/2461522/how-do-i-perform-an-accent-insensitive-compare-e-with-e-e-e-and-e-in-sql-ser) but it doesn't help me with " ş ", " ţ " characters. This doesn't return anything if the ...
The characters you've specified aren't part of the Latin1 codepage, so they can't ever be compared in any other way than ordinal in `Latin1_General_CI_AI`. In fact, I assume that they don't really work at all in the given collation. If you're only using one collation, simply use the correct collation (for example, if ...
In SQL Server 2008 collations versioned 100 [were introduced](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms143503(v=sql.105)). Collation `Latin1_General_100_CI_AI` seems to do what you want. The following should work: ``` SELECT * FROM City WHERE Name LIKE '%iasi%' COLLATE Latin1_Gene...
compare s, t with ş, ţ in SQL Server
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a table called `project_errors` which has the columns `project_id`, `total_errors` and `date`. So everyday a batch job runs which inserts a row with the number of errors for a particular project on a given day. Now I want to know how many errors were reduced and how many errors was introduced for a given month ...
It's always helpful if you can show the output that you want. My guess is that you want to subtract 54 from 56 and show that 2 errors were added on project 1, subtract 7 from 14 to show that 7 errors were added on project 2, and subtract 80 from 89 to show that 9 errors were added on project 3. Assuming that is the cas...
In addition to Justin's answer, you may want to consider changing your table structure. Instead of recording only totals, you can record the actual errors, then count them. So suppose you had a table structure like: ``` CREATE TABLE PROJECT_ERRORS( project_id INTEGER error_id INTEGER stamp DATETIME ) ``` ...
Difference between previous field in the same column in Oracle table
[ "", "sql", "oracle", "function", "" ]
I have my defined table type created with ``` CREATE TYPE dbo.MyTableType AS TABLE ( Name varchar(10) NOT NULL, ValueDate date NOT NULL, TenorSize smallint NOT NULL, TenorUnit char(1) NOT NULL, Rate float NOT NULL PRIMARY KEY (Name, ValueDate, TenorSize, TenorUnit)...
``` --Create table variable from type. DECLARE @Table AS dbo.MyTableType --Create new permanent/physical table by selecting into from the temp table. SELECT * INTO dbo.NewTable FROM @Table WHERE 1 = 2 --Verify table exists and review structure. SELECT * FROM dbo.NewTable ```
It is just like an other datetype in your sql server. Creating a Table of a user defined type there is no such thing in sql server. What you can do is Declare a variable of this type and populate it but you cant create a table of this type. Something like this... ``` /* Declare a variable of this type */ DECLARE @My...
create SQL Server table based on a user defined type
[ "", "sql", "sql-server", "create-table", "" ]
I'm having a rough time getting this syntax correct and cannot figure out how to correctly write this. I have a stored procedure with some joins and the where clause is like this: ``` WHERE [Column1] = (SELECT Source FROM @CurrentTransition) AND [Column2] = (SELECT Target FROM @CurrentTransition) AND [IsD...
That's not what a CASE statement is for. Use simple boolean logic instead: ``` AND (s.StratTimeBiasId IS NULL OR s.StartTimeBiasId IS NOT NULL AND s.StratTimeBiasId IN (SELECT * FROM dbo.fnGetValidTimeBiases(CAST(@datetime AS TIME)))) ``` The above will match anything where `s.StratTimeBiasId` has a NULL value OR whe...
Try this: ``` WHERE [Column1] = (SELECT Source FROM @CurrentTransition) AND [Column2] = (SELECT Target FROM @CurrentTransition) AND [IsDeprecated] = 0 AND sbl.StratId is null AND std.StratId is null AND s.StratTimeBiasId IS NULL OR s.StratTimeBiasId IN (dbo.fnGetValidTimeBiases(CAST(@datetime A...
SQL Conditional WHERE Using IN
[ "", "sql", "sql-server", "" ]
I want to use same value for different queries from different DB like ``` DECLARE @GLOBAL_VAR_1 INT = Value_1 DECLARE @GLOBAL_VAR_2 INT = Value_2 USE "DB_1" GO SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_1 AND "COL_2" = @GLOBAL_VAR_2 USE "DB_2" GO SELECT * FROM "TABLE" WHERE "COL_!" = @GLOBAL_VAR_2 ``` b...
There is no way to declare a global variable in Transact-SQL. However, if all you want your variables for is to be accessible across batches of a single script, you can use the **SQLCMD** tool or the **SQLCMD mode** of SSMS and define that tool/mode-specific variables like this: ``` :setvar myvar 10 ``` and then use ...
You **cannot** declare global variables in SQLServer. If you're using Management Studio you can use SQLCMD mode like @Lanorkin pointed out. Otherwise you can use [`CONTEXT_INFO`](http://msdn.microsoft.com/en-us/library/ms187768.aspx) to store a single variable that is visible during a session and connection, but it'l...
how to declare global variable in SQL Server..?
[ "", "sql", "sql-server", "" ]
I have a table in MYSQL like this: ``` ID | Team | DPV | DPT | Difference | 1 | Team1 | 25 | 27 | | 2 | Team2 | 24 | 14 | | ``` I want to do a math on DPV and DPT so like: DPV minus DPT = Difference **I have now:** e2teams is my tablename. ``` SELECT FROM e2teams GROUP by Difference HA...
How about this one: ``` SELECT ID, Team, DPV, DPT, DPV-DPT AS Difference FROM e2teams ```
Something like this? ``` SELECT ID, Team, DPV, DPT, (DPV - DPT) as Difference FROM e2teams ``` You can find more information **[here](https://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html)**
How to table minus table = answer PHP MYSQL
[ "", "mysql", "sql", "select", "count", "" ]
I have one Table name Demodata which have two column col1 and col2. data of table is ``` col1 col2 1 5 1 6 2 7 3 8 3 9 4 10 ``` and after **SELECT** command we need this data ``` col1 Col2 1 5 6 2 7 3 8 ...
Try this ``` SELECT CASE WHEN RN > 1 THEN NULL ELSE Col1 END,Col2 FROM ( SELECT *,Row_Number() Over(Partition by col1 order by col1) AS RN From yourTable ) AS T ```
No it is not possible. SQL Server result sets are row based not tree based. You must have a value for each column (alternatively a NULL value). What you can do is grouping by `col1` and run an aggregate function on the values of `col2` (possibly the `STUFF` function).
DISTINCT for only one Column and other column random?
[ "", "sql", "sql-server-2008", "" ]
I have two tables named ServiceIOD and ServiceSubs and between them only one column named ShortCode is common. So, when I try to join these two tables to get the combined result for some given short code it is not giving me the correct output. May be it is because the ShortCode column is holding redundant data for both...
I have solved this problem with this following query: ``` SELECT serviceIOD.keyword, serviceIOD.shortcode FROM serviceIOD where shortcode = 36788 UNION select serviceSubs.keyword, serviceSubs.shortcode from serviceSubs where shortcode = 36788 ``` Thank you everyone for taking your valuable time to help me on...
Try this code.Usually the UNION is avoiding duplication entries. ``` (SELECT serviceIOD.keyword, serviceIOD.shortcode FROM serviceIOD) UNION (select * from serviceSubs) WHERE serviceIOD.shortcode = 36788 ```
How to join two tables with redundant column value?
[ "", "mysql", "sql", "" ]
I have a function called generate\_table, that takes 2 input parameters (`rundate::date` and `branch::varchar`) Now I am trying to work on a second function, using PLPGSQL, that will get a list of all branches and the newest date for each branch and pass this as a parameter to the generate\_table function. The query ...
You can do this with a plain SELECT query using the new [**`LATERAL JOIN`**](http://www.postgresql.org/docs/devel/static/sql-select.html) in Postgres 9.3+ ``` SELECT * FROM ( SELECT max(rundate) AS rundate, branch FROM t_index_of_imported_files GROUP BY branch ) t , generate_table(t.rundate, t.branch)...
``` select generate_table(max(rundate) as rundate, branch) from t_index_of_imported_files group by branch ```
Dynamically execute query using the output of another query
[ "", "sql", "postgresql", "dynamic", "plpgsql", "lateral", "" ]
I have a database column and its give a string like `,Recovery, Pump Exchange,`. I want remove first and last comma from string. Expected Result : `Recovery, Pump Exchange`.
You can use [`SUBSTRING`](http://msdn.microsoft.com/en-us/library/ms187748.aspx) for that: ``` SELECT SUBSTRING(col, 2, LEN(col)-2) FROM ... ``` Obviously, an even better approach would be not to put leading and trailing commas there in the first place, if this is an option. > I want to remove last and first com...
Alternatively to dasblinkenlight's method you could use replace: ``` DECLARE @words VARCHAR(50) = ',Recovery, Pump Exchange,' SELECT REPLACE(','+ @words + ',',',,','') ```
How to replace first and last character of column in sql server?
[ "", "sql", "sql-server-2008", "" ]
I have this query: ``` select "ID" = CASE WHEN LEN(LEFT(ID, (charindex('.', ID)-1))) > 1 THEN LEFT(ID, (charindex('.', ID)-1)) ELSE ID END From table where tableID = '111' ``` The ID is something like AA11.1 or BB22 some with a period and some without. I'm wanting to truncate all characters after the period, ...
Try: ``` CASE WHEN charindex('.', ID) > 1 THEN LEFT(ID, (charindex('.', ID)-1)) ELSE ID END ```
Try this: ``` select ID = CASE WHEN charindex('.', ID) > 1 THEN LEFT(ID, (charindex('.', ID)-1)) ELSE ID END ```
SQL query conditioned by error
[ "", "sql", "sql-server", "" ]
So this seems like something that should be easy. But say I had an insert: ``` insert into TABLE VALUES ('OP','OP_DETAIL','OP_X') ``` and I wanted X to go from 1-100. (Knowing there are some of those numbers that already exist, so if the insert fails I want it to keep going) how would I do such a thing?
Here's a slightly faster way ``` -- techniques from Jeff Moden and Itzik Ben-Gan: ;WITH E00(N) AS (SELECT 1 UNION ALL SELECT 1), E02(N) AS (SELECT 1 FROM E00 a, E00 b), E04(N) AS (SELECT 1 FROM E02 a, E02 b), E08(N) AS (SELECT 1 FROM E04 a, E04 b), cteTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER B...
No need for loops. Set-based methods FTW! This is a prime example where you should use a numbers table. Other answerers have created the equivalent on the fly but you can't beat a good, old-fashioned table if you ask me! Use your best Google-Fu to find a script or alternatively [here's one I made earlier](http://gvee...
SQL SERVER Insert Addition?
[ "", "sql", "sql-server", "t-sql", "" ]
I need a query output like the below table; This is a primary entry to a table and these records will be modified by a third party program which I have no control. Can anyone suggest a good sample? ``` ID | DATEIN | DATEOUT | STATUS 1 02.02.2014 00:00:00 02.02.2014 23:59:59 1 2 03.0...
There is no need for `PM` if you want it to be in 24-hour format. And pay attention to the mask for minutes, it is `mi`, not `mm` as in your query. Also as already mentioned no need to convert `SYSDATE` to date as it is already of that datatype: ``` SELECT to_char(to_date(SYSDATE), 'dd-mm-yyyy HH24:mi:ss') date_in, ...
You can do away with DATE\_ADD and TO\_DATE functions (SYSDATE is already a DATE, no need of conversion ) , and also use `mi` to show minute instead of `mm` which is format specifier for month as in: ``` SELECT To_Char(SYSDATE, 'dd-MM-yyyy hh:mi:ss PM'), To_Char((SYSDATE + 1) + INTERVAL '-1' SECOND, 'dd-MM-yyyy...
start/end date and time in oracle sql query
[ "", "sql", "oracle", "date", "" ]
Here i am trying to auto increase my identity column in mysql databse like the following with a prefix adding before the number. **Id------------------Category** Cat10001---------Men Cat10002--------Women Cat10003---------Kids here is the [link](https://stackoverflow.com/questions/2177584/sqlserver-identity-colu...
You can use BEFORE INSERT trigger. You can do something like this. Check below to see if this is what you needed. ``` CREATE TABLE MyTable ( Id int NOT NULL PRIMARY KEY AUTO_INCREMENT, categoryid varchar(16), categoryname varchar(16) ); CREATE TRIGGER mytrigger BEFORE INSERT ON MyTable FOR EACH ROW ...
Create a view or a separate table to have this type of data. Like ``` create view calculateddata as select Id, concat('cat',CAST(Id as varchar(16))) AS categoryid from MyTable ```
how to add prefix to identity column in mysql.?
[ "", "mysql", "sql", "phpmyadmin", "" ]
I would like to create a table which will automatically compute the values of four other column to a table called totalAmount. my SQL script won't work. Kindly guide me. Thanks. This is my sql, ``` CREATE TABLE dbo.phicTF( guid UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY, phno ...
``` CREATE TABLE dbo.phicTF( guid UNIQUEIDENTIFIER NOT NULL DEFAULT NEWSEQUENTIALID() PRIMARY KEY, phno NVARCHAR(14) NOT NULL, memLname NVARCHAR(MAX) NOT NULL, memFname NVARCHAR(MAX) NOT NULL, memMname NVARCHAR(MAX) NOT NULL, pLname NVARCHAR(M...
Define the `total` column as `NVARCHAR(MAX)` and add a trigger on `INSERT` and `UPDATE`. In the trigger get values for the 4 columns sum them and assign to the `total` column.
How to create a table with a column that will automatically compute the sum of the other column using SQL Server 2008 R2?
[ "", "sql", "sql-server", "sql-server-2008-r2", "" ]
I want to ask something about Counting on WHERE clause. I have researched about it, but not found any solution. I have 2 tables: Table1 contains: ``` id, level, instansi ``` Table2 contains: ``` id, level, table1ID ``` Question: How to display `table1.instansi` only if the number of rows of `table2 less than 2`....
``` Select t1.instanci From table1 t1 inner join table2 t2 on t1.table1id=t2.table2id Group by t2.table2id Having count(t2.table2id)<2 ```
``` select t1.* from table1 t1 join table2 t2 on t2.table1ID=t1.id group by t1.id having count(*)<2 ```
How to count fields on WHERE Clause
[ "", "mysql", "sql", "where-clause", "" ]
I have a database Like this : ``` --------------------------------------------------- | MemberID | IntrCode | InstruReply | CreatedDate | ...other 2 more columns --------------------------------------------------- | 6 | 1 | Activated | 26 FEB 2014 | | 7 | 2 | Cancelled | 25 FEB 2014 | ...
Try this **Method 1:** ``` SELECT * FROM ( SELECT *,ROW_NUMBER()OVER(PARTITION BY MemberID Order By CreatedDate DESC) RN FROM MyTable WHERE InstruReply = 'Activated' AND IntrCode = @IntrCode ) AS T WHERE RN = 1 ``` **Method 2 :** ``` SELECT * FROM ( Select MemberID,max(CreatedDate) as LatestDate from MyTab...
You can use a [`CTE`](http://msdn.microsoft.com/en-us/library/ms175972.aspx) and the [`ROW_NUMBER` function](http://technet.microsoft.com/en-us/library/ms186734.aspx): ``` With CTE As ( SELECT t.*, RN = ROW_NUMBER()OVER(PARTITION BY MemberID Order By CreatedDate DESC) FROM MyTable t WHERE IntrC...
SQL Query to get 1 latest record per member based on a latest date
[ "", "sql", "sql-server", "" ]
I'm trying to build a search feature on my website. I have search working for usernames and emails, but I'd also like to be able to search based on the users full name. My problem is that first\_name and last\_name are stored separately, and I'm not sure how to build the query for this. Something like ``` SELECT * FRO...
``` SELECT * FROM users WHERE first_name LIKE '%$query%' AND last_name LIKE '%$query%' ```
Yeah, try using below query: For Oracle: ``` SELECT * FROM users WHERE first_name || ' ' || last_name LIKE '%' || $query || '%'; ``` For SQL Server: ``` SELECT * FROM users WHERE first_name + ' ' + last_name LIKE '%' + $query + '%'; ```
sql - use LIKE to search two columns at once (first and last name)
[ "", "sql", "" ]
I realize "an [`INSERT`](http://www.postgresql.org/docs/current/static/sql-insert.html) command returns a command tag," but what's the return type of a command tag? I.e., what should be the return type of a [query language (SQL) function](http://www.postgresql.org/docs/current/static/xfunc-sql.html) that ends with an ...
Most APIs specify that DML statements return the number of records affected if there are no errors, and negative numbers as error codes if there are errors that prevent the code from executing successfully. This is a good practice to incorporate into your designs.
If the inserted values are of any interest, as when they are processed before inserting, you can return a row of type `messages`: ``` CREATE FUNCTION messages_new(integer, integer, text) RETURNS messages AS $$ INSERT INTO messages (from, to, body) VALUES ($1, $2, $3) returning *; $$ LANGUAGE SQL; ``` And get...
INSERT return type?
[ "", "sql", "postgresql", "sql-insert", "return-type", "sql-function", "" ]
I need to replace HTML codes with the special characters. I am affected by the HTML code as said [here](http://webdesign.about.com/od/localization/l/blhtmlcodes-it.htm) ``` +------------------------+ + Html code + Display + +-----------+------------+ + &Agrave; + À + + &agrave; + à + + &Aacute; ...
You want to use [UTL\_I18N.unescape\_reference](http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/u_i18n.htm#i998992). For not writing long scripts, let Oracle do the job for you. Then run its generated script: ``` select 'UPDATE ' || table_name || ' SET ' || col_name || ' = UTL_I18N.unescape_reference(' || co...
You can create a procedure that will spool the UPDATE statements into a file, which you can eventually execute to perform the actual updates. The steps will involve the following: 1. Create a temp table with two columns storing the HTML Code and the Display value mapping. 2. Create a procedure that will perform this ...
Efficient way to replace HTML codes with special characters in oracle sql
[ "", "sql", "regex", "oracle", "replace", "oracle11g", "" ]
I have the following MySQL table to log the registration status changes of pupils: ``` CREATE TABLE `pupil_registration_statuses` ( `status_id` INT(11) NOT NULL AUTO_INCREMENT, `status_pupil_id` INT(10) UNSIGNED NOT NULL, `status_status_id` INT(10) UNSIGNED NOT NULL, `status_effectivedate` DATE NOT NULL, PRIMARY KEY (...
Is this what you're after? ``` SELECT a.* FROM pupil_registration_statuses a JOIN ( SELECT prs.status_pupil_id , MIN(prs.status_id) min_status_id FROM pupil_registration_statuses prs JOIN ( SELECT status_pupil_id , MAX(status_effectivedate) last_da...
I have changed where clause, please try it. ``` SELECT * FROM pupil_registration_statuses prs INNER JOIN (SELECT status_pupil_id, MAX(status_effectivedate) last_date FROM pupil_registration_statuses WHERE Datediff(status_effectivedate, '2013-05-06') <= 0 GROUP BY status_...
MySQL Query for finding a "LAST" row, based on two fields
[ "", "mysql", "sql", "" ]
I am trying to use this select statement but my issue is for this ID that i am trying to use in my select statement has null value. Even though ID 542 has null value but i know for fact in the future is going to have a 'COMPLETE' value in it. The 3 possible values for the FLAG field are COMPLETE, NOT COMPLETE AND NULL....
Convert the NULL to text: ``` SELECT ID, DT, STAT FROM myTable WHERE ID = 542 and ISNULL(FLAG,'NULL') <> 'COMPLETE' ```
``` SELECT ID, DT, STAT FROM myTable WHERE ID = 542 and ISNULL(FLAG, 'NOT COMPLETE') <> 'COMPLETE' ``` Since the `FLAG` is null it cannot be compared against 'COMPLETE' and you're missing the entry... or: ``` SELECT ID, DT, STAT FROM myTable WHERE ID = 542 AND (FLAG <> 'COMPLETE' OR FLAG IS NULL) ```
Issue with null value using select statement
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I am working on DW project where I need to query live CRM system. The standard isolation level negatively influences performance. I am tempted to use no lock/transaction isolation level read uncommitted. I want to know how many of selected rows are identified by dirty read.
Maybe you can do this: ``` SELECT * FROM T WITH (SNAPSHOT) EXCEPT SELECT * FROM T WITH (READCOMMITTED, READPAST) ``` But this is inherently racy.
Why do you need to know that? You use `TRANSACTION ISOLATION LEVER READ UNCOMMITTED` just to indicate that `SELECT` statement won't wait till any update/insert/delete transactions are finished on table/page/rows - and will grab even *dirty* records. And you do it to increase performance. Trying to get information abou...
How to Select UNCOMMITTED rows only in SQL Server?
[ "", "sql", "sql-server", "t-sql", "isolation-level", "transaction-isolation", "" ]
I am stuck with a query where one table has many records of the same id and the columns have different values like this: ``` ID Name Location Daysdue date 001 MINE NBI 120 13-FEB-2013 001 TEST MSA 111 14-FEB-2013 002 MINE NBI 13 13-FEB-2013 002 MINE MSA 104 15-FEB-2013 `...
It appears that you want something like ``` SELECT * FROM (SELECT t.*, rank() over (partition by id order by daysDue desc) rnk FROM table_name t) WHERE rnk = 1 ``` Depending on how you want to handle ties (two rows with the same `id` and the same `daysDue`),...
First you need to find the `MAX(daysdue)` for each `ID`: ``` SELECT ID, MAX(daysdue) AS max_daysdue FROM table GROUP BY ID; ``` Then you can join your original table to this. ``` SELECT t.* FROM table t JOIN ( SELECT ID, MAX(daysdue) AS max_daysdue FROM table ...
Select the record with the greatest value in Oracle
[ "", "sql", "oracle", "" ]
1. How do I reuse the value returned by `pair` called in the function below? ``` CREATE FUNCTION messages_add(bigint, bigint, text) RETURNS void AS $$ INSERT INTO chats SELECT pair($1, $2), $1, $2 WHERE NOT EXISTS (SELECT 1 FROM chats WHERE id = pair($1, $2)); INSERT INTO messages VALUES...
Since the function body is procedural, use the [`plpgsql`](http://www.postgresql.org/docs/current/static/plpgsql.html) language as opposed to SQL: ``` CREATE FUNCTION messages_add(bigint, bigint, text) RETURNS void AS $$ BEGIN INSERT INTO chats SELECT pair($1, $2), $1, $2 WHERE NOT EXISTS (SELECT 1...
``` create function messages_add(bigint, bigint, text) returns void as $$ with p as ( select pair($1, $2) as p ), i as ( insert into chats select (select p from p), $1, $2 where not exists ( select 1 from chats where id = (select p from p) ...
SQL: Reuse value returned by function?
[ "", "sql", "postgresql", "variables", "sql-insert", "sql-function", "" ]
I'm having trouble using the `filter by form` in a SQL query via VBA in Access 2013. I didn't create the Access forms but was commissioned to correct an issue. Also the client told me that it worked in the previous Office versions and that the Access-Database hasn't been changed in the past few years. So it seems, that...
Since I couldn't get rid of the preceding `Lookup_`-thing I decided to deal with it in VBA. I used following VBA-Code to change the part with **Lookup\_[field]** to a corresponding SQL-query: ``` If InStr(strFilter, "Lookup_") <> 0 Then If InStr(strFilter, "Programm__IDFS") <> 0 Then strFilter = Replace(s...
Recently I ran in to a similar problem with an application that was upgraded to Access 2013 after running fine under Access 2003. I noticed that the form's combo box controls shared the exact same name as their source fields. Suspecting that name ambiguity might be confusing Access when it generates the filter, I renam...
Use the filter of a form in a SQL query via VBA
[ "", "sql", "ms-access", "filter", "vba", "" ]
I can find a solution for one of my sql statement and I want to ask for your help ;) Lets imagine that we have table of Athletes and they have to run 100 meters of what ever distance. after each run the table innserts Run, Name and Time for each run: ``` Run Name Time[s] 1 Joe 10 2 Joe 11 1 Jim 14 ...
Your SQL query is all over the place You have an uncessary join and your `group by` is in the wrong place and your `left join` syntax is also incorrect. I scrapped it and rewrote it to use `min()` properly. ``` SELECT run, MIN(Time) AS MinTime, Name AS Timename From Athletes group by TimeName ``` There is no need to ...
``` select Run , Name, Time from Athletes a where Time=(select min(time) from Athletes s where s.Name=a.Name) ```
SQL multi select with join
[ "", "sql", "select", "join", "left-join", "" ]
I have an sql like this: ``` SELECT temp.inst_id, ' ', gv.instance_name, gv.host_name, CASE WHEN component IS NULL THEN 'others' ELSE component END component, ROUND (SUM (used_mb), 1) used_mb FROM (SELECT inst_id, CASE WHEN name = 'buffer...
If the value is `NULL`, then you can use `coalesce()` (or several other functions)` to put in a value: ``` SELECT temp.inst_id, ' ', gv.instance_name, gv.host_name, CASE WHEN component IS NULL THEN 'others' ELSE component END component, COALESE( ROUND (SUM (used_mb), 1), 0...
You just need to give it a default value if it is `NULL`: ``` COALESCE(ROUND (SUM (used_mb), 1),0.0) used_mb ```
Assigning a specific value in sql query
[ "", "sql", "oracle", "" ]
I now have my table results ordered by points. But it needs to be order by points but if this is the same than order by Difference. Now is have is this: ``` ... ORDER BY Points DESC"; ``` But i want to have something like this: ``` ... ORDER BY Points (if two have the same amount) Than ORDER BY Goal Difference ``` ...
The correct answer is: Thanks! ``` ORDER BY Points DESC, Goal Difference DESC ``` This works for me
It would help if you included the full query in your question. The `order by` clause can accept multiple arguments. As you phrase the question, the answer would be something like: ``` order by Points desc, GoalDifference ``` You might want an expression: ``` order by Points, t1.Goals - t2.Goals ``` These are also a...
Order by Points but if the same order by in MySQL
[ "", "mysql", "sql", "sql-order-by", "" ]
I am learning SQL, and I am trying to solve a problem in SQL Server -- what we use at school. I am however playing around with Postgres because it's the only DB I can easily install at home. I know this may cause difficulties, but I imagine my query is quite easy. Having said that, in Postgres I create the following s...
"Partitioning" or "windowing" methods are available in MSSQL. Great tutorial over at [simple talk](https://www.simple-talk.com/sql/learn-sql-server/window-functions-in-sql-server/) Windowing methods, like `OVER` would create data like your example. [`RANK`](http://technet.microsoft.com/en-us/library/ms176102.aspx) i...
As you already have a rank column, the easiest should be to do the following: ``` Select id1 , Min(rank) as Min_Rank From Test Group by id1 ```
SQL Server aggregator
[ "", "sql", "sql-server", "postgresql", "t-sql", "" ]
I have following query, that's not working. ``` select * from table where id in ( 1,2, (select id from another_table) ) ``` How i can rewrite it?
How about ``` select * from table where id in (1,2) or id in (select id from another_table) ``` Take care and use parentheses when adding additional `WHERE`-conditions using `and`!!!
``` select * from table where id in (1,2) OR id in( select id from another_table ) ```
Oracle SQL Query IN
[ "", "sql", "oracle", "" ]
I want to execute this statement ``` CREATE TABLE Tab2 AS SELECT 1, "abc", 123456789.12 UNION SELECT 2, "def", 25090003; ``` on an SQL database. However column names of the resulting table are 1, "abc", and 123456789.12. Is there a way to give the columns explicit names, e.g. like col1, col2, and col3? I know, I cou...
Simply give the selected columns alias names as desired: ``` CREATE TABLE Tab2 AS SELECT 1 AS COLUMN1, \"abc\" AS COLUMN2, 123456789.12 AS COLUMN3 UNION SELECT 2, \"def\", 25090003; ```
You can use the `as` clause for columns: ``` CREATE TABLE Tab2 AS SELECT 1 as col1, \"abc\" as col2, : ```
CREATE TABLE ... AS SELECT with discrete values with explicit column names
[ "", "sql", "" ]
I have 1 tables userinfo as shown below.There may be 1000 records. I want to get each record from table userinfo and insert into tblRating. For RatingQue1,RatingQue2,RatingQue3 i want add '4'.I want final result of tblRating as shown in tblRating below. userinfo ``` Id empname managername 1 E1 M1 ...
This worked for me ``` DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR SELECT Ename FROM Tegra DECLARE @id nvarchar(50) OPEN c FETCH NEXT FROM c INTO @id WHILE (@@FETCH_STATUS = 0) BEGIN INSERT INTO Rating2 SELECT 'Manager','E1', @id, 4, 4, 4, 4, 4, 4 FETCH NEXT FROM c INTO @id END CLOSE c DEALLOCATE c ```
Never use Cursors in your query it will slow down your query performance use following it gives o/p as you want: create this two table (rating,userinfo ) before executing this query ``` **Insert into rating select *,4,4,4,4 from userinfo** ```
Get data from one table and for each record from this table insert data into another table
[ "", "mysql", "asp.net", "sql", "sql-server-2008", "" ]
I have a dataset of about 32Million rows that I'm trying to export to provide some data for an analytics project. Since my final data query will be large, I'm trying limit the number of rows I have to work with initially. I'm doing this by running a create table on the main table (32Million) records with a join on ano...
**Try explain select to see what is going on first of all. Are your indexes properly setup?** **Also you are not joining the two tables with their primary keys, is that on purpose?** Where is your primary key and foreign key? **Can you also provide us with a table schema?** Also, could your hardware be the problem? ...
Your join is a full cross-join it seems. That will take really really long in any case. Is there no common field in both tables? Why do you need this join? If you really want to do this, you should first create two tables from `alerts` and `sig` that fulfill your `WHERE conditions` and then join the resulting tables if...
MySQL: SELECT millions of rows
[ "", "mysql", "sql", "" ]
I need to build a MYSQL VERSION 5.6.15 query that will allow me to do a SELECT statement that returns a column of answers and then use that column to build the next SELECT statement. I'm new to mySQL and have tried a bunch of ideas but so far have failed. I'm sure that the answer must be simple but I've given on on fi...
this should do the trick.. its not the best way to build a query as it can run slowly with a really large table... but this should do what you want... see fiddle <http://sqlfiddle.com/#!2/b7a53/10> ``` SELECT order_date as o_date, quantity, (SELECT order_date FROM orders WHERE order_date > o_date LIMIT 1) as n...
``` WITH OrderedOrders AS ( SELECT order_date, quantity, ROW_NUMBER() OVER (ORDER BY order_date) AS RowNumber FROM Orders ), FilteredOrders AS ( SELECT * FROM OrderedOrders WHERE quantity>35 ) SELECT OrderedOrders.order_date, OrderedOrders.quantity FROM OrderedOrders INNER JOIN FilteredOrde...
How do I SELECT a column of dates and use that to drive a second SELECT statement?
[ "", "mysql", "sql", "" ]
I have two columns in SQL Server in two different tables. One column has `9.011`, and other table columns has `9011`. I need to remove the `.` and compare these two columns to see whether they are equal. Can anybody help me out how to do this? Thanks in advance.
Try this: ``` SELECT CASE WHEN REPLACE (Table1.ColName1,'.','') = Table2.ColName2 THEN 'Equal' ELSE 'Not Equal' END AS IsEqual FROM Table1 INNER JOIN Table2 ON Table1.PrimaryKey = Table2.ForeignKey ``` This query will return `Equal` if they are equal and `Not Equal` if t...
I am assuming that your columns are decimal type, so I have converted them to varchar first ``` where replace(Convert(varchar(50), column1 ),'.','') = Convert(varchar(50), column2) ```
How to compare two columns in SQL server
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a table which looks as follows (simplified): **name | status** app-1 | start app-1 | run app-1 | run app-1 | run app-1 | finish app-2 | start app-2 | run app-2 | run now, I would like to filter all apps, that have "start" for a status AND no "finish". For the example above, the result is suppos...
``` select name from _table t1 where t1.status = 'start' and not exists ( select name from _table t2 where t1.name = t2.name and t2.status = 'finish' ) ```
Try something like this: ``` SELECT * FROM table_name WHERE status = 'run' and name NOT IN (SELECT name FROM table_name WHERE status = 'finish') ```
SQL Query: comparison with condition
[ "", "sql", "filter", "comparison", "conditional-statements", "" ]
Assume I have the following table: ``` +------------+-------------+ | Product_id | customer_id | +------------+-------------+ | a | c1 | | a | c2 | | a | c3 | | a | c4 | | b | c1 | | c | c1 | | b | c2 ...
You can do this with a single aggregation and no subqueries. The key is using a nested case statement with aggregation to count each product for each customer. The following determines whether a customer has each "bundle": ``` SELECT CUSTOMER_ID, (case when max(case when product_id = 'a' then 1 else 0 end) + ...
Please try below query to find customer having the products `a, b and c`: ``` SELECT CUSTOMER_ID FROM CUSTOMERS_SALES WHERE PRODUCT_ID IN ('a', 'b', 'c') GROUP BY CUSTOMER_ID HAVING COUNT(DISTINCT PRODUCT_ID)=3 ``` **To get the count try**: ``` SELECT COUNT(*) FROM( SELECT CUSTOMER_ID FROM CUSTOMERS_SALES WHE...
Aggregation based on another column values
[ "", "sql", "oracle", "" ]
Is there a difference between these two queries? Like performance issues, etc? Query 1: ``` select i.invoice_id, i.total_price from ( select invoice_id, sum(price) as total_price from orders group by invoice_id ) as i inner join...
Let me rewrite your queries without any sinifical changes: Query 1 ``` SELECT i.invoice_id, i.total_price FROM invoice INNER JOIN ( SELECT invoice_id, sum(price) AS total_price FROM orders G...
Your first query ``` select i.invoice_id, i.total_price from ( select invoice_id, sum(price) as total_price from orders group by invoice_id ) as i inner join invoice ON i.invoice_id = invoice.invoice_id ``` i...
MySQL nested select query performance
[ "", "mysql", "sql", "performance", "nested", "profiling", "" ]
if there : (department) table: (id,name) (employee) table : (id,dept\_id,name) how to show every department (id,name), then all employees (id,name) in this department under its department. I'd like it as SQL statment
You need to use JOIN I believe it's something like this: ``` SELECT department.id, department.name, employee.id, employee.name FROM department LEFT JOIN employee ON department.id=employee.dept_id ORDER BY department.id ```
Since all employees must be present under a particular department at any time, you can do a `inner join` on both the table with `dept_id` like ``` SELECT dept.id, dept.name, emp.id, emp.name FROM department dept JOIN employee emp ON dept.id=emp.dept_id ```
display all departments and all employees
[ "", "sql", "" ]
I want to delete rows based on the combination of two columns. My table looks like this (simplified): ``` [ID], [Sub_ID], [Value] ``` Values could for example be: ``` 1234 - 1 - 100 1234 - 2 - 50 5678 - 1 - 90 4321 - 1 - 75 4321 - 2 - 75 ``` I want to delete all records except for some specific combinations of [ID]...
You could use a `CTE` which selects all records that should not be deleted, then you can join it with the original table: ``` WITH Keep AS ( SELECT ID=1234, Sub_ID=2 UNION ALL SELECT ID=4321, Sub_ID=2 ) SELECT t.* FROM Table1 t INNER JOIN Keep k ON t.ID = k.ID AND t.Sub_ID = k.Sub_ID ``` This sho...
Performing a transform on the left side of the where clause will usually result in poor performance. I would suggest staging the rows you want to delete in a temp table and then simply join to it in your delete. When you need to expand the delete criteria just add an insert into this staging table (@delete): ``` decla...
Efficient way to delete values based on multiple columns in SQL
[ "", "sql", "sql-server", "" ]
I want to design a DB for school, where marks for students will be scored. But i got stuck at a point with my current design where i want to insert student marks. My current DB design at broader level is something like: ``` ------------------- ------------------- ------------------ STUDENTINFO | ...
I hope I have understood the problem correctly. It seems you design may need some improvements. In the current design nothing could prevent a student to have participate in an exam twice. Exam have no subject so an exam could be result in multiple subjects... etc (correct me if i am wrong) BTW the sou...
All the tables that describe the static objects are there. These are look up tables. To get to your answer a transaction table that pulls items from the lookup tables is needed. The transaction will describe the particular student in a particular class. Maybe the transaction will include the exam they are signed up for...
Insertion anomaly in database design
[ "", "sql", "database", "database-design", "" ]
I have a table with 100 rows, indexed 1-100. I have another table with 50 rows, indexed 1-50. I want to take the rows in the 50 row table and update the values at the corresponding index in the 100 row table: ``` UPDATE t100 SET text = (SELECT text FROM t50 WHERE t50.id = t100.id) ``` It works, but it turns rows 51-1...
You are updating all entries of `t100` regardless of whether there is a corresponding entry in `t50`. What you should be doing is: ``` UPDATE t100 SET text = (SELECT text FROM t50 WHERE t50.id = t100.id) WHERE t100.id IN (SELECT id FROM t50) ```
Because you update every row in t100. Add the following to the end of your query ``` Where t100.id <=50 ```
Why does updating only some rows delete the rest of the rows in the column?
[ "", "sql", "merge", "sql-update", "" ]
I am stuck with something. I am trying to take a long column of dates of which are formated to show also hours and minutes and run a Group query to paste values at the date level without acknowledging the differences in hours and minutes.. Unfortunately I have no clue how to start. The code i put together so far which ...
One way of doing this is to format the date/time as a date string. If you use `YYYY/MM/DD` it will sort properly. Otherwise you can convert the date/time to an int to trim off the time and then convert back to a date/time type. Here is an example of formatting as string: ``` Format([tblSearchEngine02].[Date], "yyyy/m...
Focus on the `SELECT` piece first. You can use `DateValue()` for your `Date` field values. Start with this as a new query in the Access query designer: ``` SELECT DateValue(se02.Date) FROM tblSearchEngine02 AS se02 GROUP BY se02.Date ORDER BY se02.Date ``` Or you could use `DISTINCT` instead of `GROUP BY`: ``` SELEC...
Rounding dates to the day in an SQL query
[ "", "sql", "ms-access", "vba", "ms-access-2010", "" ]
I have a MySQL database with a 1 to N relation in there. ``` Sample Data: Table User: ID,Name Table Entry: ID,Name Table User_Entry: UserID,EntryID ``` I would like to get all Entries (their ID and NAME) and a flag, that states, if a User with ID x has this Entry (via Table USER\_ENTRY)
You would need to select from your entry table to get all your entries, and then left join to your user\_entry table to find out if a particular user has that entry: ``` SELECT e.ID, e.Name, CASE WHEN ue.EntryID IS NULL THEN 0 ELSE 1 END AS UserFlag FROM Entry AS e LEFT JOIN user_Entry AS ...
@GarethD answer is fine but I would go one step further to verify that actual `UserID` in `User_Entry` is actual valid user in `User` table. If you do not have foreign keys on the table it is possible that you have `UserID` that does not exists in `User` table. To enforce that check you can join both tables and verify ...
SQL Query Help 1 to N
[ "", "mysql", "sql", "" ]
I have to do a sql query and I don't know how to do. I'd like to get the latest rows for each unique duo A/B. I'm working with postgresql. For instance: Table: Person ``` id A B modification_date 1 5 6 2014-04-12 2 6 7 2014-04-13 3 5 6 2014-04-14 4 9 1 2014-04-15 5 6 7 2014-04-16 ``` And I'd...
`SELECT` the `MAX`imum of `modification_date` for each `GROUP` of (`A`, `B`), then `JOIN` back to the original row to get the values (necessary to get the `id` column): ``` SELECT t1.* FROM Person t1 JOIN ( SELECT MAX(modification_date) max_date, A, B FROM Person GROUP BY A, B ) t2 ON t1.A = t2.A AND t1.B ...
``` SELECT DISTINCT ON (a, b) * FROM person ORDER BY a, b, modification_date DESC; ``` Detailed explanation: [Select first row in each GROUP BY group?](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564)
SQL Query, latest rows for each unique duo
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
SELECT Count the rows that are in this query --> (SELECT Family FROM BIRD GROUP BY Family) FROM BIRD Every time I just try and count that sub query I get an error saying that there is more than one resulting value. I'm not sure how to count up the rows resulting from a sub query, any ideas?
You could put this sub-query in the `from` clause: ``` SELECT COUNT(*) FROM (SELECT family FROM bird GROUP BY family) t ``` But if you're just trying to get the number of different bird families you don't really need a subquery: ``` SELECT COUNT (DISTINCT family) FROM bird ```
Try this: ``` SELECT Count(*) as FamilyCount FROM (SELECT Family FROM BIRD GROUP BY Family) Families ``` `Count()` returns the number of items in a group. Read more [here](http://technet.microsoft.com/en-us/library/ms175997.aspx).
SQL Counting up rows resulting from a sub query
[ "", "sql", "" ]
I'm trying to create a SQL query that tells me how many users there are that have one or more products. I created this query which tells me all of the users that have products: ``` SELECT DISTINCT `users`.* FROM `users` INNER JOIN `products` ON `users`.`id` = `products`.`creator_id` ``` However, I want the count of ...
``` SELECT COUNT(DISTINCT `users`.`id`) FROM `users` INNER JOIN `products` ON `users`.`id` = `products`.`creator_id` ```
`DISTINCT` filters your result rows to be unique. The aggregation (i.e. the `COUNT()`) is done prior, so is following your `JOIN` and counting users twice. So, to get the number of users that have products, you could do: ``` SELECT COUNT(DISTINCT u.id) FROM users AS u INNER JOIN products AS p ON...
How do I use the SQL COUNT() function properly in this context?
[ "", "mysql", "sql", "" ]
I like to get the amount of rows where a certain field is either 1 or 0. My table looks like this: ``` ID | name | my_bool =================== 1 | foo | 1 2 | bar | 1 3 | loo | 0 4 | zoo | 1 ``` as result I expect ``` YES | NO | percentage ====================== 3 | 1 | 0.3333 ``` `YES` is how many ro...
In MySQL, you can do this easily with conditional aggregation: ``` select sum(my_bool = 1) as yes, sum(my_bool = 0) as no from table t; ``` EDIT: The percentage is very easy: ``` select sum(my_bool = 1) as yes, sum(my_bool = 0) as no, avg(my_bool = 0) from table t; ``` However, your value suggests you are looking ...
``` SELECT SUM(IF(my_bool=1, 1, 0)) AS YES, SUM(IF(my_bool=0, 1, 0)) AS NO FROM mytable ```
Count boolean field values within a single query
[ "", "mysql", "sql", "" ]
I have 2 table in my database (like this): ``` tblCustomers: id CustomerName 1 aaa 2 bbb 3 ccc 4 ddd 5 eee 6 fff ``` --- ``` tblPurchases: id CustomerID Price 1 1 300 2 2 100 3 3 500 4 1 150 5 4 50 6 ...
``` select c.id, c.customername, sum(isnull(p.price, 0)) as sumprice from tblcustomers c left join tblpurchases p on c.id = p.customerid group by c.id, c.customername ``` SQL Fiddle test: <http://sqlfiddle.com/#!3/9b573/1/0> Note the need for an outer join because your desired result includes customers with ...
You can use the below query to get the result ``` select id,CustomerName,sum(price) as TotalPrice from ( select tc.id,tc.CustomerName,tp.price from tblCustomers tc join tblPurchases tp on tc.id = tp.CustomerID ) tab group by id,CustomerName ```
How to Get Sum of One Column Based On Other Table in Sql Server
[ "", "sql", "sql-server", "stored-procedures", "sum", "" ]
*Problem is solved - see end of this post.* when i call to\_date in select clause everything works fine - get a resultset of 12 records: ``` select value1,to_date(value1,'DD.MM.YYYY') from variableindex where value1 is not null and value1 <> '0' and creation_time_ > to_timestamp('20140307','YYYYM...
This is your query with the `where` clause: ``` select value1, to_date(value1,'DD.MM.YYYY') from variableindex where value1 is not null and value1 <> '0' and creation_time_ > to_timestamp('20140307', 'YYYYMMDD') and to_date(value1 'DD.MM.YYYY') < to_date('20140301', 'YYYYMMDD') order by 2; ``` Ora...
If you're using `OracleParameter` in SQL with parameter name and value binding, check you set the `oracleCommand.BindByName = true` then it'll bind by name, and not by parameter adding order.
ORA-01847 day of month must be between 1 and last day of month - but data is OK
[ "", "sql", "oracle", "date", "" ]
I wrote two queries which are working fine, but they are really really slow: ``` SELECT director FROM movies WHERE id NOT IN (SELECT movie_id FROM stars_in_movies WHERER star_id = %s); SELECT first_name, last_name FROM stars WHERE id NOT IN (SELECT star_id FROM stars_in_movies WHERE ...
Try this: ``` SELECT m.director FROM movies m LEFT JOIN stars_in_movies sm ON m.id = sm.movie_id WHERE sm.movie_id IS NULL AND sm.star_id = %s ``` the second query ``` SELECT first_name, last_name FROM stars s LEFT JOIN stars_in_movies sm ON sm.star_id = s.id WHERE sm.star_id IS NULL AND sm.star_id = %...
Try this: ``` select t1.director from movies t1 left outer join stars_in_movies t2 on t1.id = t2.movie_id where t2.movie_id is null; select t1.first_name, t1.last_name from stars t1 left outer join stars_in_movies t2 on t1.id = t2.star_id where t2.star_id is null; ``` here is an **[example](http://sqlfiddle.com/#!2/...
Replace NOT IN with LEFT JOIN in SQL statement
[ "", "mysql", "sql", "database", "" ]
I have a table in SQL Server that has 34 columns. I need sum all column values in a row in SQL Server. Table : `[CALEN]` Columns: ``` YEAR_ | MONTH_ |D1 | D2 | D3 | D4 | D5 .... | D31 | Days ------------------------------------------------------------ 1392 | 12 | 1 | 1 | 2 | 1 | 4 ... | 0 | 29 ```...
You need to unpivot your table: ``` SELECT YEAR_, MONTH_, DAY_, COUNT_ FROM (SELECT * FROM [CALEN] WHERE YEAR_ = 1392 and MONTH_ = 12) CALEN_FILTER UNPIVOT (COUNT_ FOR DAY_ IN (D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, D14, D15, D16, D17, D18, D19, D20, D21, D22, D23, D24, D25, D26, D27, D28, D29...
You can do something like this: ``` SELECT CASE WHEN D1 = 1 THEN 1 ELSE 0 END + CASE WHEN D2 = 1 THEN 1 ELSE 0 END + CASE WHEN D3 = 1 THEN 1 ELSE 0 END + CASE WHEN D4 = 1 THEN 1 ELSE 0 END + . . . CASE WHEN D31 = 1 THEN 1 ELSE 0 END AS TOTAL_D FROM [CALEN] WHERE YEAR_ = 1392 AND MONTH_ = 12 ``` ## [SQL Fiddle](ht...
Sum all column value in a row in SQL Server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two tables as below: ``` Highschooler ID name grade 1510 Jordan 9 1689 Gabriel 9 1381 Tiffany 9 1709 Cassandra 9 1101 Haley 10 1782 Andrew 10 1468 Kris 10 1641 Brittany 10 1247 Alexis 11 1316 Austin 11 1...
You need to join the 'highschooler' table twice: ``` select h1.name, h1.grade, h2.name, h2.grade from highschooler h1 inner join friends on friends.id1 = h1.id inner join highschooler h2 on h2.id = friends.id2 ``` The problem with the 'friends' table and the above query is that even if A is a friend of B, B is not n...
As previous poster mentioned, you need to list the highschooler table twice, since you need to reference it twice to compare both the ID's from the friends table. His syntax is correct; another way to do it with straight joins and a where clause is: ``` SELECT side1.name, side1.grade, side2.name, side2.grade FROM h...
SQL- Looking up value across tables
[ "", "sql", "" ]
I'm trying to learn how to import data from a csv file to my database and then reorganise it into my tables. I have imported a very simple set of data into a table called ' CSVTest\_Match' that looks like this: ``` HEADER DATA --(Column Names) --------------- -------------- Home Team Barnsle...
``` SELECT * FROM (SELECT Header, Data FROM CSVTest_Match) AS T PIVOT (Min(Data) FOR Header IN ([Home Team], [Away Team], [Kick Off Time], [Kick Off Date], [Home Goals], [Away Goals])) AS T2 ```
I don't remember where I swiped this from, probably from around here, but here you go, I've been using this for a while.. This assumes the column 'names' are Indicator1-x and the table is yourtable. Search and replace accordingly. If you don't know your header names ahead of time, do a select distinct on them, and then...
Convert Columns of Data to Rows of data in SQL Server
[ "", "sql", "sql-server", "pivot", "" ]
How to use select statement using like condition by passing a column from another table? My query ``` SELECT count(1) FROM COMPANYNAME_RESTRICT_LIST a,itaukei_data_store_key b WHERE b.surname LIKE a.company_name% OR b.surname LIKE %a.company_name% OR b.surname LIKE %a.company_name% OR b.surname LIKE a...
This Works Fine. ``` SELECT * FROM COMPANYNAME_RESTRICT_LIST a,itaukei_data_store_key b WHERE b.surname LIKE '%'||a.company_name||'%' or b.surname LIKE '%'||a.company_name or b.surname LIKE a.company_name||'%' or b.surname LIKE a.company_name; ```
The standard SQL function is `concat()`: ``` SELECT count(1) FROM COMPANYNAME_RESTRICT_LIST a join itaukei_data_store_key b on b.surname like concat('%', a.company_name, '%') ``` Not all databases support `concat()`. So, one of the following will also generally work: ``` on b.surname like '%' || a.co...
Select command using like condition
[ "", "sql", "select", "sql-like", "" ]
Im trying to combine these 3 mysql statements. I've been using the UNION and JOIN Keyword however it doesnt come up with the output I desired. Any suggestions? This is my 3 statements. ``` SELECT * FROM entrancequestion WHERE Subject='Abstract Reasoning' ORDER BY RAND() LIMIT 10 SELECT * FROM entrancequestion WHERE S...
Quoting the [docs](http://dev.mysql.com/doc/refman/5.1/en/union.html), To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT: ``` (SELECT * FROM entrancequestion WHERE Subject='Abstract Reasoning' ORDER BY RAND() LIMIT 10) UNION (SELECT * FROM entrancequ...
You need to use parentheses in the query when using UNION and LIMIT, like: ``` (SELECT * FROM entrancequestion WHERE Subject='Abstract Reasoning' LIMIT 10) UNION (SELECT * FROM entrancequestion WHERE Subject='English' ORDER BY RAND() LIMIT 30); ```
Combine 4 SELECT queries on mysql
[ "", "mysql", "sql", "vb.net", "" ]
I am trying to setup foreign key for my mysql database using phpmyadmin. But phpmyadmin only displays internal relation in 'relational view'. Note I have already made sure of following steps. 1. Setup phpmyadmin database (create\_table.sql and config stuff) ![phpmyadmin status](https://i.stack.imgur.com/PX9Jr.png) ...
This is not actually a solution, but since I cannot comment on posts yet, I'll add a few comments that might help. I've faced this same issue and the **critical parameters** seem to be the following: 1. Case insensitive operating system (in my case windows) 2. Mixed-case table names (e.g. "TableName") I've been usin...
If you have different storage engines on the tables in your database, this would be the case. The only storage engine I know to support foreign keys is InnoDB. MyISAM and the rest don't seem to work.
phpmyadmin only displays internal relation in relational view
[ "", "mysql", "sql", "database", "phpmyadmin", "" ]
In MongoDB you can retrieve the date from an ObjectId using the `getTimestamp()` function. How can I retrieve the date from a MongoDB ObjectId using SQL (e.g., in the case where such an ObjectId is stored in a MySQL database)? Example input: ``` 507c7f79bcf86cd7994f6c0e ``` Wanted output: ``` 2012-10-15T21:26:17Z `...
This can be achieved as follows (assuming `objectId` is a string) in MySQL: ``` SELECT FROM_UNIXTIME( CAST(CONV(SUBSTR(objectId, 1, 8), 16, 10) AS UNSIGNED) ) FROM table ``` It works as follows: * `SUBSTR(objectId, 1, 8)` takes the first 8 characters from the hexadecimal `objectId` string * `CONV(..., 16, 10)` c...
For those using SQL Server, similar results would be generated with: ``` SELECT DATEADD( SECOND, CAST( CONVERT( BINARY(4), '0x'+SUBSTRING(@MongoObjectId, 1, 8), 1 ) AS BIGINT ), CAST('1970-01-01 00:00' AS DATETIME) ) ```
How to retrieve the date from a MongoDB ObjectId using SQL
[ "", "sql", "mongodb", "" ]
I have a table iminvbin\_sql.. This table has columns item\_no, loc, bin\_no. Each item number should have 4 bins in location 2. how do I find all the items that do not have these four bins in loc 2? I tried ``` select item_no from iminvbin_sql where bin_no not in('910SHIP','910STAGE','910PROD','1') AND loc = 2 ``` ...
I think this is what you want: ``` select item_no from iminvbin_sql where bin_no in ('910SHIP', '901STAGE', '910PROD', '1') and loc = 2 group by item_no having count(distinct bin_no) <> 4; ``` This will check that all four of those values are in the bins. If you want to verify that these four values are in the ...
Use a `group by` with a `having` clause to determine if *all* bins are not there: ``` select item_no from iminvbin_sql group by item_no having sum(case when loc = 2 and bin_no in ('910SHIP','901STAGE','910PROD','1') then 1 end) < 4 ``` The important point with this query is that by moving the condtions into the `case...
How to find all items in table that don't have a certain text in column
[ "", "sql", "sql-server-2008-r2", "" ]
I am working in SQL Server Management Studio 2008. I need to write a query that searches several fields in a table against a large list of words (about 50 words). My current idea is to simply write an `IN` clause to put all of my words in. However, creating this `IN` clause could become tedious due to the amount of wo...
You can create a table (let's say `word_table`) and store all your words inside it. Then you can simply do ``` SELECT x, y FROM Table1 WHERE x IN (SELECT word FROM word_table) OR y IN (SELECT word FROM word_table) ```
``` select t.* from your_table t left join word_table wx on wx.word = t.x left join word_table wy on wy.word = t.y where wx.word is not null or wy.word is not null ```
How to query against a large list of words with an IN clause
[ "", "sql", "sql-server", "" ]
I want to use WHERE in mysql join ``` SELECT user.name , course.name FROM `user` LEFT JOIN `course` on user.course = course.id; ``` i want to add `WHERE name='Alice'` in `user.name` i tried to do it via : ``` SELECT user.name WHERE name='Alice' , course.name FROM `user` LEFT JOIN `course` on user.course = course.id...
The syntax is wrong, the correct syntax is ``` SELECT FROM JOIN ON WHERE ``` So in your case it will be ``` SELECT a.name, b.name as bname FROM `user` a LEFT JOIN `course` b ON a.course = b.id WHERE a.name='Alice' ``` Note that i used an alias since two columns have the same name
Almost right. This should work fine: ``` SELECT u.name, c.name FROM `user` u LEFT JOIN `course` c on u.course = c.id WHERE u.name='Alice'; ``` I know, it's weird to think about, but that's actually how you do it. And I changed to `u` and `c` because it's neater to work with.
use WHERE in mysql join
[ "", "mysql", "sql", "join", "" ]
Hello Guys i am fairly new in the databases. I have 2 tables ``` 1 Tbl_name ID - Varchar Name - Varchar 2 Tbl_ref ID - Varchar Fid - Varchar ``` I want to get Names from `Tbl_name` if `Fid from Tbl_ref = '111-11'` any help welcome :)
``` SELECT N.NAME FROM Tbl_name N INNER JOIN Tbl_ref R ON N.ID = R.ID WHERE FID = '111-11'; ``` try this
With whatever i understand from your question, this is what you are looking for.. ``` SELECT N.NAME FROM Tbl_name N INNER JOIN Tbl_ref R ON N.ID = R.ID AND FID = '111-11' ``` I would also suggest you to refer to this link.. <http://www.w3schools.com/sql/>
SQL join 2 tables with conditons on other tables
[ "", "sql", "sql-server", "database", "" ]
I'm trying to do an innerjoin but when I do this in Sql it says: Unknown column 'evenement.id' in 'on clause'. How can I make this work? SQL join: ``` SELECT * FROM `evenement` INNER JOIN `evenementontvanger` ON `evenement.id` = `evenementontvanger.idEvent` ORDER BY `id` ``` my tables are-> Evenement: `...
You need to quote each identifier individually; ``` ON `evenement`.`id` = `evenementontvanger`.`idEvent` ```
The problem is that you have `evenement.id` between backticks. That makes it a single identifier, rather than two connected by a `.`. The following fixes the query and adds table aliases and fixes the next problem which is the ambiguous column in the `order by`: ``` SELECT * FROM evenement e INNER JOIN evenemento...
My inner join doesn't work Unknown column
[ "", "mysql", "sql", "join", "phpmyadmin", "" ]
I'm attempting to write a function for Access. I have some very basic coding skills, but almost no knowledge of VBA. When I attempt to call the function from an update query, I get the "JOIN expression not supported" error, and I can't figure out what the problem is. Here's the function: ``` Function PrimaryCampus(stu...
Try explicitly referencing the table and field in the join like so: ``` "SELECT COUNT(SSBSECT_SEQ_NUMB) " & _ "FROM SATURN_SFRSTCR " & _ "INNER JOIN SATURN_SSBSECT " & _ "ON SATURN_SFRSTCR.SFRSTCR_TERM_CODE = SATURN_SSBSECT.SSBSECT_TERM_CODE " & _ "AND SATURN_SFRSTCR.SFRSTCR_CRN = SATURN_SSBSECT.SSBSECT_CRN " & _ "WHE...
Looking [here](http://msdn.microsoft.com/en-us/library/office/ff820966%28v=office.15%29.aspx), it seems like you will have to specify a recordset type or it will assume you're trying to call a table rather than a query. Try: ``` Set rec = db.OpenRecordset("SELECT COUNT(SSBSECT_SEQ_NUMB) " & _ ...
Access 2010 VBA JOIN expression not supported
[ "", "sql", "vba", "ms-access", "inner-join", "" ]
``` select * from table where substring(username,1) >= 'A' and substring(username,1) <= 'C' and height_in_meters * 100 > 140 and height_in_meters * 100 < 170; ``` what are the possible methods to speed up the query? It runs quite slowly
`where username like '[A-C]%'` would allow index use (should one be present) on `username` as opposed to passing `username` through a function which would always prevent it.
There is not much you can optimize but ``` WHERE username >= 'A' AND username < 'D' AND height_in_meters > 1.4 AND height_in_meters < 1.7; ``` so you save the computation
Optimise substring sql query
[ "", "sql", "sql-server", "" ]
I like to get the percentage of a certain version. If stored the info in `mytable`: ``` ID | name | version =================== 1 | foo | 1.0 2 | bar | 1.0 3 | loo | 1.1 4 | zoo | 1.2 ``` I like to get this result ``` version | percentage ==================== 1.0 | 0.500 1.1 | 0.250 1.2 | 0.250 `...
This query should work: ``` select version, count(*) / const.cnt from mytable cross join (select count(*) as cnt from mytable) const group by version order by version; ```
Use `COUNT` ``` SELECT version, COUNT(version)/(SELECT COUNT(*) FROM table) FROM table GROUP BY version ```
Get percentage of appearance of a certain value in mysql
[ "", "mysql", "sql", "" ]
I'm trying to get the average price of all products, several of which are `NULL`. I want to know if when I use the following query: ``` SELECT AVG(Price) AS PriceAverage FROM Products; ``` if it is including the products that have `NULL` as a price or is it skipping them?
The only aggregate function that doesn't ignore NULL values is COUNT(\*). Even COUNT() ignores NULL values, if a column name is given. Read more about it here: <http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html>
`Null` values are ignored. If you want to include `Null` values in your average: ``` SUM(Price) / Count(*) ```
When using the AVG() SQL function, is NULL part of the average or is it ignored?
[ "", "sql", "" ]
Suppose I have following tables: T1,T2 and T3. How could I rephrase the following query using only left joins. ``` Select * From T1 Right join T2 On T1.FK2=T2.PK Right join T3 On T1.FK3=T3.PK ``` Following attempt is not correct: ``` Select * From T2 Left join T1 On T1.FK2=T2.PK Left join T3 On T1.FK3=T3.PK ``` T3...
Apparently brackets can help to order your joins. I wonder if this is really documented, i've found Nothing at first glance in the mysql docs. Following query is correct and does not have any subqueries: ``` Select T1.Id Ida, t2.id idb, T3.id idc FROM T3 LEFT JOIN (T2 LEFT JOIN T1 ON (T1.ID = T2.ID)) ON (T1....
The first way is just to reverse the order that the tables are mentioned: ``` Select * from t3 left outer join t2 on T1.FK3 = T3.PK left outer join t1 on T1.FK2 = T2.PK ``` But this won't work, because the first condition is on `t1` and not `t2`. And `t2` hasn't yet been defined. When working wit...
Transforming queries: right joins to left joins
[ "", "mysql", "sql", "database", "relational-database", "" ]
In our development environment we have long been using a particular backup and restore script for each of our products through various SQL Server versions and different environment configurations with no issues. Recently we have upgraded to SQL Server 2012 as our standard development server with SQL Compatibility Leve...
This issue is caused by different sector sizes used by different drives. You can fix this issue by changing your original backup command to: ``` BACKUP DATABASE MyDB TO DISK = N'D:\MyDB.bak' WITH INIT , NOUNLOAD , NAME = N'MyDB backup', STATS = 10, FORMAT ``` Note that I've changed NOFORMAT to FORMAT and remove...
All you have to do is back it up with a different name.
Backup a database on a HDD with a different sector size
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "backup", "" ]
I have a table where I want to combine two separate rows into one row. This is a product catalog that is storing information on separate rows. Here is the sample data and the expected results. Table name: `ProductCatalog` ``` Product_ID | Action | Date ----------------------------------------- 0001 | Adde...
I think the easiest way is conditional aggregation: ``` select pc.product_id, max(case when pc.action = 'Added' then pc.[date] end) as Added, max(case when pc.action = 'Removed' then pc.[date] end) as Removed from ProductCatalog pc group by pc.product_id; ``` You can also do this using `pivot`.
First what you need to do is to get data into two separate columns, after than you can wrap that in sub-select and group by `Product_id`, because only one of the `AddedDate` or `RemovedDate` will have value we can use `MAX` function to display that data, producing only 1 row per `Product_ID` ``` SELECT Product_id ...
Combine two rows in table using one column data
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm selecting all entries from first table which have certain category in second one. Those 2 are connected through ID, which is the same in both tables. I'm new at UNION and JOIN, so I'm wondering if I can do this without using those? Example: ``` SELECT * FROM entries, categories WHERE entries.id = cat...
This would work. You might as well type : ``` SELECT your fields FROM entries AS E INNER JOIN categories as C USING (id) WHERE C.category = 'default' ```
Try like this ``` SELECT * FROM entries INNER Join categories ON entries.id = categories.id WHERE categories.category = 'default' ```
Easiest way to select from 2 tables, with where condition in second
[ "", "mysql", "sql", "select", "" ]
I have tables that looks like this:- **tblConsuptionsFromA** > id  meter        date        total > 1      1      03/01/2014  100.1 > 2      1      04/01/2014  184.1 > 3      1      05/01/2014  134.1 > 4      1      06/01/2014  132.4 > 5      1      07/01/2014  126.1 > 6      1      08/01/2014  190.1 and...
The `UNION` operator is used to combine the result-set of two or more SELECT statements. ``` SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; ``` The document of UNION is here: <http://www.w3schools.com/sql/sql_union.asp> And `ROW_NUMBER()` returns the sequential number of a row within a...
Here's one way to do it: ``` SELECT COALESCE(a.source_id,b.source_id) as source_id, COALESCE(a.meter,b.meter) as meter, COALESCE(a.[from],b.[from]) as [from], COALESCE(a.[date],b.[date]) as [date], COALESCE(a.total,b.total) FROM (select source_id,meter,'b' as [from],[date],total from tblCons...
SQL Server: Join 2 tables, preferring results from one table where there is a conflict
[ "", "sql", "sql-server", "join", "" ]
I am trying to retrieve records from oracle 10g express. I want to execute : ``` select name|| '=' || id from literals where name='vge_1' ``` only when count(vge\_1) is equal to 1. else I want to display an error. I tried following query, but its giving ``` ORA-00905: missing keyword ``` THe query I tried is as ...
Try this [SQL Fiddle](http://sqlfiddle.com/#!4/fe716/33): ``` select distinct case when l2.c = 1 then l1.name || '=' || l1.id else 'Error' end as name_id from literals l1, ( select name, count(name) as c from literals where name = 'vge_1' group by name having count(name) = 1 ) l2 where l1....
Instead of the `case` add `HAVING count(name)=1` in the end of th query
Sql query to select records only when count(column)=1
[ "", "sql", "oracle10g", "case", "" ]
When I run my query as `INNER JOIN` between two tables, I get the correct result - 182 in all. However, when I run the query as `LEFT JOIN`, I get only 8 records back. Am I performing the join incorrectly? First the code: ``` select e.username, e.password, coalesce(r.access_level, 0) as orgid from e...
The trick with outer joins and conditions is to move the condition from the where clause into the join condtions clause: ``` select e.username, e.password, coalesce(r.access_level, 0) as orgid from employees e left join retired r on e.employeeid = r.employeeid and access_level=3 ``` The reason...
If `Access_Level` is a column in the `Retired` table then its value will be `NULL` for any rows in Employee that don't have a corresponding row in Retired. Those rows will then be filtered out by your WHERE clause as they *don't* have a `Access_Level` of 3. Moving that condition to the `ON` clause should be enough: ``...
My LEFT JOIN is not returning correct results. What am I doing wrong?
[ "", "sql", "sql-server", "join", "" ]
I know how to do this but I don't know how to do it without a loop. Basically, for each `CustomerID + PaymentID`, I want to populate the column `"SumOfAmount"` with the total. The total will repeat for each row of that `CustomerID + PaymentID`. ![](https://i.stack.imgur.com/WHa8I.png) How would I go about doing this...
Try using a [windowing function](http://technet.microsoft.com/en-us/library/ms189461.aspx): ``` SELECT ID, CustomerID, PaymentID, ItemID, DeductionBucketID, Qty, Amount, Deductions , SUM(Amount) OVER (PARTITION BY CustomerID, PaymentID) AS SumofAmount FROM ... ```
Assuming you have SQL Server 2005 or later, you can use the OVER keyword with the SUM aggregate to partition your data by the customer ID and payment ID. This code provides an example: ``` DECLARE @CustPaymentDetail AS TABLE ( CustomerID int, PaymentID int, ItemID int, Amount numeric(19,2) ); INSERT IN...
how to get the SUM of certain rows based on an ID and populate column with the value without using a loop
[ "", "sql", "sql-server", "" ]
I would like to give a user all the permissions on a database without making it an admin. The reason why I want to do that is that at the moment DEV and PROD are different DBs on the same cluster so I don't want a user to be able to change production objects but it must be able to change objects on DEV. I tried: ``` ...
*All commands must be executed while connected to the right database cluster. Make sure of it.* Roles are objects of the database *cluster*. All databases of the same cluster share the set of defined roles. Privileges are granted / revoked per database / schema / table etc. A role needs access to the *database*, obvi...
``` GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user; ```
PostgreSQL: Give all permissions to a user on a PostgreSQL database
[ "", "sql", "postgresql", "ddl", "privileges", "sql-grant", "" ]
I need to display records from mysql database where a particular column has only alphabets. eg, Table Name: data ``` column abcde 12345 xyz 123 ``` so the output should be abcde and xyz only. So far i tried using pattern match but no luck here is what is use yet `SELECT * FROM listing WHERE Zip LIKE '[^a-zA-Z...
Try this code ``` SELECT * FROM listing WHERE Zip REGEXP '^[A-z]+$' ```
Try regexp: ``` SELECT * FROM listing WHERE Zip REGEXP '^[a-zA-Z.]+$' ```
Mysql query to select a column with only alphabetical characters
[ "", "mysql", "sql", "" ]
I require some help with my very shaky sql skills. Say I have the following select statement: ``` SELECT DISTINCT p.ProjectId, p.Title, i.Name, p.StartDate, p.EndDate, ped.ProjectEthicsDocumentId, st.Description AS StatusText FROM dbo.Project p inner join dbo.WorkflowHistory w ON p...
You can move selecting institution name to a subquery. This way you it doesn't affect how other tables are joined. ``` SELECT DISTINCT p.ProjectId, p.Title, (SELECT TOP 1 i.Name FROM dbo.Institution i INNER JOIN dbo.ProjectInstitution pi ON i.InstitutionId = pi.InstitutionId WHERE pi.ProjectId =...
The easiest way is probably with the `row_number()` function: ``` select * from (SELECT DISTINCT p.ProjectId, p.Title, i.Name, p.StartDate,p.EndDate, ped.ProjectEthicsDocumentId, st.Description AS StatusText, row_number() over (partition by p.ProjectId order by i.InstitutionId) as seqnum ...
Sql join 1 instance
[ "", "sql", "sql-server", "select", "join", "distinct", "" ]
How to get dynamic Order by based on the parameter in Oracle sql,Base on the condition any one of the Dynamic Order by to be binded ,What is wrong with my query please help to solve this.Parameter value will be passed dynamically for user. ``` SELECT actionstatus, id FROM rdt_orderdetail WHERE id IN (45565,...
Try something like this: ``` SELECT actionstatus, id FROM rdt_orderdetail WHERE id IN (45565,44033,45761,45543,45495,43472,42462,43477) order by (CASE WHEN ':user' = 'supplier THEN id ELSE actionstatus END) ``` [Example fiddle](http://www.sqlfiddle.com/#!2/16441/2)
You want to use dynamic order ? Then you'll have to use dynamic SQL :-) ``` create or replace function GET_DETAILS(iField in varchar2) return sys_refcursor is aQuery varchar2(1000); aCursor SYS_REFCURSOR; begin aQuery := 'select actionstatus,id from rdt_orderdetail where id in (45565,44033,45761,455...
Dynamic Order by using Case in SQL
[ "", "sql", "oracle", "" ]
In a MySQL calendar, items are placed using start+duration. Both integers, BUT: Start looks like this: `YYYYMMDDhhmm` while duration is just a number of minutes. Before inserting a new item I have to ensure it doesn't overlap existing items. **The hard part**: Is any existing item's start+duration > the my new ite...
One way to convert to a DATETIME, from integer "start" representation YYYYMMDDHHMM and adding an integer "duration" in minutes, is to just add a seconds portion (change from 12 digits to 14 digits) by multiplying by 100, and then add an interval, and MySQL will implicitly convert the integer value to DATETIME. For exam...
> *How to (YYYYMMDDhhmm + minutes) and return a valid YYYYMMDDhhmm (in SQL)?* One way to do it ``` SELECT t.*, 1 * DATE_FORMAT(STR_TO_DATE(start, '%Y%m%d%H%i') + INTERVAL duration MINUTE, '%Y%m%d%H%i') end FROM table_name t ``` or without string manipulation ``` SELECT t.*, ...
Time calculation with SQL
[ "", "mysql", "sql", "" ]
I am new to SQL and I cannot figure out why my SQL result returns all data from the wrong table. I want to receive all data from product table but I want to filter the results so it does not show those results that have some value in another table. My SQL statement is: ``` SELECT * FROM orders JOIN product...
You can get products which don't have orders of a certain criteria (`order_date != somedate`) like this: ``` SELECT p.* FROM products p LEFT JOIN orders o ON o.product_id = p.product_id AND order_date != somedate WHERE o.id IS NULL ```
Not sure I got your question right, but you can try this: ``` SELECT p.* FROM orders JOIN products ON orders.product_id=products.product_id WHERE order_date<>somedate; ```
SQL join returns all values from the wrong table
[ "", "mysql", "sql", "" ]
I would like to join 3 tables together and have it return the data where the results from one would be null. tblCustomer is the main table that will always have the required result. It would then be tied to 2 other tables tblEvents and tblPending and should return with the data for either. Example ``` tblCustomer.Cu...
If you only want one of event or pending you may want the union of two joins, e.g. ``` SELECT tblCustomer.CustomerID, tblEvents.EventID, null AS tblPending.PendingID FROM dbo.tblCustomer LEFT OUTER JOIN dbo.tblEvents ON dbo.tblEvents.CustomerID = dbo.tblCustomer.CustomerID UNION SELECT tblCustomer.CustomerID, null AS...
what you want is a FULL OUTER JOIN, which doesnt exist in mysql, so you have to do your left outer join and union with a right outer join ``` LEFT OUTER JOIN dbo.tblCustomer ON dbo.tblEvents.CustomerID = dbo.tblCustomer.CustomerID LEFT OUTER JOIN dbo.tblPending ON dbo.tblCustomer.CustomerID = dbo.tblPending.CustomerI...
SQL outer Join 3 tables merging data
[ "", "sql", "sql-server", "join", "" ]
I know how to get the last record of a group but I also need to get the second to last record. How can I do this? here is my code for getting the last record. ``` select job qjob, max(id) qid from sqbclog group by job ```
``` SELECT * FROM ( select job AS qjob , id AS qid ,ROW_NUMBER() OVER (PARTITION BY JOB ORDER BY ID DESC) AS RN from sqbclog )Sub WHERE rn <= 2 ``` This query will return last two records but if you only need the 2nd last record then in where clause use where en = 2 else leave it as it is.
**This should do it !** ``` select * from sqbclog where id not in ( select top ( (select count(*) from sqbclog ) - 2 ) id from sqbclog ) ```
getting second to last record per group in SQL
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I am pretty new to delphi and I would like to ask how can I create a correct SQL statement / SQL string in delphi. I have tried something like this: ``` sql:='use [TestovaciaDb] INSERT INTO [dbo].[client]([Meno],[Priezvisko]) VALUES('+name+','+surname+')'; ``` I am using MS SQL server 2012 But I am getting a excep...
Use parameterized queries. You set the database in your ConnectionString, so you don't need to `use' it in your query. ``` ADOQuery1.SQL.Text := 'INSERT INTO [dbo].[client] ([Meno],[Priezvisko]) ' + 'VALUES(:Meno, :Priezvisko)'; ADOQuery1.Parameters.ParamByName('Meno').Value := Edit1.Text; ADOQue...
Remove the `use [xxx]` at the begining of the statement. The connection you use must be already configured to point to the correct database. Just like many others said, avoid creating your sentences by using constants, instead, use paramenters.
How to create correct SQL statement in delphi
[ "", "sql", "sql-server", "delphi", "" ]
I have the following query which returns the correct results but I am aware of the overheads associated with subqueries in a WHERE IN clause. ``` SELECT event_start_date FROM events JOIN joins ON event_id = join_event_id JOIN groups ON join_type_id IN (SELECT group_id ...
MySQL does [optimize uncorrelated subqueries](http://dev.mysql.com/doc/refman/5.0/en/optimizing-subqueries.html) (which you have in your example): > MySQL executes uncorrelated subqueries only once. Use EXPLAIN to make > sure that a given subquery really is uncorrelated. If your subquery returns only one result, be s...
try this: ``` SELECT event_start_date FROM events JOIN joins ON event_id = join_event_id join view_groups on ............condition here JOIN groups ON join_type_id = view_groups.group_id WHERE user_id = 3 AND event_start_date >= now() GROUP BY event_start_date; ```
Re-writing query to avoid WHERE IN with a subquery
[ "", "mysql", "sql", "subquery", "where-in", "" ]
I'm trying to create a temp table and process two data flows using the temp table. It is in a sequence container and if I just execute the container it run perfect but when the entire package is ran it returns this error: > Information: 0x4004300A at V-AccidentCodesBase, SSIS.Pipeline: > Validation phase is beginning....
I ended up solving the problem which was overloading tempDB. When I slowed the process down to one command to tempDb at a time it all ran through smoothly.
I would set the DelayValidation property to True. You may get away with just setting this on the Sequence Container, or you may need to repeat that setting on child objects, e.g. your Data Flow Task.
SSIS failed validation and returned validation status "VS_ISBROKEN"
[ "", "sql", "sql-server", "validation", "ssis", "" ]
I was wondering if it is possible to write a query that returns a field only if that field contains a certain data type. So for example, I could want to return all fields with data type VARCHAR from a search, or data type BIGINT. Not just search for fields that contain numbers or letters. Here is an example of my psu...
The Data Type of any field in SQL is set when the field (aka column) is created. So I think you might be intending to ask whether or not a field's value can be converted (or cast) to another type. This will depend on who is doing the conversion, and what they are capable of: If you store the string "3/1/2014" who dete...
You can exclude non-digits ``` WHERE ra.TRADE_REP NOT LIKE '%[^0-9]%' ```
Is it possible to query for a specific data type?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have data like this `1,2,3,4-8,10,11` I want split the data into rows with these 2 rules : 1. The `,` will only split the data into rows. Ex 1,2,3 become : ``` 1 2 3 ``` 2. The `-` will split into series number. Ex 4-8 become : ``` 4 5 6 7 8 ``` How can a SQL query do that? Pl...
This will work as long as your intervals are less than 2048 (let me know if that numbers can go higher) and you @data follow your current syntax: ``` declare @data varchar(50) = '1,2,3,4-8,10,11' ;with x as ( SELECT t.c.value('.', 'VARCHAR(2000)') subrow FROM ( SELECT x = CAST('<t>' + ...
``` CREATE FUNCTION dbo.MultipleDelemiterSplit ( @List NVARCHAR(MAX), @Delemiter1 Varchar(100), @Delemiter2 Varchar(100) ) RETURNS TABLE AS RETURN ( SELECT Item = FirstSet.cnt.value('(./text())[1]', 'nvarchar(4000)') FROM ( SELECT x = CONVERT(XML, '<cnt>' + RE...
Split data in sql with multiple delimiters ( , and - ) with owns rule
[ "", "sql", "sql-server", "t-sql", "split", "numbers", "" ]
I have a replace statement that does something like this: ``` SELECT Distinct Forenames, Surname, dbUSNs.DateOfBirth, Datasetname, dbUSNs.MoPIGrade, SourceAddress, VRM, URNs FROM Person WHERE ( Replace(Replace(Replace(Replace(Replace(Replace(Replace (Replace(Replace(Replace(Replace(Replace(Replace(Re...
The problem isn't that `REPLACE` is "too slow", but that using it at all makes that part of the query *unsargable*, meaning that it can't use an index. [Wikipedia: Sargable](http://en.wikipedia.org/wiki/Sargable) Basically you've forced a tablescan / indexscan, from top to bottom. On top of that you have the overhead...
If you want to simply remove all special characters it's easier to specify the valid characters and use a function to perform the cleansing. This shows you how to clean the string to alphanumeric characters and spaces `'%[^a-z0-9 ]%'` ``` DECLARE @Temp nvarchar(max) ='O''Rielly la/.das.d,as/.d,a/.da.sdo23eu89038 !£$$...
SQL replace statement too slow
[ "", "sql", "sql-server", "" ]
I have a problem where I want to replace characters I am using `replace` function but that is not giving desired output. Values of column table\_value needs to replaced with their fill names like E - Email P - Phone M - Meeting ![enter image description here](https://i.stack.imgur.com/0hjtN.jpg) I am using thi...
The below will work (*even it's not a smart solution*). ``` select table_value, replace(replace(replace(replace(table_value, 'M', 'MXXTING'), 'E', 'XMAIL'), 'P', 'PHONX'), 'X', 'E') required_value from foobar ```
You can do it using CTE to split the table values into E, P and M, then replace and put back together. I assumed each record has a unique identifer `Id` but please replace that with whatever you have. ``` ;WITH cte AS ( SELECT Id, SUBSTRING(table_value, 1, 1) AS SingleValue, 1 AS ValueIndex FROM replacetable ...
Replace multiple characters in SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a select sql command like under: ``` SELECT Title,G ,K ,M, CASE WHEN (tblMain.G <> 0 AND tblMain.K <> 0 AND tblMain.M = 0) then (select sum(price) from tblCustomer where tblCustomer.G = tblMain.G AND tblCustomer.K = tblMain.K) WHEN (tblMain.G <> 0 AND tblMain.K = 0 AND tblMain.M = 0) then (select su...
``` with SubQuery as ( SELECT Title,G ,K ,M, CASE WHEN (tblMain.G <> 0 AND tblMain.K <> 0 AND tblMain.M = 0) then (select sum(price) from tblCustomer where tblCustomer.G = tblMain.G AND tblCustomer.K = tblMain.K) WHEN (tblMain.G <> 0 AND tblMain.K = 0 AND tblMain.M = 0) then (select sum(pri...
You cannot reuse the aliases this way. You can use a subquery tho: ``` SELECT Title,G ,K ,M, B1, S1, (S1 - B1) AS Result FROM (SELECT Title,G ,K ,M, CASE WHEN (tblMain.G <> 0 AND tblMain.K <> 0 AND tblMain.M = 0) then (select sum(price) from tblCustomer where tblCustomer.G = tblMain.G AND tblCustomer.K = tblMa...
How Use Custom Column in Select Sql Statement
[ "", "sql", "sql-server", "" ]
I've got a table in SQL holding Alarm data from an iFix SCADA system that is designed as follows: ``` CREATE TABLE [dbo].[FIXALARMS]( [ALM_ID] [int] IDENTITY(1,1) NOT NULL, [ALM_NATIVETIMEIN] [datetime] NOT NULL, [ALM_PHYSLNODE] [char](8) NOT NULL, [ALM_TAGNAME] [varchar](32) NOT NULL, [ALM_VALUE] ...
If you don't need the data realtime, use SSIS to set up an ETl process to transform the data to your normalized form. If you must have the data realtime, then use triggers but use them very carefully and make sure they handle sets of data. Sql server triggers should never be expected to handle only one row of data. Yo...
Assuming you go with a trigger, most likely it will be breaking incoming data into multiple tables, right? This is a viable approach. If the incoming data matches the schema of that table, you do a "regular" trigger. consider INSTEAD OF triggers, if incoming data schema doesn't perfectly match your schema. In any case...
SQL Trigger vs Other Options Performance
[ "", "sql", "sql-server", "t-sql", "triggers", "" ]