Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
While running this query ``` update p_leave_allocation_14122015 set 'month' + @actualMonth = @actualleavedays where year = @actualYear and emp_card_no = @emp_card_no ``` I get an error: > Incorrect syntax near 'month'. The table `p_leave_allocation_14122015` has columns like `month1`, `month2`, `month3`,**......
*You should try something like below*, ``` DECLARE @sql NVARCHAR(MAX); SET @sql = N'update p_leave_allocation_14122015 SET MONTH'+CAST(@actualMonth AS VARCHAR(2)) +' = ' + CAST(@actualleavedays AS VARCHAR(10))+ ' WHERE YEAR = '+ CAST(@actualYear AS VARCHAR(4))+ ' AND emp_card_no = '+C...
You need to use `dynamic query` to do this ``` DECLARE @sql NVARCHAR(max) = '' SET @sql = 'update p_leave_allocation_14122015 set month' + Cast(@actualMonth AS VARCHAR(10)) + ' = ' + Cast(@actualleavedays AS VARCHAR(10)) + ' where year = @actualYear and emp_card_no = @emp...
Incorrect syntax near 'month' with dynamic number
[ "", "sql", "sql-server-2005", "" ]
I have a mysql table with this structure: ``` CREATE TABLE `item_rate` ( `id` int(11) NOT NULL AUTO_INCREMENT, `item` int(11) NOT NULL, `ip` int(32) NOT NULL, `rate` int(1) NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `item` (`item`), CONSTRAINT `it...
Try this: ``` SELECT item, FLOOR(SUM(rate * ratecount) / SUM(ratecount)) AS cnt FROM (SELECT item, rate, COUNT(id) ratecount FROM item_rate GROUP BY item, rate ) AS A GROUP BY item; ``` To fetch ip related details check below query: ``` SELECT item, FLOOR(SUM(rate * ratecount) / SUM(ratecount)) AS ...
It looks like you simply want the average rating for an item. This is most easily written as: ``` select item, avg(rate) from item_rate group by item; ``` If you want this to two decimal places, cast as a `decimal` or use `format()`: ``` select item, cast(avg(rate) as decimal(8, 2)) as avg_rate from item_rate group ...
How do I get the average 'rate' from my below MySQL table?
[ "", "mysql", "sql", "select", "group-by", "sum", "" ]
I have a query that returns results grouped by the hour, like so. ``` SELECT COUNT(*) FROM (`shipped_products`) WHERE HOUR(timestamp) = 8 ``` The issue is, I get different results on localhost than on the live server. The data is exactly the same on both (UTC). I believe that my localhost database is New York while t...
You could just set the session timezone (or the global time zone) to UTC, [as described in the docs](https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html). ``` set time_zone = '+00:00'; ``` Then `HOUR` and other functions will interpret `timestamp` types in UTC. See also the differences between `timestamp` ...
Try the [`CONVERT_TZ()` function](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_convert-tz): ``` SELECT COUNT(*) FROM (`shipped_products`) WHERE HOUR(CONVERT_TZ(timestamp, 'UTC', 'America/New York')) = 8 ``` The manual warns: > ## Note > > To use named time zones such as `'MET'` or `'...
mysql HOUR() accounting for timezones
[ "", "mysql", "sql", "timezone", "" ]
Is there a way to correct this query so that it works with `ONLY_FULL_GROUP_BY` enabled? ``` SELECT LOWER(s) AS lower_s, SUM(i) AS sum_i FROM t GROUP BY 1 HAVING LENGTH(lower_s) < 5 ``` It gives the error message > Non-grouping field 'lower\_s' is used in HAVING clause [Fiddle](http://sqlfiddle.com/#!9/749fb9/1)
why dont you just use `where LENGTH(LOWER(s)) < 5` It seems the using of `having` is not right here. According to [having sql wiki](https://en.wikipedia.org/wiki/Having_(SQL)) > A HAVING clause in SQL specifies that an SQL SELECT statement should only return rows where aggregate values meet the specified conditions....
No need to use **HAVING** clause in your query. Check below query that will satisfy your requirement. Try this: ``` SELECT LOWER(s) AS lower_s, SUM(i) AS sum_i FROM t WHERE LENGTH(LOWER(s)) < 5 GROUP BY 1; ```
MySQL error: Non-grouping field is used in HAVING clause
[ "", "mysql", "sql", "select", "group-by", "having", "" ]
I have a project where I need to record answers to a questionnaire that has 50+ questions. Each question is associated with numbers 1 to 5. So the data for each questionnaire filled out is something like ``` Username : "Bob", "Question 1" : 1, "Question 2" : 1, "Question 3" : 5, . . . "Question N" : 2 ``` where t...
The direct answer to your question is: "No, you do not serialize the information into a giant `varchar()` column." That is easy, because such serialization is almost never the right thing to do in SQL. The right thing is a junction table. However, apart from that, a data structure for surveys is quite hard to implemen...
``` UserID QuestionID Answer -------------------------------- 1238 1 2 1238 2 5 ... 1238 50 3 ```
What type of database design do I use for a questionnaire that has a lot of questions?
[ "", "sql", "sql-server", "t-sql", "database-design", "" ]
The following is the "pc" table which contains details about pc. ``` user=> SELECT * FROM pc; code | model | speed | ram | hd | cd | price ------+----------+-------+------+------+-----+--------- 101 | Imac | 2000 | 4096 | 500 | 16x | ₹550.00 102 | G450 | 1500 | 2048 | 500 | 8x | ₹450.00 (2 ...
``` SELECT AVG(price::numeric) FROM pc; ``` or As per PostgreSQL 8 .4's [Monetary Types](http://www.postgresql.org/docs/8.4/static/datatype-money.html) ``` select avg(regexp_replace(price::text, '[$,]', '', 'g')::numeric) from pc ```
You can do: ``` SELECT AVG(price::money::numeric::float8) FROM pc; ```
Average value for Money Datatype
[ "", "sql", "regex", "postgresql", "average", "postgresql-8.4", "" ]
I have column with type `BOOLEAN` At first (on `INSERT`), value would be always `FALSE`, only after may be updated column as `TRUE` So question is: make this column `NOT NULL DEFAULT FALSE`, or make this column `DEFAULT NULL` and then update as `TRUE` (and if then also would be reversing update, set column `NULL` and...
It makes no meaningful difference to storage. Depending on other nullable columns, we're talking at most a single byte if this column happens to overflow the nullable bitmap to the next byte, but in all likelihood it won't add any storage at all. For performance (as well as programmer productivity/maintenance), it dep...
If you want to assume FALSE unless specifically set to TRUE, then use `NOT NULL DEFAULT FALSE`. It also depends on how you are using this column. If you only test where column = TRUE, then don't think it will matter. The point being that NULL is not equal to FALSE.
FALSE and TRUE vs NULL and TRUE
[ "", "sql", "postgresql", "plpgsql", "postgresql-9.5", "" ]
I was reading some Oracle SQL resources and I found this SQL code: ``` SELECT e.ename AS "NAME", e.sal AS "Salary", e.deptno, AVG(a.sal) dept_avg FROM emp e, emp a WHERE e.deptno = a.deptno AND e.sal > ( SELECT AVG(sal) FROM emp WHERE deptno = e.deptno ) GR...
If you remove `GROUP BY` and use `SELECT *`, you'll see what's happening. `emp` is joined on itself, every employee with salary higher than average is joined with every other employee in his department, making an awful lot of rows. Then, from that data, average salary (from every other worker in dept) is counted again...
Maybe re-writing with more modern conventions makes it clearer? ``` WITH avgbydept as ( SELECT deptno, avg(sal) as avgsal FROM emp GROUP BY deptno ) SELECT e.ename AS "NAME", e.sal AS "Salary", e.deptno, AVG(a.sal) dept_avg FROM emp e JOIN emp a ON e.deptno = a.deptno JOIN avgbydept a...
the grouping column for an aggregate function is as a join condition?
[ "", "sql", "oracle11g", "" ]
I know similar questions had been asked before, but none of them had this same conditions and their answers didn't work for this case. The table containing the messages looks like this: ``` id | owner_id | recipient_id | content | created 1 | 1 | 2 | Hello | 2015-12-08 20:00 2 | ...
``` select t.* from t join (select user, max(created) m from ( (select id, recipient_id user, created from t where owner_id=1 ) union (select id, owner_id user, created ...
This should do the trick: ``` $joins = array( array('table' => 'conversations', 'alias' => 'Conversation2', 'type' => 'LEFT', 'conditions' => array( 'Conversation.id < Conversation2.id', 'Conversation.owner_id = Conversation2.owner_id', ) ), array('ta...
Get last message from each conversation
[ "", "mysql", "sql", "database", "relational-database", "" ]
I want to see only grant privileges on a particular procedure in MySQL. [This documentation](http://dev.mysql.com/doc/refman/5.7/en/show-grants.html) shows all grants. Is there a way to see grants only for a particular procedure in a db. The below command gives all grants including select, update etc. : ``` SHOW GRA...
Try this: ``` SELECT * FROM mysql.procs_priv A WHERE A.Db = 'DatabaseName' AND A.User = 'root' AND A.host = 'localhost' AND A.Routine_name = 'ProcedureName' AND FIND_IN_SET('Grant', A.proc_priv); ```
Suppose, you want to create a procedure called MyFirstProc and you wanted to grant ALL users the ability to EXECUTE this procedure. You would run the following GRANT statement: ``` GRANT EXECUTE ON PROCEDURE MyFirstProc TO '*'@'localhost'; ```
How to view only procedure related grants in MySQL?
[ "", "mysql", "sql", "select", "privileges", "sql-grant", "" ]
What I'm trying to do is get the name of the city with biggest number of orders. Seems simple enough, yet when I run this code (I had to use CTEs), I get only the number of orders, no city name. ``` WITH CityOrder AS ( SELECT City FROM Person.Address JOIN Sales.SalesOrderHeader ON ShipToAddressID = A...
Order your results and take top 1 but with ties in case several cities have same number of orders: ``` ... SELECT TOP 1 WITH TIES * FROM CitiesOrders ORDER BY NoOfOrders DESC ```
Try this! ``` select top 1 * from ( SELECT City,count(1) as x FROM Person.Address JOIN Sales.SalesOrderHeader ON ShipToAddressID = AddressID group by City ) order by x desc ```
SQL Select with CTE
[ "", "sql", "sql-server", "" ]
I've got me this nice table. ``` create table Records ( Id uniqueidentifier primary key, Occasion datetime not null, Information varchar(999) default ' ' ) ``` When I execute the first line line below, I get an error. When I execute the second, I see *NULL* in the cell. How should I insert stuff into the table ...
By using the `DEFAULT` keyword: ``` INSERT INTO Records VALUES (newid(), CONVERT(varchar(21), getdate(), 121), DEFAULT) ``` Or, better, by specifying the exact columns with the `INSERT` statement ``` INSERT INTO Records (Id, Occasion) VALUES (newid(), CONVERT(varchar(21), getdate(), 121)) ``` Or: ``` INSERT INTO ...
``` insert into Records ( Id Occasion ) values (newid(), convert(varchar(21), getdate()), 121)) ``` Try this. when you don't specify column names in insert query, sql-server expects values for all the columns. that is why your first query is throwing error as you have supplied value for two columns only, wherea...
How not to store a value in a column?
[ "", "sql", "sql-server", "" ]
I am not very friendly with SQL so I need to write a SQL update/delete query on a table. The requirement is as below. Table A: Col1(PK)     Col2            Col3            Quantity 1                 Code1        Value1            5 2                 Code2       Value2             2 3                 Code1         ...
You will need to do this in two parts, and if you want to ensure the integrity of the data, the two parts should be wrapped in a transaction. The first part updates the required rows' `Quantity`, the second deletes the now duplicated rows. ``` BEGIN TRANSACTION UPDATE TableA SET Quantity=upd.Quantity FROM TableA a I...
Use this: ``` select * from (select *, sum(Quantity) over (partition by col2,col3) as Quantity from tableA ) t ```
Writing SQL Query to query and update same table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to create a report to show me the last date a customer filed a ticket. Customers can file dozens of tickets. I want to know when the last ticket was filed and show how many days it's been since they have done so. The fields I have are: Customer, Ticket\_id, Date\_Closed All from the Same table "Ticket...
``` select Customer, datediff(day, date_closed, current_date) as days_since_last_tkt from (select *, rank() over (partition by Customer order by "Date_Closed" desc) as date_order from tickets) zd join tickets t on zd.date_closed = t.date_closed where zd.date_order = 1 ``` Or you can simply do ``` select customer, da...
This should be simple enough, ``` SELECT customer, MAX (date_closed) last_date, ROUND((SYSDATE - MAX (date_closed)),0) days_since_last_ticket_logged FROM emp GROUP BY customer ```
Days Since Last Help Ticket was Filed
[ "", "sql", "amazon-redshift", "domo", "" ]
I'm trying to sort using the months name, when I have it in numbers everything is working, but when I try to make a select like this ``` SELECT DISTINCT CONVERT(nvarchar(50), DATENAME(m, date) + ', ' + DATENAME(yyyy,date)) as date From MyTable ``` In my output I have something like this ``` August, 2015 July, 2015...
Just embed the query into subquery and select month number along with your string: ``` DECLARE @t TABLE ( [date] DATE ) INSERT INTO @t VALUES ( '20150701' ), ( '20150701' ), ( '20150801' ), ( '20150901' ) SELECT [date] FROM ( SELECT DISTINCT CONVERT(NVARCHAR(50), DAT...
You should set a order criteria that you must have in the selected list. Try something like this: ``` SELECT DISTINCT CONVERT(nvarchar(50), DATENAME(m, date) + ', ' + DATENAME(yyyy,date)) as date, year(date) * 100 + month(date) as ordercrit From MyTable order by ordercrit ``` The `ordercrit` sh...
Sort by distinct date in MSSQL
[ "", "sql", "sql-server", "datetime", "" ]
I have a query and i want different conditions to be used as per value in a column. ``` SELECT * FROM com140 cm WHERE cm.csnstar IN (90) ``` but the problem comes because i want this to happen. when `cm.csnrsncde IN (135,177)` i want this condition to execute ``` AND cm.duedate > (SELECT MAX(e.dte1) ...
Code that you added should work ``` SELECT * FROM com140 cm WHERE cm.csnstar = 90 AND ((cm.csnrsncde IN ( 135, 177 ) AND cm.duedate > (SELECT Max(e.dte1) FROM events e WHERE e.ispec = 'FI560' AND e.inrtyp = 'RVP' AN...
Try this `Where` clause ``` SELECT * FROM com140 cm WHERE cm.csnstar = 90 OR ( cm.csnrsncde IN ( 135, 177 ) AND cm.duedate > (SELECT Max(e.dte1) FROM events e WHERE e.ispec = 'FI560' AND e.inr...
using different condition based on column value possible by switch case
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle10g", "" ]
The following is the "printer" table which contains details about printer. ``` user=> SELECT * FROM printer ; code | model | color | type | price ------+-----------+-------+--------+------------ 1002 | ProXPress | y | laser | ₹20,000.00 1003 | M1136 | y | jet | ₹100.00 1004 | Air1000...
*column "printer.code" must appear in the GROUP BY clause or be used in an aggregate* means that columns selected that aren't in an aggregate function (MIN is an aggregate function) must be in a group by. So you need to add `GROUP BY code,model` to the end as those columns are in the select but they aren't in a aggreg...
You can `INNER JOIN` the `printers` table to a subquery table containing the minimum price whose record(s) you want to display. ``` SELECT p1.code, p1.model, p1.price FROM printer p1 INNER JOIN ( SELECT MIN(price) AS minPrice FROM printer WHERE color='y' ) p2 ON p1.price = p2.minPrice WHERE p1.color='y' ``...
What is the use of Group by clause
[ "", "sql", "postgresql", "group-by", "" ]
I can't find solution, I'm trying to take in my database date of event that are 10 days after now. I tried : ``` SELECT * FROM XXX.Vente WHERE date > (now()+40); ``` and : ``` SELECT * FROM LeVigneau.Vente WHERE date > now()+INTERVAL 10 DAY; ``` But it doesn't work. Du you have an idea ? Thanks a lot
You have to use backticks on date, that because `DATE` is [reserved keyword](https://dev.mysql.com/doc/refman/5.5/en/keywords.html) and `DATE_ADD` function in following: **Syntax** ``` DATE_ADD(date,INTERVAL expr type) ``` **Query** ``` SELECT * FROM LeVigneau.Vente WHERE `date` > DATE_ADD(now(), INTERVAL 10 DAY); ...
For exactly 10 days: ``` SELECT * FROM LeVigneau.Vente WHERE `date` = DATE_ADD(now(), INTERVAL 10 DAY); ``` All other solution give more then 10 days, not exactly 10 days. for 10 days or more: ``` SELECT * FROM LeVigneau.Vente WHERE `date` >= DATE_ADD(now(), INTERVAL 10 DAY); ```
SQL - NOW() + 10 days
[ "", "mysql", "sql", "database", "" ]
I have tables with T1(user) ``` Id Name CourseIds 1 Joel 1,2,3 2 Jeff 2,3,4 ``` T2(courses) ``` CourseId CourseName 1 C# 2 Javascript 3 SQL 4 VB ``` I have to join the two tables and find out the count of each courses - learned by a user (group by) like (result table) ``...
First, you should fix your data structure. Storing lists of ids in a comma delimited list is bad for many reasons: * Storing numbers as strings is bad. * Storing multiple values in a single field is bad. * Not being able to declare foreign key relationships is bad. * Such lists cannot take advantage of indexes. * Junc...
``` With cte(courseids,si,ei) As( Select courseids, 1, charindex(',', courseids) From user Union all Select courseids, Cast( 1 +ei as int), Charindex(',',courseids,1+ei) From cte Where ei >0 ) Select substring(courseids,si, case when ei>0 then ei- si else Len(co...
How to group by comma delimited column in mssql?
[ "", "sql", "sql-server", "" ]
I am using cursor on below temporary reultset ``` SELECT price FROM flight where source1='delhi' and dest='Bangkok'; ``` I want to find minimum ticket price of flight on above route. How to do this?
Try this, **ORDER BY** AND **LIMIT** ``` SELECT `price` FROM flight WHERE `source1` = 'delhi' AND `dest` = 'Bangkok' ORDER BY `price` ASC LIMIT 1 ```
Use **ORDER BY** clause to order your desired result. Try this: ``` SELECT price FROM flight WHERE source1='delhi' AND dest='Bangkok' ORDER BY price ASC; ``` **OR** If you want only minimum price then Use **LIMIT** also. ``` SELECT price FROM flight WHERE source1='delhi' AND dest='Bangkok' ORDER BY price ASC...
how to find minimum value from result set using cursor in mysql?
[ "", "mysql", "sql", "select", "cursor", "sql-order-by", "" ]
I am having a bit of trouble dynamically creating a table and inserting into it. I have tried this multiple ways and cannot produce a desirable outcome. See below for a simplified version of what I am trying to do. Note that this is only one attempt - I have tried others as well (such as `INSERT INTO [table] EXEC(@exe)...
You need to declare as: ``` DECLARE @sqlText nvarchar(1000) ``` Other way it has length 1 by default. And since you have new line in the beginning of statement it doesn't throw syntax exception(your query contains only new line symbol and it is legal). Delete new line and you will get an error. <https://msdn.microso...
I was able to successfully test your script when I changed this: ``` DECLARE @sqlText nvarchar ``` To this: ``` DECLARE @sqlText nvarchar(max) ```
TSQL - Dynamic Create Table and Insert
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "" ]
I have a set of data I am wanting to report on (in Oracle 12c). I am wanting to show the sum of certain groupings, based on the value of the 'ITEM' column. If ITEM = ('A', 'B' or 'C'), then they get "grouped" together and the values for columns Cost1 and Cost2 are summed up. This is called "Group1". Group2 contains ITE...
The `CASE` statement is good for this type of one-off value transformation: ``` SELECT Year, CASE WHEN Item IN ('A', 'B', 'C') THEN 'Group1' WHEN Item IN ('D', 'E', 'F') THEN 'Group2' ELSE 'Others' END AS Item, SUM(Cost1), SUM(Cost2) FROM myTable GROUP BY Year, CASE WHEN Item IN ('A', 'B', ...
Look like you want `Group By` query: ``` select Year, case when item = 'A' or item = 'B' or item = 'C' then 'Group1' else 'Group2' end as Item Sum(nvl(Cost1, 0)) as Cost1, -- note NVL to prevent nulls from summing Sum(nvl(Cost2, ...
Oracle - How to sum related items?
[ "", "sql", "oracle", "" ]
I am having following data in a table ``` **TEAM NAME** Germany Holland Scotland Brazil ``` I AM Expecting data to be like below with same order, Please help ``` **ScheduledMatches** Germany VS Holland Germany VS Scoltland Germany VS Brazil Holland VS Scoltland Holland VS Brazil Scoltland VS Brazil ``` Thanks Vija...
``` DECLARE @t TABLE (Team VARCHAR(100)) INSERT INTO @t (Team) VALUES ('Germany'), ('Holland'), ('Scotland'), ('Brazil') ;WITH cte AS ( SELECT *, RowNum = ROW_NUMBER() OVER (ORDER BY 1/0) FROM @t ) SELECT t2.Team + ' vs ' + t1.Team FROM cte t1 JOIN cte t2 ON t1.RowNum > t2.RowNum ``` outp...
You can first calculate `ROW_NUMBER` for each team and use self join with `<` based on calculated `rn`: ``` CREATE TABLE #teams(name VARCHAR(100)); INSERT INTO #teams(name) VALUES('Germany'), ('Holland'), ('Scotland'), ('Brazil'); ;WITH cte AS ( SELECT *, rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM #teams ...
@SQL With single column i need to get below mentioned output like below
[ "", "sql", "sql-server", "" ]
I want to get ID value from mySQL table. For example :Get id from Second row or Third row. How can I do this? ``` SELECT Id From myTable --------- ; ``` What is the second row syntax?
If you want to fetch second row then use `LIMIT 2, 1` and if you want 3rd row then use `LIMIT 3, 1`. Try this: ``` SELECT Id FROM myTable ORDER BY Id LIMIT 2, 1; ```
2 ways to do that... Return 1 record, start from second record ``` select id from table_name limit 2,1 ``` Fetch 10 records, leave first 15. ``` SELECT * FROM Orders LIMIT 10 OFFSET 15 ```
How can I get ID from MYSQL
[ "", "mysql", "sql", "select", "row", "" ]
Let's say I have a table like this ``` id col1 col2 col3 col4 col5 col6 1 1 2 3 4 5 6 2 2 1 4 3 6 5 3 1 1 2 3 4 5 ``` I would want to select the rows where every field has a different value. The out put would be ``` id col1 col2 col3 col4...
You can unpivot your table using `UNION ALL`: ``` SELECT id FROM ( SELECT id, col1 AS col FROM mytable UNION ALL SELECT id, col2 FROM mytable UNION ALL SELECT id, col3 FROM mytable UNION ALL SELECT id, col4 FROM mytable UNION ALL SELECT id, col5 FROM mytable UNION ALL SELECT i...
A little less verbose than your solution, although it doesn't scale perfectly if the number of columns is excessively large: ``` SELECT * -- In actual live code you would of course never use '*' FROM MyTable WHERE col1 NOT IN (col2, col3, col4, col5, col6) AND col2 NOT IN (col3, col4, col5, col6) AN...
mySQL - Selecting all records where all columns are unique
[ "", "mysql", "sql", "" ]
I need to create mysql table with default value on column CURRENT\_DATE() I try ``` DROP TABLE IF EXISTS `visitors`; CREATE TABLE `visitors` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(32) NOT NULL, `browser` VARCHAR(500) NOT NULL, `version` VARCHAR(500) NOT NULL, `platform` ENUM('w','l...
Use **CURRENT\_TIMESTAMP** function instead of **CURRENT\_DATE()** function Try this: ``` DROP TABLE IF EXISTS `visitors`; CREATE TABLE `visitors` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(32) NOT NULL, `browser` VARCHAR(500) NOT NULL, `version` VARCHAR(500) NOT NULL, `platform` ENUM(...
you just have to replace CURRENT\_DATE() by NOW() in your query. I tried it and it's look ok.
How to create mysql table with column timestamp default current_date?
[ "", "mysql", "sql", "datetime", "timestamp", "create-table", "" ]
I am using Cursor for some operation on same table which I used in Select statement of Cursor as below, ``` CREATE TABLE #nsn (ID INT IDENTITY(1,1) ,Val1 Varchar(MAx) ,Val2 Varchar(MAx) ) INSERT INTO #nsn(Val1,VAl2) select 'A1','A2' INSERT INTO #nsn(Val1,VAl2) select 'B1','B2' INSERT INTO #nsn(Val1,VAl2) select 'C1',...
To achieve your expected result you should try something like below, ``` DECLARE @ID INT ,@Val1 VARCHAR(MAX) ,@Val2 VARCHAR(MAX) DECLARE cursor_Latest CURSOR FOR SELECT ID,Val1,Val2 FROM #nsn ORDER BY 1 ASC OPEN cursor_Latest FETCH NEXT FROM cursor_Latest INTO @ID , @Val1 ,@V...
DECLARE @ID INT ,@Val1 Varchar(MAx),@Val2 Varchar(MAx) ,@v1 Varchar(MAx) ,@v2 Varchar(MAx),@t Varchar(MAx),@val varchar(max) set @ID=1 while @ID<=(select count(\*) from #nsn) begin select @v1=val1,@v2=val2 from #nsn where ID=@ID select @Val1=val1,@Val2=val2 from #nsn where id=@ID+1 update #nsn set val2= ...
How to get Latest value of row in Cursor result set in SQL
[ "", "sql", "sql-server", "cursor", "" ]
When i executed below query ``` DECLARE @I INT=1 while(@I<13) BEGIN PRINT DATENAME(MONTH,@I) PRINT @I SET @I=@I+1 END ``` I got output like: ``` January 1 January 2 January 3 January 4 January 5 January 6 January 7 January 8 January 9 January 10 January 11 January 12 ``` Why all months names are not printing in the...
Because when you use `DATENAME(MONTH,@I)` the values 1,2,3,4... are implicitly converted to `DATETIME`: ``` SELECT CAST(1 AS DATETIME) -- 1900-01-02 00:00:00 1 - Jan 2 1900 12:00AM 2 - Jan 3 1900 12:00AM 3 - Jan 4 1900 12:00AM ... 12 - Jan 13 1900 12:00AM ``` and `DATENAME` for month part is always `January` You...
For [DATENAME](https://msdn.microsoft.com/de-de/library/ms174395(v=sql.120).aspx) to work the second parameter needs to be a date and not a number. Using an `int` will automatically convert this number to a day starting from January 1st in 1900 (`@I = 0`): ``` SELECT CONVERT(DATETIME, 0) -- returns 1900-01-01 00:00...
Why all months are not printing in it?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I am in the process of producing a report in SSRS and trying to add a check in to say when this parameter equals this value then display these values, but because the parameter is an integer and I can't pass multiple integer values into the one parameter. How can I do this? Here is example of what I am trying to do: ...
Why not just use two `SELECT` statements. If you already have your control flow, just use it to do the `SELECT`, e.g. ``` DECLARE @EntityGroupID INT SET @EntityGroupID = 741 IF @EntityGroupID = 741 BEGIN SELECT * FROM tEntityGroup WHERE ID IN (3097,3098,3099,3100,3101,3125); END ELSE BEGIN SEL...
Pass it as table variable like ``` declare @tbl table(EntityGroupID int); insert into @tbl select 3097 union select 3098 union select 3099 ``` Then you can just say ``` SELECT * FROM tEntityGroup WHERE ID in (select EntityGroupID from @tbl); ```
How to pass multiple integer values in one parameter in SQL Server
[ "", "sql", "t-sql", "sql-server-2014", "" ]
i'm trying to grab some data out of a table. The Variable is VARCHAR 30000 and when I use COBOL EXEC SQL to retrieve it, the string is returned but without the necessary (hex) Line Feeds and Carriage Returns. I inspect the string one character at a time looking for the Hex Values of 0A or 0D but they never come up. Th...
I have seen situations where CR and LF were in data in the database. These are valid characters so it's possible for them to be stored there. Have you tried to confirm that there really are CR and LF characters in the database using some other tool or method? My Z-Series experience is quite limited, so I'm unable to s...
If the data is stored / **converted** to ebcdic when **retrieved** on the mainframe, you should get the EBCDIC New-Line characters x'15' decimal=21 rather than 0A or 0D. It is only if you are retrieving the data in ASCII / UTF-8 that you would get 0A or 0D. --- Most java editors can edit EBCDIC (with the EBCDIC New-...
DB2 to COBOL String Losing Line Feed and Carriage Returns
[ "", "sql", "db2", "cobol", "" ]
I have following tables ``` tbl1 (empID, Name, ctNo) tbl2 (salID, empID, salry) tbl3 (histryID, salDate, empID, salID) ``` Expect Output `(empID,Name,salary,Salary_Date)` For Salary date, I only want the last salary\_date to be displayed. (maybe By using Partitiion by or Selfjoin methods.) Thank You.
Below query can answer your question ``` Create table #tbl1 (empID int , Name varchar(11), ctNo int) Create table #tbl2 (salID int, empID int, salry int) Create table #tbl3 (histryID int, salDate DATE, empID int, salID int) INSERT INTO #tbl1 values(1,'Dinesh',23),(2,'Raj',11) INSERT INTO #tbl2 values(1,1,1000),(2,...
You could try something like this: ``` select t1.empID, t1.Name, t2.salry as salary, top (t3.salDate) as Salary_Date from tbl1 t1, tbl2 t2, tbl3 t3 on t1.empID=t2.empID and t1.empID=t3.empID ``` Note: Pointing in correct direction. Not tested.
Join 3 tables based on Partition by or Self join
[ "", "sql", "sql-server-2008", "" ]
For example if a column has value like `200806`, and I want to know if this variable is a date variable or a numeric variable or a character variable, where can I see that? Thanks!
If you have SSMS (SQL Server Management Studio) then you can expand Database -> Tables -> Columns and find the type of that column. Else, use `sp_help` (or) `sp_helptext` along with your table name like below ``` sp_help your_table_name ```
You can pull the column information for your table by querying the `INFORMATION_SCHEMA.COLUMNS` table: ``` SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = 'YourDatabase' AND TABLE_SCHEMA = 'YourSchema' AND TABLE_NAME = 'YourTable' AND COLUMN_NAME = 'YourColumn' ```
How can I view the property of a variable (column) in SQL Server
[ "", "sql", "sql-server", "types", "" ]
I have the query below that counts the amount of occurrences for each group ``` SELECT ss.year, COUNT(*) FROM stackexchange_question seq INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code WHERE (seq.evaluation LIKE 'PARTIALLY' OR seq.evaluation LIKE 'TOTALLY') GROUP BY ss.year ORDER BY ss.year; ``` ...
You can use the `where` clause from both the queries as a `case` expression. Then count the occurrences and divide one by the other. ``` SELECT ss.year, 1.0 * sum(case when (seq.evaluation LIKE 'PARTIALLY' OR seq.evaluation LIKE 'TOTALLY') AND seq.percentile = 90 then 1 else 0 end) / sum(case when seq.evalua...
Ue conditional aggregation. Here is a simple way: ``` SELECT ss.year, COUNT(*), AVG(CASE WHEN (seq.percentile = 90) THEN 1.0 ELSE 0.0 END) as ProportionAT90 FROM stackexchange_question seq INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code WHERE seq.evaluation IN ('PARTIALLY', seq.eva...
How to calculate percentage of each group on a select query
[ "", "sql", "percentage", "" ]
I am not sure how to word this, so I wasn't sure what to google before posting this. This will be done with SQLite as well. Basically what I am trying to do is like this: `SELECT name FROM users WHERE Language = 'en'` If `'Language = 'en'` returns no rows, change `'en' to 'fr'` I know I can achieve this by running...
Please forgive me if any of this syntax isn't available in SQLLite, but this should work if it is: ``` SELECT name FROM users WHERE language = 'en' OR ( language = 'fr' AND NOT EXISTS (SELECT * FROM users WHERE language = 'en') ) ```
If you are only looking for one row, then use prioritzation: ``` select name from users where language in ('en', 'fr') order by (case when language = 'en' then 1 else 2 end) fetch first 1 row only; ``` If you are looking for multiple rows, then an `exists` clause is the way to go.
SQL When where x = y returns no rows, use x = z
[ "", "sql", "sqlite", "" ]
I have two table with same column but the second table has a column more than first table(`InfoDate`). **Table 1** ``` KID ParentID KLevel ---------------------------------------- 1 0 1 2 1 2 3 1 2 ``` **Table 2** ``` KID...
Your `WHERE NOT EXISTS...` condition does not really make sense. Right now you're only checking, if there is no row with `InfoDate = '2015-12-31 00:00:00.000'`. Since there obviously is such a row, no records are affected. Try this: ``` INSERT INTO [table2] ( [KID] , [ParentID] , [KLevel]) SELECT ...
Use any key value get the not existing records. ``` insert into table2 (KID , ParentID , KLevel) select KID , ParentID , KLevel from table1 where KID NOT IN ( SELECT KID FROM table2 WHERE InfoDate = '2015-12-31 00:00:00.000' ); ```
SQL: Insert from first table into second table when records not exist in second table
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have to build a database as follows: We have one table, called Organization. An Organization can have one or more products, which they sell. Then, I have a table called Products, which lists the Product title, cost, and amount sold. How can I create a relationship where a organization.product can contain a referenc...
Assuming you have something like this for your Organization and Product tables. ``` Organization Id (Primary Key) Name .... Product Id (Primary Key) Name Cost .... ``` Then you would create a join table like this that would link your Organization to Products. ``` OrganizationProduct ...
What you want to do here is have a table representing your products and in that table one of the fields should represent the Organisation which has the product, called something like org\_id. Then in your Organisation table you will have an id column to join with org\_id from the product table. Eg: ``` Products: i...
How do I fix the following many to many relationship?
[ "", "sql", "oracle", "" ]
First I have table `users` ``` +---------+----------+------------------+ | user_id | username | email | +---------+----------+------------------+ | 1 | User 1 | email1@gmail.com | | 2 | User 2 | email2@gmail.com | | 3 | User 3 | email3@gmail.com | | 4 | User 4 | email4@gmail....
When doing a `LEFT JOIN`, if you need to filter on a column in the second table, you should do it in the `ON` clause. ``` SELECT * FROM user u LEFT JOIN user_announcement ua ON u.user_id=ua.user_id AND ua.annou_id = 1 ```
Edit: Updated answer as per user requirement This is what you are looking for. Here I am first getting `min(annou_id)` for each user and then getting other records for that row. Now treating this derived table as second table, I am going for a left join as earlier to get the required records. ``` select u.user_id,u.u...
Join two tables but still get full data of first table
[ "", "mysql", "sql", "" ]
I keep getting the below error when trying to do a Group By on Multiple Inner Joins. > Msg 8120, Level 16, State 1, Line 1 Column 'address.Address1' is > invalid in the select list because it is not contained in either an > aggregate function or the GROUP BY clause. Below is my code, can't work out what I am doing wr...
what I understand from your comment is all you want is how many records of the same company name exist. If that’s the case then you can rewrite the query as: ``` select COUNT(*), C.CompanyName FROM [address] as AD Inner Join (Select TownId, Town FROM Town as Tw)TW ON Tw.TownID=Ad.TownID Inner Join (select Cou...
What you're doing wrong, is using a `mysql` like script for `sql server`. In sql server (and every other sane DBMS), every selected attribute, which is not in an aggregate function, has to be in the `group by`. In your case, I don't understand why you are using a `group by` at all, since you don't use aggregate functio...
Multiple Inner Joins Group By 'not contained in either an aggregate function or the GROUP BY clause'
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have 3 tables: ``` CREATE table materials (id serial primary key not null, name varchar(50) not null, unit varchar(10) not null default 'шт', price decimal(12, 2) not null check (price>0)); CREATE table warehouses (id serial primary key not null, lastname varchar(25) not null); CREATE table materials_in_ware...
Pretty straight forward. ``` SELECT m.name, count(miw.id_warehouses) FROM materials m LEFT JOIN materials_in_warehouses miw ON m.id=miw.id_materials AND miw."count">100 GROUP BY m.id, m.name ``` Your mistake might have just been the fact that you're using `count` as a column name, when it's an aggregate function. Use...
Try like this ``` select materials.name, count( select id_warehouses from materials_in_warehouses join materials on materials.id = materials_in_warehouses.id_materials where material_in_warehouses.count > 100 ) as sount from materials; ```
PostgreSQL select query doesn't work
[ "", "sql", "postgresql", "select", "" ]
I have two tables: Target table: `Specialisation (id , name , description)` Source table `TempSpecialisation(id , name , description)` I want to copy `TempSpe.description` to `Specialisation.Description` if the name matches or insert a new record in `Specialisation` with all the columns. I get duplicate entries beca...
Use `LTRIM(RTRIM(s.Name))` to remove white space from the beginning and the end of the field, so your merge statement becomes: ``` MERGE Specialisation as T USING TempSpecialisation as S ON LTRIM(RTRIM(s.Name)) = LTRIM(RTRIM(T.Name)) WHEN NOT MATCHED BY Target THEN INSERT(id ,Name, Description1) VALUES(S.id ,S.Name, ...
``` ALTER PROCEDURE [dbo].[TempDatabase2] WITH EXECUTE AS OWNER AS BEGIN MERGE dbo.Specialisation T USING dbo.TempSpecialisation S ON LTRIM(S.Name) = LTRIM(T.Name) WHEN NOT MATCHED BY TARGET THEN INSERT (id, Name, Description1) VALUES (S.id, S.Name, S.Description1) WHEN ...
How to Trim white spaces of string in stored procedure?
[ "", "sql", "sql-server", "trim", "" ]
I have table Asset (see below). For all Asset\_Type that are not "Automobile" I need to display it and round the Asset\_Value to the nearest hundreds. I need to **omit Asset\_Type type with only one asset** and sequence the results by asset type. ``` +-------------------+----------------------------------+------------...
Try this ``` SELECT Asset_Type, Round(Asset_Value / 100, 0) * 100 AS [Rounded Asset Value] FROM Asset WHERE Asset_Type IN (SELECT Asset_Type FROM Asset WHERE Asset_Type <> 'Automobile' GROUP BY Asset_Type HAVING Count...
Here is an alternative to Shep's answer using joins instead of a subquery: ``` SELECT a1.Asset_Type, ROUND(a1.Asset_Value/100, 0)*100 AS [Rounded Asset Value] FROM Asset a1 INNER JOIN ( SELECT Asset_Type, COUNT(*) AS frequency FROM Asset GROUP BY Asset_Type HAVING COUNT(*) > 1 ) a2 ON a1.Asset_Type = a...
Filter by COUNT(*) > 1 and display all relevant rows
[ "", "sql", "ms-access", "" ]
I have a table with records as below image [![Student Table](https://i.stack.imgur.com/djMy6.png)](https://i.stack.imgur.com/djMy6.png) I have to maintain the replica of student ABC as shown below, for each student in each process can contain only one active row. What is the best way to stop duplicates for every stud...
You can maintain the uniqueness by using a unique filtered index: ``` create unique index unq_table_name_processid_filtered on table(name, processid) where IsActive = 'true'; ``` [Here](https://msdn.microsoft.com/en-us/library/cc280372.aspx) is the documentation on the topic.
``` create unique index unq_table_name_processid_filtered on table(name, processid) where IsActive = 1; ``` 1 for bit type true
How to deal with duplicate records in SQL Server database
[ "", "sql", "sql-server", "database", "sql-server-2008", "sql-server-2012", "" ]
I have a MySQL table which has a column containing VARCHAR data. The data could be of the following type: * Simple integer (1,2,3, etc.) * Integer appended with the letter 'L', for example (L1, L2, etc.) * Integer appended with the letter 'Q', for example (Q1, Q2, etc.) * Integer appended with the letter 'W', for exam...
This should allow desired ordering. ``` ORDER BY FIELD(LEFT(type,1), 'Q', 'L', 'W') , CAST(type AS UNSIGNED) , CAST(SUBSTRING(type, 2) AS UNSIGNED) ``` The [first one](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_field) ensures those letters happen in that order; anything beginning othe...
The second column should be sorted based on the integer value of the column: ``` SELECT `type` FROM `table` ORDER BY CASE WHEN `type` LIKE 'Q%' THEN 1 WHEN `type` LIKE 'L%' THEN 2 WHEN `type` LIKE 'W%' THEN 3 ELSE 4 END, CASE WHEN `type` LIKE 'Q%' THEN CONVERT(SUBS...
MySQL ORDER BY using a CASE statement?
[ "", "mysql", "sql", "sql-order-by", "" ]
I have Two tables in my access database * table1(ID,productname,qunatity,remainder) * table2(ID,productname,sales) these tables are related together using "product name" ,How can I update"reminder" from table1 with the value of "quantity form first table - Sum(sales) from second table"
Because update queries in MS Access require [updateable](http://allenbrowne.com/ser-61.html) status, you cannot use a direct inner join on an aggregate query. Consider using the MS Access [DSum()](http://www.techonthenet.com/access/functions/domain/dsum.php) function: ``` UPDATE table1 SET table1.remainder = table1.qu...
Perform an update join by getting the `SUM()` first like ``` UPDATE a SET a.remainder = x.SaleTotal FROM table1 a INNER JOIN (SELECT productname, SUM(sales) AS SaleTotal FROM TABLE2 GROUP BY productname) x ON a.productname = x.productname; ```
How to update ms access database table using update and sum() function?
[ "", "sql", "" ]
I have data in a table which looks like: [![enter image description here](https://i.stack.imgur.com/y5HCa.png)](https://i.stack.imgur.com/y5HCa.png) I want to split its data and make it look like the following through a sql query in Oracle (without using pivot): [![enter image description here](https://i.stack.imgur...
You need to use a pivot query here to get the output you want: ``` SELECT Name, MIN(CASE WHEN ID_Type = 'PAN' THEN ID_No ELSE NULL END) AS PAN, MIN(CASE WHEN ID_Type = 'DL' THEN ID_No ELSE NULL END) AS DL, MIN(CASE WHEN ID_Type = 'Passport' THEN ID_No ELSE NULL END) AS Passport FROM you...
Since you mention without using PIVOT function, you can try to **use SQL within group for moving rows onto one line and listagg to display multiple column values in a single column.** In Oracle 11g, we can use the *listagg* built-in function : ``` select deptno, listagg (ename, ',') WITHIN GROUP (OR...
Splitting rows to columns in oracle
[ "", "sql", "oracle", "pivot", "" ]
Please help. I have 2 tables. First one is called Reservation and second one is called LastOrders. There are the columns DATE\_FROM in Date type and DATE:)\_TO in date type too. And I want if the date in table Reservation in column DATE\_TO = SYSDATE then delete this row and insert new row to table LastOrders I think ...
[SQL Fiddle](http://sqlfiddle.com/#!4/86d27/1) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE RESERVATION ( ID VARCHAR2(25) CONSTRAINT RESERVATION__ID__NN NOT NULL, DESCRIPTION VARCHAR2(100) CONSTRAINT RESERVATION__DE__NN NOT NULL, DATE_FROM DATE CONSTRAINT RESERVATION__DF__NN NOT NULL...
Trigger can do such job but it will fire only on some changes on table data. If you need to move data between tables in real-time you have to use jobs. ``` begin dbms_scheduler.create_job( job_name => 'my_job', job_type => 'PLSQL_BLOCK', enabled => true, repeat_interval =>...
How to delete row with past date and add this row to an other table?
[ "", "sql", "oracle", "plsql", "triggers", "" ]
In SQL I am trying to filter results based on an ID and wondering if there is any logical difference between ``` SELECT value FROM table1 JOIN table2 ON table1.id = table2.id WHERE table1.id = 1 ``` and ``` SELECT value FROM table1 JOIN table2 ON table1.id = table2.id AND table1.id = 1 ``` To me, it seems as i...
The answer is **NO** difference, but: I will always prefer to do the following. * Always keep the *Join Conditions* in `ON` clause * Always put the *filter's* in `where` clause This makes the query more **readable**. So I will use this query: ``` SELECT value FROM table1 INNER JOIN table2 ON table1.id = ta...
While there is no difference when using **INNER JOINS**, as VR46 pointed out, there is a significant difference when using **OUTER JOINS** and evaluating a value in the second table (for left joins - first table for right joins). Consider the following setup: ``` DECLARE @Table1 TABLE ([ID] int) DECLARE @Table2 TABLE ...
Difference between filtering queries in JOIN and WHERE?
[ "", "sql", "join", "where-clause", "resultset", "" ]
I am using `REPLACE` statement to replace certain string in my column. ``` update USER_DEFINED_DATA_SETS set DefaultValue = replace(DefaultValue, 'Area', 'Area_123') ``` It works fine most of the times. But If I have `Area` and `Area_Description` data in my `DefaultValue` column, it replaces both to `Area123` and `Ar...
You can add a `WHERE` condition to your `UPDATE` query to restrict the replacement to only occurrences where the `DefaultValue` column begins or ends with `Area`, or contains `Area` as a standalone word. ``` UPDATE USER_DEFINED_DATA_SETS SET DefaultValue = REPLACE(DefaultValue, 'Area', 'Area_123') WHERE DefaultValue ...
On `oracle` 11g and above. ``` SELECT REGEXP_REPLACE('Area Area_Description', '(^|[^[:alnum:]_])Area($|[^[:alnum:]_])', '\1Area_123\2') "Area" FROM DUAL; ``` Results in: ``` Area ------------------------- Area_123 Area_Description ```
Alternate To REPLACE
[ "", "sql", "" ]
I have this table below: [![enter image description here](https://i.stack.imgur.com/zq5lk.png)](https://i.stack.imgur.com/zq5lk.png) And when I run this query: ``` Select Gender, City, SUM(Salary) as TotalSalary, COUNT(ID) as [Total Employees] from tblEmployee Group by Gender, City ``` The output table is: [![ent...
# General info about grouping Taken from Postgres [documentation](http://www.postgresql.org/docs/current/static/sql-select.html). `GROUP BY` clause behavior is described below. **Edit**. After reading @lad2025 comment I'm putting some clarification. Yes, explanation of `GROUP BY` clause is quoted from specific DBMS m...
First SQL separates your table into all the different genders (2), then it separates those groups into all the different cities (3). 2 \* 3 = 6, i.e. there are 6 output rows. However, there are no London females so you get 5 output rows. The select part of the query - including count(whatevers) - are done per each of...
How does SQL Group By clause divides query result
[ "", "sql", "oracle", "" ]
Due to some strange circumstances, random long text fields in my Microsoft Access database appear to be corrupting and being replaced with "################". I want to be able to count the number of corrupted fields with an SQL query so that I can quickly check if the number has changed. I have written a query that c...
You can add conditional logic to the `select`: ``` SELECT (sum(iif(Profile = "################", 1, 0)) + sum(iif(Notes = "################", 1, 0)) + sum(iif(CriminalConvictionsNotes = "################", 1, 0)) + sum(iif(HealthIssueNotes = "################", 1, 0)) + sum(iif(NextOfKi...
Here is one way by `unpivoting` the data ``` SELECT Count(error_data) AS [Number of Errors] FROM (SELECT 1 AS error_Data FROM gpinformation WHERE profile = "################" UNION ALL SELECT 1 FROM gpinformation UNION ALL SELECT 1 FROM ...
Count number of times value appears in columns
[ "", "sql", "database", "ms-access", "oledb", "corruption", "" ]
In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement? If so, how can it be done?
As Peter Halasz mentions in [T-SQL DateTime to Unix Timestamp](https://web.archive.org/web/20141216081938/http://skinn3r.wordpress.com/2009/01/26/t-sql-datetime-to-unix-timestamp/): > Converting a datetime to unix timestamp is easy, but involves error > prone typing the following: > > ``` > @timestamp=DATEDIFF(second,...
maybe this answer will help someone... If you have a problem when you try to convert datetime using datediff function to number of seconds (mssql message: The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datep...
Convert Datetime to Unix timestamp
[ "", "sql", "sql-server", "datetime", "sql-server-2012", "unix-timestamp", "" ]
I have a problem, i'm trying to use the PIVOT in my query and without any result. Right now I have a table that looks like: ``` Category Month Value A August 10 B August 19 C August 15 A September 20 B September 23 C September 25 A...
Try `Conditional Aggregate`. ``` select Category, max(case when Month = 'August' then Value END) as August, max(case when Month = 'September' then Value END) as September, max(case when Month = 'October' then Value END) as October from Yourtable Group by Category ``` * [**SQL FIDDLE DEMO**](http:...
By using pivot we can write below query and for syntax follow link below as mentioned > <https://www.simple-talk.com/sql/t-sql-programming/questions-about-pivoting-data-in-sql-server-you-were-too-shy-to-ask/> ``` SELECT * FROM TABLE_NAME PIVOT(MAX(VALUE) FOR MONTH IN ( [AUGUST] ,[SEPTEMBER] ...
SQL using PIVOT right
[ "", "sql", "sql-server", "pivot", "" ]
I am trying to do the following query in SQL Server Manager: ``` SELECT TOP 100 * FROM [myDB].[dbo].[content] where content_html like %<images><img src='/' alt=''></img></images>%' ``` I need to search for that exact string that exists in numerous content items and is breaking an XML feed I am creating. ``` <images>...
If you need to search for `'` you need to double it (`''` inside `'...'` is treated as single `'`): ``` CREATE TABLE #content(content_html VARCHAR(100)); INSERT INTO #content(content_html) VALUES ('<images><img src=''/'' alt=''''></img></images>') SELECT TOP 100 * FROM #content where content_html like '%<images>%<im...
You need to add wrap `single quotes` with `single quotes`. Try this ``` declare @var varchar(4000) = '<images><img src=''/'' alt=''''></img></images>' SELECT TOP 100 * FROM [myDB].[dbo].[content] where content_html like '%'+var+'%' ``` Also using `TOP` without `Order by` does not guarantee same `TOP 100` result ever...
SQL Select Statement for text within a field that includes double and or single quotes
[ "", "sql", "sql-server", "" ]
I have 15 tables which are normalized to contain records and many user may be inserting/updating data in these tables( No two user can update the same record(s) simultaneously, this is restricted by client implementation). these 15 tables are updated 1 by 1 in a stored procedure. WITH(NOLOCK) is used where select state...
**WITH(NOLOCK) :** WITH (NOLOCK) is the equivalent of using READ UNCOMMITED as a transaction isolation level. Basically it gives the dirty read. i.e. if any transaction hold some data and then we try to get the data it will give the output without wait of transaction commit. so that we get the dirty read without wait...
I think what you want to do based on the comments that you left on your original post is set the isolation level to READ UNCOMMITED. This is the same as NO LOCK except that it sets it on the entire transaction and not on the individual select statement. Code Example: ``` USE DatabaseName; GO SET TRANSACTION ISOLATION...
WITH(NOLOCK) : where & when to use
[ "", "sql", "sql-server", "t-sql", "" ]
when I use DataFrame groupby like this: ``` df.groupBy(df("age")).agg(Map("id"->"count")) ``` I will only get a DataFrame with columns "age" and "count(id)",but in df,there are many other columns like "name". In all,I want to get the result as in MySQL, > "select name,age,count(id) from df group by age" What shoul...
Long story short in general you have to join aggregated results with the original table. Spark SQL follows the same pre-SQL:1999 convention as most of the major databases (PostgreSQL, Oracle, MS SQL Server) which doesn't allow additional columns in aggregation queries. Since for aggregations like count results are not...
One way to get all columns after doing a groupBy is to use join function. ``` feature_group = ['name', 'age'] data_counts = df.groupBy(feature_group).count().alias("counts") data_joined = df.join(data_counts, feature_group) ``` data\_joined will now have all columns including the count values.
How to get other columns when using Spark DataFrame groupby?
[ "", "sql", "apache-spark", "dataframe", "apache-spark-sql", "" ]
``` SELECT Siren, CASE WHEN Code_Juridique LIKE 'M%' AND Enseigne IS NOT NULL AND Enseigne <> '' --ok THEN 'Enseigne : ' + Enseigne WHEN (Sigle IS NULL OR Sigle ='') AND (Enseigne IS NULL OR Enseigne ='') THEN '' -- ok WHEN ...
Try this: ``` SELECT Siren, CASE WHEN ( Code_Juridique LIKE 'M%' ) AND ( IsNull( Enseigne, '' ) <> '' ) THEN 'Enseigne : ' + Enseigne WHEN ( IsNull( RTrim(LTrim(Sigle)), '') = '') AND ( IsNull( Enseigne, '' ) = '') THEN '' -- ok WHEN ( IsNull( RTri...
Besides stating the obvious that a `(TRUE OR FALSE) = TRUE` I would simplify and bullet proof the code by using `ISNULL()` and `LEN()`. ``` SELECT Siren, CASE WHEN Code_Juridique LIKE 'M%' AND LEN(ISNULL(Enseigne,'')) > 0 --ok THEN 'Enseigne : ' + Enseigne WHEN (LEN(ISNULL(Sigle, '')) = 0) ...
issue with CASE combined with an OR
[ "", "sql", "sql-server", "t-sql", "if-statement", "case", "" ]
I have a text of elements seperated by `,` as follows: ``` '{4,56,7,3,2}' ``` the amount of elemets is **unkonwn**. How do I get the last element? in the above example `2`
Try this: ``` SELECT regexp_replace('4,56,7,3,2', '^.*,', '') ``` **[FIDDLE DEMO](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/5160)** **EDIT:** Try ``` SELECT replace(replace(regexp_replace('4,56,7,3,2', '^.*,', ''),'{',''),'}','') ``` **[DEMO](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4...
If the value is indeed stored with the curly braces you can simply cast it into an array and pick the last array element: ``` select (elements::text[])[array_length(elements::text[],1)] from the_table; ``` As you didn't include the table definition, I assumed the column is named `elements`. If the column does **not*...
How to get last element in postgresql Text?
[ "", "sql", "postgresql", "" ]
So I'm selecting a name and a number of sports that name is related to, and I need to only select them when that number of sports is greater than 1. ``` SELECT DISTINCT name AS FullName, (SELECT COUNT(id) FROM coaches WHERE coaches.name=FullName) AS NrOfSports FROM coaches WHERE NrOfSports>1 ``` If `WHERE` ...
Use `Group By` and `Having` instead: ``` SELECT name AS FullName, COUNT(id) AS NrOfSports FROM coaches GROUP BY name HAVING COUNT(id) > 1 ``` Your correlated query can work, you just need to move it to a subquery and then you can add the `where` criteria. However, I believe the `group by` would be faster.
## Error explanation You're getting an error, because `WHERE` clause can not access columns by their alias in the very same level. There are two solutions, which **I don't recommend**, but for the sake of your question I'm attaching: **(1)** Move your `WHERE NrOfSports > 1` to another level ``` SELECT * FROM ( S...
Use a value from SELECT in WHERE
[ "", "mysql", "sql", "" ]
Suppose I have a table named `process_states`: ``` +--------+--------+ |Process | State | ------------------- | A | 0 | | A | 0 | | B | 0 | | B | -1 | | C | -99 | ------------------- Note: State can have many more negative and positive state values ``` > I want to find ...
You could use a `group by` clause and filter the processes with a `having` clause: ``` SELECT process FROM process_states GROUP BY process HAVING COUNT(CASE state WHEN -1 THEN 1 END) = 0 ``` EDIT: Given the clarifying comments on other answers, if the requirement is to find only processes that only have `0` ...
You can `group by` process column and check if the max and min of the state column is `0`. ``` select process from process_states group by process having max(state) = min(state) and min(state) = 0 ```
Group by query based on other column value
[ "", "sql", "oracle", "select", "group-by", "" ]
I have a table: ``` ID | Name | Date 1 | ABC | 2015-01-01 2 | XYZ | 2015-01-02 3 | ABC | 2015-01-03 4 | ABC | 2015-01-04 ``` I want to query this table such a way that the result becomes: ``` ID | Name | Date | NextDate 1 | ABC | 2015-01-01 | 2015-01-03 2 | XYZ | 2015-01-02 | null 3 | ABC | 2015-...
Since `SQL SERVER 2008` does not support `LEAD` window function we have to simulate it using `row_number` and `self join`. Try this ``` ;WITH cte AS (SELECT t1.*, Row_number() OVER( partition BY Name ORDER BY [Date]) AS rn FROM T...
Another way to write it would be. ``` Select a.*, c.nextDate from table a outer apply ( Select top 1 b.Date nextDate from table b where b.Id > a.ID and a.Name = b.Name order by b.id ) c ```
How to find the next value within a table based on certain criteria
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to check if a username it was already chosen. Before of show the query this is my tables structure: **USER** ``` ID | data 5 0 6 1 ``` **USERS\_SETTINGS** ``` ID | Username 5 Dillinger 6 John ``` How you can see in the table `user` I've a list of all users available in the system and i...
You seems to assign two different alias (or a typo) to a table which is not valid and should be changed to : ``` query = "SELECT Count(username) FROM users_settings u INNER JOIN user d ON u.id = d.id WHERE u.username = @usernamep AND d.data = @datap" ```
This fixes the problem with the syntax: ``` select count(*) from user u join user_settings us on u.id = us.id -- I am guessing about the right column name here where u.username = @usernamep and us.data = @datap; ``` However, this is more expensive than it might need to be. A cheaper method uses `exists` rat...
Error in MySql syntax on INNER JOIN use
[ "", "mysql", "sql", "vb.net", "" ]
Well i am new to SQL and i have just read that it's a good practice that stored procedures always return a value determining whether the query inside the procedure has been executed successfully or not. So i have a simple stored procedure with a select statement in it and i want to return 1 if it gets executed and re...
Use an output parameter to return the success status along with Try..Catch blocks ``` CREATE PROCEDURE myTest @Result INT OUTPUT AS BEGIN SET NOCOUNT ON; BEGIN TRY SELECT FirstName,LastName FROM Employees SET @Result = 1; END TRY BEGIN CATCH SET @Result = 0; END CATCH END; ```
@@ROWCOUNT this command helpful,means effective rows number. ``` return @@ROWCOUNT ``` you just need do this. if result > 0, success, if not ,fail.
How to check whether a SELECT query is Successful?
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have 4 tables, as below. Table: **Class** ``` ClassID | ClassSTD -------------------------------- 1 | STD-1<br> 2 | STD-2 ``` Table: **Section** ``` SectionId | SectionName | ClassId -------------------------------------------- 1 | sec-A | 1 2 | sec-...
Use **GROUP\_CONCAT()** function: Try this: ``` SELECT D.classSTD, C.sectionName, GROUP_CONCAT(B.subjectName SEPARATOR ', ') AS subjectName FROM SubjectAllocationToClass A INNER JOIN Subject B ON A.subjectId = B.SubjectId INNER JOIN Section C ON A.sectionId = C.SectionId INNER JOIN Class D ON A.c...
you can do this by `group_concat` like this: ``` select classSTD , SectionName , group_concat(`subjectName` separator ',') as `subjectName` FROM SubjectAllocationToClass INNER JOIN Class ON SubjectAllocationToClass.classId = Class.ClassID INNER JOIN Section ON SubjectAllocationToClass.sectionID = Section.section...
MYSQL comma base separated select result
[ "", "mysql", "sql", "select", "group-by", "group-concat", "" ]
I want to get last 8 week starting from today ( `GETDATE()` ) So the format must be dd/mm for all 8 weeks. I tried something like this ``` select "start_of_week" = cast(datepart(dd,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2))+'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2...
Here you go: ``` DECLARE @DateTable TABLE ( ADate DATETIME ) DECLARE @CurrentDate DATETIME SET @CurrentDate = GETDATE() WHILE (SELECT COUNT(*) FROM @DateTable WHERE DATEPART( dw, ADate ) = 2) <= 7 BEGIN INSERT INTO @DateTable SELECT @CurrentDate SET @CurrentDate = DATEADD( dd, -1, @CurrentDate ) END SELECT "st...
Maybe as easy as this? ``` WITH EightNumbers(Nmbr) AS ( SELECT 0 UNION SELECT -1 UNION SELECT -2 UNION SELECT -3 UNION SELECT -4 UNION SELECT -5 UNION SELECT -6 UNION SELECT -7 UNION SELECT -8 ) SELECT CONVERT(VARCHAR(5),GETDATE()+(Nmbr*7),103) FROM EightNumbers ORDER BY Nmbr...
Get first day and month for last x calendar weeks
[ "", "sql", "sql-server", "" ]
I want to write such a Query : ``` SELECT * FROM db WHERE ID = id AND Text != text OR Text = text ``` I mean `ID = id` clause and `Text != text` clause should be combined with and, and they should be combined with **`OR`** with the last clause. How can I do that? Thanks.
``` SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text ``` You should always use parentheses when combining `and` and `or`
``` SELECT * FROM db WHERE (ID = id AND Text != text) OR Text = text ``` Use brackets to separate two clauses
AND OR Clauses in SQL
[ "", "sql", "sql-server", "" ]
I have some data that is hard coded in my select query. The SQL is as follows: ``` SELECT 'ZZ0027674', 'ZZ0027704', 'ZZ0027707', 'ZZ0027709', 'ZZ0027729', 'ZZ0027742', 'ZZ0027750' ``` Unfortunately it does not display the data. It just returns 7 columns and each column has each value. I just want 1 column with the ...
You can use [`VALUES`](https://msdn.microsoft.com/en-us/library/dd776382.aspx), aka *Table Value Constructor*, clause for hardcoded values: ``` SELECT * FROM (VALUES('ZZ0027674'),('ZZ0027704'),('ZZ0027707'), ('ZZ0027709'),('ZZ0027729'),('ZZ0027742'), ('ZZ0027750') ) AS sub(c) ``` `LiveDe...
Use union: ``` SELECT 'ZZ0027674' union all SELECT 'ZZ0027704' union all SELECT 'ZZ0027707' union all SELECT 'ZZ0027709' union all SELECT 'ZZ0027729' union all SELECT 'ZZ0027742' union all SELECT 'ZZ0027750' ```
Different ways of returning hard coded values via SQL
[ "", "sql", "sql-server", "t-sql", "" ]
This is my first question here so I apologize if I do something wrong. I am also an SQL amateur so sorry if i don't make any sense. I am working with SQL Server 2014. I have dates in a date range (11/01/15 to 11/30/15) and I have 3 location names : NY, LA, SF. Can I get each of those names to show up in a seperate row...
Seeing your CTE: ``` WITH mycte AS ( SELECT CAST('20151101' AS DATETIME ) DateValue UNION ALL SELECT DateValue + 1 FROM mycte WHERE DateValue + 1 < '20151201' ), myNames (myName ) AS ( SELECT 'NY' UNION ...
Assuming dates are in a table called myDates and names are in a table called myNames with fieldnames myDate and myName respectively: ``` select d.myDate, n.myName from myDates d cross join myNames n where d.MyDate >= '20151101' and d.myDate < '20151201' ```
How can I get 3 names to repeat for every date in a date range?
[ "", "sql", "sql-server", "" ]
Does JOIN conditions order affect pefrormance? I have two tables A and B. I'm trying to join them like that: ``` SELECT * FROM A INNER JOIN B on B.ID_A = A.ID ``` In this case firebird use `NATURAL` plan instead using foreign key. ``` SELECT * FROM A INNER JOIN B on A.ID = B.ID_A ``` works good. Is that normal?
I guess you use Firebird with version older than 2.5.4 (probably 2.5.3). And it had bug <http://tracker.firebirdsql.org/browse/CORE-4530> fixed in 2.5.4. Please upgrade to Firebird 2.5.5 and check whether your problem disappear.
i'm not familiar with firebird but usually it doesn't matter for inner join. And in the new version of Oracle or SQLServer or MySQL or Postgresql it won't impact the performance. we have explain plan to check the Database choose the right way to Join you can try it.
SQL join conditions order performance
[ "", "sql", "performance", "join", "firebird", "" ]
I am trying to do an update in SQL Server. I have a temporary table with 50 users. The table contains a `personalid` and a date. I want to update the main tables date, with the date from the temporary table based on the `personalid` of the temp table. The main table has 3000+ users. The logic is to update the users da...
This query will satisfy ur need i think ``` CREATE TABLE MainTable ( Personal_id int, [MainTable_Date] date ) CREATE TABLE #TempTable ( Personalid int, [Date] date ) INSERT INTO MainTable VALUES(1,'20120202'),(2,'20130202'),(3,'20150202'),(4,'20150206') INSERT INTO #TempTable VALUES(1,'20120203'),(2,'20130311')...
If this fails: ``` UPDATE m SET MainTable_Date = t.[Date] FROM MainTable AS m INNER JOIN TempTable AS t ON m.personal_id = t.PersonalId ``` it means that there is not an one-on-one relationship on the tables. For checking run: ``` SELECT m.personal_id, t.PersonalId FROM MainTable AS m LEFT JOIN TempTable AS...
Update a column from multiple columns in SQL Server
[ "", "sql", "sql-server", "t-sql", "sql-update", "" ]
I have a stored procedure defined as below. When I execute it, I get an error and couldn't come up with a solution. ``` ALTER PROCEDURE [dbo].[GetShippmentList] @shipmentNumber VARCHAR(20), @requestType VARCHAR(1), @shipmentNames VARCHAR(100), @assigneeDateFrom DATETIME, @assignedDateTo DATE...
This is an `order by`: ``` ORDER BY CASE @sortField WHEN 'TaskName' THEN NAME WHEN 'ShipmentName' THEN ShipmentName WHEN 'ShipmentNumber' THEN ShipmentNumber WHEN 'AssignedDate' THEN AssignedDate WHEN 'CompletedDate' THEN CompletedDate WHEN 'Assignees' THEN Assig...
Another approach is to use dynamic SQL to generate different SQL for the different choices, allowing the optimizer to choose the best plan for each. ``` DECLARE @ComputedSortField SYSNAME = CASE @sortField WHEN 'ShipmentNumber' THEN N'ShipmentNumber' WHEN 'TaskName' THEN N'NAME' WHEN 'Shipmen...
Error in Order by clause when using case statement in SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I have two tables : a table PERSON, and a table CAR. there is a one to many relatshionship between the two tables : One person can own multiple cars, and one car can be owned by one and only one person. The table PERSON has the following columns: ``` PERSON PERSON_ID PERSON_NAME ``` The table...
or simply ``` select descr from ( select -1 as car_id, person_id, person_name as descr from person union all select car_id, person_id, car_description as descr from car order by 2,1) ```
Possible solution - ``` with person as ( select 1 as PERSON_ID, 'John' as PERSON_NAME from dual union all select 2 as PERSON_ID, 'Karl' as PERSON_NAME from dual union all select 3 as PERSON_ID, 'Sarah' as PERSON_NAME from dual union all select 4 as PERSON_ID, 'Kevin' as PERSON_NAME from dual ), car a...
select columns from two tables and put the result in one colum in a specific order
[ "", "sql", "oracle", "" ]
I have a table like this: ``` SaleID Region Customer OrderAmt 1 North Keesha 10 2 West Mary 10 3 North Winston 10 4 North John 10 5 North Keesha 10 6 West John ...
With a CTE: ``` WITH cte AS ( SELECT Region, Customer , sum(OrderAmt) AS CustAmt , sum(sum(OrderAmt)) OVER (PARTITION BY Region) AS RegAmt , row_number() OVER (PARTITION BY Region ORDER BY sum(OrderAmt) DESC) AS rn FROM tbl GROUP BY Region, Customer ) SELECT Region, Customer, Cu...
In one select: ``` select top 1 with ties Region , Customer , CustAmt = sum(OrderAmt), RegAmt = sum(sum(OrderAmt)) over (partition by Region) from your_table group by Region, Customer order by row_number() over(partition by Region order by sum(OrderAmt) desc); ``` **[S...
select customer with the highest total orders per region, alongside both totals
[ "", "sql", "sql-server", "greatest-n-per-group", "window-functions", "" ]
I need some help with the SUM feature in android app. I have a table that looks something like the following : [![enter image description here](https://i.stack.imgur.com/0jOKm.png)](https://i.stack.imgur.com/0jOKm.png) I have need to `SUM` Quantities between last two records Notes and last one record with Note. I nee...
I am inclined to phrase the question as: sum the quantity from all rows that have one note "ahead" of them. This suggests: ``` select sum(quantity) from (select ft.*, (select count(*) from fuel_table ft2 where ft2.note = 'Yes' and ft2.id >= ft.id ) as numNotesAhead...
``` WITH max_id_with_note AS ( SELECT MAX(ID) AS max_id FROM YourTable WHERE IFNULL(note, '') <> '' ) , previous_max_id_with_note AS ( SELECT max(ID) as max_id FROM YourTable WHERE IFNULL(note, '') <> '' AND ID ...
SQLite SUM() between several rows
[ "", "android", "sql", "sqlite", "" ]
I have a table `software` and columns in it as `dev_cost`, `sell_cost`. If `dev_cost` is 16000 and `sell_cost` is 7500, how do I find the quantity of software to be sold in order to recover the `dev_cost`? I have queried as below: ``` select dev_cost / sell_cost from software ; ``` It is returning 2 as the answer. B...
Your columns have integer types, and [integer division truncates the result towards zero](http://www.postgresql.org/docs/current/static/functions-math.html). To get an accurate result, you'll need to [cast at least one of the values to float or decimal](https://stackoverflow.com/questions/28736227/postgresql-9-3-conver...
You can cast integer type to `numeric` and use [`ceil()`](http://www.postgresql.org/docs/9.4/static/functions-math.html#FUNCTIONS-MATH-FUNC-TABLE) function to get the desired output > The PostgreSQL ceil function returns the smallest integer value that > is greater than or equal to a number. ``` SELECT 16000::NUMERIC...
Division ( / ) not giving my answer in postgresql
[ "", "sql", "postgresql", "division", "modulo", "" ]
Is it possible to set the transaction isolation level to read uncommitted for users by default in MS SQL Server Management Studio 2012? I was thinking it could either be done through editing a config file or changing a reg key but i haven't been able to locate anything that would change this yet.
As far as I know you can't change the default lock level. For workloads with a lot of reads and fewer writes, you can avoid blocking queries with [multiversion concurrency control](https://en.wikipedia.org/wiki/Multiversion_concurrency_control). That's the default for Postgres and Oracle. In SQL Server, MVCC is called...
You can’t. The default isolation level for all SQL Server databases is Read Committed, and your only option is to set the isolation level within a session, if you want to use a level other than the default. You could also set *SET TRANSACTION ISOLATION LEVEL* within stored procedure body.
How to set transaction isolation level as read uncommitted as default for users
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I have a simple query: ``` Select qty from X where id=....; ``` this query always return 0 or 1 row. when it return 1 row everything works. but if it return 0 rows my query fails as `qty` is used in calculations. (This is acatually a Sub query in Select statment). I need somehow to make sure the query always return ...
You can do this: ``` SELECT COALESCE( (SELECT qty from X where id=....), 0) ``` if nothing is returned from the inner `SELECT` statement, `COALESCE` will give you `0` in the outer `SELECT` statement.
``` Select *.a from ( Select qty, 0 as priority from X where id=.... Union Select 0, 1 as priority ) a Order By a.priority Asc Limit 1 ``` This select basically ensures that at least one row is returned by adding an additional row to the end and by adding the limit statement we just return the first row. So now...
Is it possible to force reutrn value from query when no rows found?
[ "", "sql", "postgresql", "" ]
I'm working on Library Database and it contains a table called book\_transaction. There are 2 columns called `issued_date` and `due_date`. `due_date` should be 7 days from `issued_date`. Can I specify this condition using `default` key word while creating the table? If it is not possible please leave an alternative fo...
Thank you for the use full comment by "fabulaspb". I come up with this ``` create table book_transaction ( transaction_number int primary key, book_isbn int REFERENCES book_master(book_isbn), student_code int references student_master(student_code), issued_date date default sysdate, due...
Oracle `default` constraints cannot refer to other columns. You can get the same functionality using a trigger (see [this answer](https://stackoverflow.com/a/3787229/50552)): ``` CREATE TRIGGER book_transaction_trigger BEFORE INSERT ON book_transaction FOR EACH ROW BEGIN IF :new.due_date IS NULL THEN :new.du...
updating column value based on another column value
[ "", "sql", "oracle", "" ]
For an example, if have: ``` SELECT 'A@G.com' AS Email, 2 AS Somenumber, 3 AS Number UNION ALL SELECT 'A@G.com' AS Email, 2 AS Somenumber, 5 AS Number UNION ALL SELECT 'z@y.com' AS Email, 1 AS Somenumber, 6 AS Number ``` instead of: [![enter image description here](https://i.stack.imgur.com/LLiYr.jpg)](https://i.sta...
``` SELECT Email, Somenumber, Number FROM ( SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Number DESC) FROM ( VALUES ('A@G.com', 2, 3), ('A@G.com', 2, 5), ('z@y.com', 1, 6) ) t(Email, Somenumber, Number) ) t WHERE RowNum = 1 ``` output - ``` ...
It looks like you're after one row per email. You can do that like: ``` ; with all_rows as ( ... your union query here ... ) , with numbered_rows as ( select row_number() over (partition by email order by somenumber) as rn , * from all_rows ) ...
How to handle duplicates in sql on union all select statements
[ "", "sql", "sql-server", "sql-server-2012", "" ]
I will need your help with this one. I want to normalize numbers within groups. Say I have this dataset: ``` A B C ------- 0 1 3 1 1 0 1 1 2 1 1 4 1 2 1 1 2 1 ``` I want to group these rows by A and B, then normalize the values of C *within its group*, i.e. summing up all C's of the group and then divid...
You could use windowed functions for it: ``` SELECT a,b, 1.0 * c / CASE WHEN SUM(c) OVER(PARTITION BY a,b) = 0 THEN 1 ELSE SUM(c) OVER(PARTITION BY a,b) END AS c FROM tab ``` `SqlFiddleDemo` Output: ``` ╔════╦════╦════════════════════╗ ║ a ║ b ║ c ║ ╠════╬════╬═════════════...
You can use a derived table to aggregate the values and then `join` the results back to the original table. To avoid division by `0`, a `where` clause has been included. For these `0` sum cases, you might have to include a special condition to select them. ``` select t.a, t.b, 1.0 * t.c/t1.total_c from tablename t jo...
Normalize values within a group using SQL
[ "", "sql", "postgresql", "" ]
I have a table with 3 values. ``` ID AuditDateTime UpdateType 12 12-15-2015 18:09 1 45 12-04-2015 17:41 0 75 12-21-2015 04:26 0 12 12-17-2015 07:43 0 35 12-01-2015 05:36 1 45 12-15-2015 04:35 0 ``` I'm trying to return only records where the `UpdateType` has changed...
By using a CTE it is possible to find the previous record based upon the order of the AuditDateTime ``` WITH CTEData AS (SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AuditDateTime) [ROWNUM], * FROM @tmpTable) SELECT A.ID, A.AuditDateTime, A.UpdateType FROM CTEData A INNER JOIN CTEData B ON (A.ROWNUM ...
This should do what you're trying to do I believe ``` SELECT T1.ID, T1.AuditDateTime, T1.UpdateType FROM dbo.My_Table T1 INNER JOIN dbo.My_Table T2 ON T2.ID = T1.ID AND T2.UpdateType <> T1.UpdateType AND T2.AuditDateTime < T1.AuditDateTime LEFT OUTER JOIN dbo.My_Table T3 ON T3.ID = T1.I...
SQL Server Return Rows Where Field Changed
[ "", "sql", "sql-server", "record", "" ]
I have this query segment below where I'm trying to build a string of "month-year" from a date field in this table. It's very important that it comes in the right order starting from current month going forward 12 months. ``` DECLARE @cols AS NVARCHAR(MAX) SELECT @cols = STUFF( (SELECT N',' + QUOTENAME(y) AS [text()] ...
If you are using `SQL Server 2012+` you could use [`FORMAT`](https://msdn.microsoft.com/en-us/library/hh213505.aspx) function: ``` DECLARE @cols AS NVARCHAR(MAX); ;WITH cte AS -- get only one date per month/year ( SELECT MIN(StartDate) AS StartDate FROM #Products2 GROUP BY YEAR(StartDate),MONTH(StartDate...
You could use ``` DECLARE @cols AS NVARCHAR(MAX); SELECT @cols = STUFF((SELECT N',' + QUOTENAME(y) AS [text()] FROM (SELECT CONVERT(CHAR(3), StartDate, 0) + '-' + RIGHT(CONVERT(VARCHAR, YEAR(StartDate)), 2) AS y, MIN(Sta...
MSSQL Order by date with distinct
[ "", "sql", "sql-server", "t-sql", "sql-order-by", "" ]
I need to insert custom date time in the oracle database where the `ITEM_TIME_DATE` column has the `TIMESTAMP` data type. Here is my query: ``` INSERT INTO items (ITEM_AUTHOR_ID, ITEM_TITLE, ITEM_DESCRIPTION, ITEM_TIME_DATE, ITEM_STATUS) VALUES ('0', 'test title', 'test des', TO_TIMESTAMP('12-23-2015 8...
The date format in the `TO_TIMESTAMP` call doesn't match the data. Use: ``` INSERT INTO items (ITEM_AUTHOR_ID, ITEM_TITLE, ITEM_DESCRIPTION, ITEM_TIME_DATE, ITEM_STATUS) VALUES ('0', 'test title', 'test des', TO_TIMESTAMP('12-23-2015 8:00 PM', 'MM-DD-YYYY HH:MI AM'), 0); ``` Best of luck.
You need to remove the `:SS` or add seconds `:00` to your time, and add `AM` to the format. This works: ``` INSERT INTO items (ITEM_AUTHOR_ID, ITEM_TITLE, ITEM_DESCRIPTION, ITEM_TIME_DATE, ITEM_STATUS) VALUES ('0', 'test title', 'test des', TO_TIMESTAMP('12-23-2015 8:00:00 PM', 'MM-DD-YYYY HH:MI:SS AM'...
Inserting custom TIMESTAMP value in the Oracle SQL
[ "", "sql", "oracle", "" ]
I have following query ``` SELECT R.ServiceID,ItemName, Price FROM RequisitionDetail RD, Requisition R WHERE RD.ItemStatus='Used' AND RD.RequisitionID=R.RequisitionID AND R.ServiceID=2264 ``` and result yields ``` ServiceID ItemName Price 2264 LCD 1500.00 2264 Touch Panel 12...
Try this simple sql. ``` SELECT t.ServiceID, STUFF( ( SELECT ',' + s.ItemName FROM (SELECT R.ServiceID,ItemName, Price FROM RequisitionDetail RD, Requisition R WHERE RD.ItemStatus='Used' AND RD.RequisitionID=R.RequisitionID AND R.ServiceID=2264) s WHERE s.ServiceID = t.ServiceID FOR XML PATH(''...
Aggregate string concatenation is a bit of a pain in SQL Server. You can do this as: ``` WITH r as ( SELECT R.ServiceID, ItemName, Price FROM RequisitionDetail RD JOIN Requisition R ON RD.RequisitionID = R.RequisitionID WHERE RD.ItemStatus = 'Used' AND R.ServiceID = 2264 ...
Showing multiple data in select query in Sql server 2014
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I keep getting this error in Oracle when i try to run this statement. I am not sure where the formatting error is coming from. maybe someone with fresh eyes can assist me with this problem. ``` INSERT INTO Faculty (FacNo, FacFirstName, FacLastName, FacCity, FacState, FacDept, FacRank, FacSalary, FacSupervisor, FacHir...
Most likely, your [`NLS_DATE_FORMAT`](https://docs.oracle.com/cd/B19306_01/server.102/b14237/initparams122.htm#REFRN10119), the default date format for literals does not match your string. Never assume dates are formatted one way or another. use `TO_DATE` function to specify the format, so convert to : `Insert (... to...
OldProgrammers answer is the correct answer. Explicitly converting the string to a date is the safest. MS-SQL will generally automatically convert anything recognizable as a date and Oracle will do it if your formatting matches the default formatting for the system. All the oracle systems I have worked with used 'DD/MO...
SQL Error: ORA-01861: literal does not match format string
[ "", "sql", "string", "oracle", "" ]
I got 2 tables of recipes, and recipe\_ratings and I don't know how to get the AVG(rating\_value) from recipe\_rating and join them Recipes table (get '\*') and join it with AVG(recipe\_value) order by date\_posted
here is my approach: **Table & Data :** ``` CREATE TABLE recipes (`id` int, `recipe_name` varchar(7)) ; CREATE TABLE recipe_ratings (`id` int, `recipeId` int,`rating_value` int,`date_posted` datetime) ; INSERT INTO recipes (`id`, `recipe_name`) VALUES (1, 'Cake'), (2, 'Bun'), (3, 'Hot Dog')...
Execute the following query: ``` SELECT t1.*, t2.avg(rating) as 'Average Rating' FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id GROUP BY t1.id ```
Join 2 tables for viewing
[ "", "mysql", "sql", "select", "join", "group-by", "" ]
I'm looking to summarise data by week from a given starting date into the indefinite future. Typically I would just dump a result set into an Excel dash and group there via pivots etc., but I'm writing this query to hand off to a set of users and allow them access through a front-end BI application, so I want to give i...
Something like this will give you the same output without having to manually specify every week ending date: ``` SELECT convert(varchar, duedate - datepart(dw, duedate) + 6, 111) as [Week Ending], sum(linetotal) FROM PurchaseOrderDetail WHERE year(duedate) > '2014' GROUP BY year(duedate), convert(varchar, dueda...
Consider a solution along these lines (please note - the code is untested as I do not have access to a SQL Server instance right now). The idea is to replace the (hard-coded) date with year and week numbers. This suggested solution will allow your BI users to view the SUM of `linetotal` by year and week number. As you ...
tSQL summarise data by week based on date field?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table contains information about calls, each call have a `start date` and `end date` with DATE type with **YYYY:MM:DD HH:MI:SS** format. how to get the following: 1- number of seconds in the range from **00:00:00** to **07:30:00** between the `start date` and the `end date`, and the number of seconds out of ...
My try with hierarchical subquery generating days for each call and functions `greatest`, `least`: [SQLFiddle](http://sqlfiddle.com/#!4/a68e3/2) ``` with t as ( select id, sd, ed, trunc(sd)+level-1 dt from calls connect by trunc(sd)+level-1<=trunc(ed) and prior dbms_random.value is not null and prio...
With : ``` SELECT (end_date - start_date), ... FROM ... ``` you obtain the number of days... With : ``` SELECT (end_date - start_date)*24, ... FROM ... ``` you obtain the number of hours... And, with : ``` SELECT (end_date - start_date)*24*60*60, ... FROM ... ``` you obtain the number of seconds...
Get number of seconds in specific duration
[ "", "sql", "oracle", "datetime", "" ]
I am working on a SQL query which returns all records between two dates from a table as follows ``` select convert(varchar(2),TestDate,108) from dbo.Table where TestDate between convert(datetime,convert(varchar,GETDATE(),101)) and dateadd(day,1,convert(datetime,convert(varchar,GETDATE(),101))) ``` ...
Why would you convert dates to a string for comparisons? Just do the comparisons as dates. In addition, you can use `datepart()` to extract the hour, rather than using some esoteric format to `convert()`: ``` select datepart(hour, TestDate) from dbo.Table where TestDate between cast(GETDATE() as date) and ...
I guess that you are having an extra CONVERT. Wherever you have this ``` convert(varchar,GETDATE(),101) ``` just replace with your date: ``` '2015-12-27 00:00:00.000' ``` because the purpose of the CONVERT function is to translate a Date into a Varchar
incorrect results while passing a datetime instead of getdate()
[ "", "sql", "datetime", "" ]
How to change `*` [asterisk symbol] into list of column names? I can view the list of column names after placing mouse cursor over the `*`. Is it possible to click-crack on something to change the `*` into names without running the script an inserting the results into some dbo.temp table? [![enter image description he...
There is an option into Sql Server Management in which you can execute a stored procedure with the keyboard, you can configure that option to execute a procedure that lists the columns of a table, this is the way you can do it: [![enter image description here](https://i.stack.imgur.com/Ed9B8.png)](https://i.stack.imgu...
In SQL Server Management Studio, you can do what you want. On the left side of the screen, expand the database to get the table name. Then, drag the table name over to the query pane and it will list all the columns.
Edit asterisk symbol into list of column names in SSMS by wildcard expansion
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2017", "sql-server-2019", "" ]
I have this query that's taking forever to run. The table contains about 7 million rows. Everything else I'm doing with it (it's a "temporary" permanent table) is going relatively quickly (an hour or so) while this one UPDATE belong took 7 hours! We have SQL Server 2014. `DOI` is an `NVARCHAR(72)` and has a non-unique...
Here is another way `SUB-QUERY` version ``` UPDATE TempSourceTable SET AffiliationsSameForAllDOI = 1 WHERE doi IN (SELECT doi FROM TempSourceTable S GROUP BY DOI HAVING COUNT(DISTINCT Affiliations) = 1) ``` `EXISTS` Version ``` UPDATE TempSourceTable S SET Affi...
``` update TempSourceTable set AffiliationsSameForAllDOI = 1 where DOI in ( select DOI from TempSourceTable group by DOI having count(distinct Affiliations) = 1 ) ``` Depending on what your data looks like maybe you'd have some luck with performance by creating a computed column that strips out say the...
How to speed up SQL query with JOIN on large varchar field and a NOT EXISTS
[ "", "sql", "sql-server", "performance", "t-sql", "" ]
I need to `convert` `Time` value into `integer` value . For E.g: If the `time` value is `'07:00 PM'` I need to `convert` it into `19`. I have tried below query to do this. ``` select CAST(substring(CONVERT(varchar,convert(smalldatetime,'07:00 PM'),114), 1,2) as int) as VALUE ``` It returns me the desired output. Bu...
You seem to want to extract the hour from the time. Use `datepart()`: ``` select datepart(hour, timecol) ```
By using DATEPART() ... ``` DECLARE @DATE DATETIME = N'07:00 PM' SELECT DATEPART(hh, @DATE) ```
Convert Time value into Integer in sql server
[ "", "sql", "sql-server", "t-sql", "" ]
I have a bit of a brain lock on this one. **TLDR;** How do I implement "mark as read" for million items efficiently? I have a use case of marking all articles as read. Tens of thousands. The solution I have now works fine for small number of articles, but it's very, very slow with big numbers. It's essentially becaus...
Why don't you remove the foreign keys from the `read_article` table and create a unique index on both the columns. This should speed up the search and insert queries. To check if the article has been read you can use a subquery in the main query and when inserting the row in the table you could use an upsert statement....
``` insert into read_articles (article_id, user_id) select a.id, u.id from articles a cross join users u ```
Mark all as read
[ "", "sql", "postgresql", "" ]
I have a table something like: ``` stuff type price first_stuff 1 43 second_stuff 2 46 third_stuff 3 24 fourth_stuff 2 12 fifth_stuff NULL 90 ``` And for every `type` of stuff is assigned a description which is not stored in DB ``` 1 = Bad 2 = Good 3 = Exce...
``` DECLARE @t TABLE ([type] INT) INSERT INTO @t ([type]) VALUES (1),(2),(3),(2),(NULL) SELECT [Description] = CASE t.[type] WHEN 1 THEN 'Bad' WHEN 2 THEN 'Good' WHEN 3 THEN 'Excellent' ELSE 'Not_Assigned' END, t.[Count] FROM ( SELECT [type], [Co...
``` ;WITH CTE_TYPE AS (SELECT DESCRIPTION, VALUE FROM (VALUES ('BAD', 1), ('GOOD', 2), ('EXCELLENT', 3))V( DESCRIPTION, VALUE )), CTE_COUNT AS (SELECT C.DESCRIPTION, ...
SQL Server case when or enum
[ "", "sql", "sql-server", "enums", "case-when", "" ]
how can I find the count of number of rows of different tables.i.e i am using mysql server and i want to have a total count of rows in both the tables This is what I have tried so far ``` SELECT COUNT(*) FROM student_it; UNION ALL SELECT COUNT(*) FROM student_cs; SUM(COUNT(*)); ```
You could also try the following sql: ``` SELECT SUM(tot) FROM ( SELECT COUNT(*) tot FROM `student_it` UNION ALL SELECT COUNT(*) tot FROM `student_cs` ) sub ``` But I think you should consider storing all students in one `student` table.
You can use `sp_msforeachtable` like this: ``` Use <your_db>; EXEC sp_MSforeachtable N'select count(*) from ?;'; ``` Also if you need to filter the data you can use the `@whereand` paremeter.
count number of rows different table database
[ "", "mysql", "sql", "count", "" ]
I have a list, for instance: 1,2,5,6,8,12,15 I'm trying to come up with an SQL query that returns to me a list of numbers, from the previous list, not present in another list. So, suppose I'm getting all id's from a table and those are: 1,3,7,8,15 The resultset should be: 2,5,6,12 Because those were the numbers not...
``` with a (id) as (values (1),(2),(5),(6),(8),(12),(15) ), b (id) as (values (1),(3),(7),(8),(15) ) select id from a except all select id from b ; id ---- 6 5 12 2 ``` <http://www.postgresql.org/docs/current/static/sql-select.html#SQL-EXCEPT>
I would recommend using an inner join and checking for nulls. ``` with a (id) as (values (1),(2),(5),(6),(8),(12),(15) ), b (id) as (values (1),(3),(7),(8),(15) ) select a.id from a left join b on a.id=b.id where b.id is null; ```
PostgreSQL: Get all numbers in a list that were not present in another list
[ "", "sql", "list", "postgresql", "" ]
I have a query which return a table something like: ``` Value Description -------------------- 12 Decription1 43 Decription2 78 Decription3 3 Decription4 6 Decription5 ``` My `select` looks like ``` select sum(value), description from table group by description ```...
You can use windowed functions: ``` SELECT *, [percentage] = ROUND(100 * 1.0 * value / SUM(value) OVER(), 0) FROM #tab; ``` `LiveDemo` Output: ``` ╔═══════╦═════════════╦════════════╗ ║ value ║ Description ║ Percentage ║ ╠═══════╬═════════════╬════════════╣ ║ 12 ║ Decription1 ║ 8 ║ ║ 43 ║ Decript...
``` declare @total int; select @total = Sum(Value) from table select (sum(value) * 100.0)/@total as percentage , description from table group by description` ```
SQL Server calculate percents of values for each row
[ "", "sql", "sql-server", "select", "" ]
Below is my table called 'datapoints'. I am trying to retrieve instances where there are different instances of 'sensorValue' for the same 'timeOfReading' and 'sensorNumber'. For example: ``` sensorNumber sensorValue timeOfReading 5 5 6 5 5 6 5 ...
You can use a self-JOIN to match related rows in the same table. ``` SELECT DISTINCT t1.sensorNumber, t1.timeOfReading FROM datapoints AS t1 JOIN datapoints AS t2 ON t1.sensorNumber = t2.sensorNumber AND t1.timeOfReading = t2.timeOfReading AND t1.sensorValue != t2.sensorValue WHERE t1.timeOfReading < 20 `...
I think you have missed a condition. Add a not condition also to retrieve only instances with different values. ``` SELECT * FROM new_table a WHERE EXISTS (SELECT * FROM new_table b WHERE a.num = b.num AND a.timeRead = b.timeRead AND a.value != b.value); ```
Retrieving rows that have 2 columns matching and 1 different
[ "", "mysql", "sql", "" ]
Assuming I have a column named `creation_timestamp` on a table named `bank_payments`, I would like to break today into five-minute intervals, and then query the database for the count in each of those intervals. I'm going to read this manually (i.e. this is not for consumption by an application), so the output format ...
If you want to group by your records in table on 5 min interval then you can try this: ``` SELECT col1, count(col1), creation_timestamp FROM bank_payments WHERE DATE(`creation_timestamp`) = CURDATE() GROUP BY UNIX_TIMESTAMP(creation_timestamp) DIV 300, col1 ```
Yes. Here is one method: ``` select sec_to_time(floor(time_to_sec(time(datetimecol)*5/60))), count(*) from t where t.datetimecol >= curdate() and t.dattimeecol < curdate() + interval 1 day group by 1 order by 1; ```
How can I get the number of records for today in five-minute intervals?
[ "", "mysql", "sql", "" ]
So, code is very simple: ``` var result = dbContext.Skip(x).Take(y).ToList(); ``` When x is big (~1.000.000), query is very slow. y is small - 10, 20. SQL code for this is: (from sql profiler) ``` SELECT ... FROM ... ORDER BY ... OFFSET x ROWS FETCH NEXT y ROWS ONLY ``` The question is if anybody knows how to spee...
I think `OFFSET` .. `FETCH` is very useful when browsing the first pages from your large data (which is happening very often in most applications) and have a performance drawback when querying high order pages from large data. Check this [article](https://web.archive.org/web/20190925145935/http://www.mssqlgirl.com/pag...
You are right on that, Skip().Take() approach is slow on SQL server. When I noticed that I used another approach and it worked good. Instead of using Linq Skip().Take() - which writes the code you showed - , I explicitly write the SQL as: ``` select top NTake ... from ... order by ... where orderedByValue > lastRetrie...
Entity Framework Skip/Take is very slow when number to skip is big
[ "", "sql", "performance", "entity-framework", "linq", "" ]
I have a table named PublishedData, see image below [![enter image description here](https://i.stack.imgur.com/jMfjy.png)](https://i.stack.imgur.com/jMfjy.png) I'm trying to get the output like, below image [![enter image description here](https://i.stack.imgur.com/Znevm.png)](https://i.stack.imgur.com/Znevm.png)
I think you can use a query like this: ``` SELECT dt.DistrictName, ISNULL(dt.Content, 'N/A') Content, dt.UpdatedDate, mt.LastPublished, mt.Unpublished FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY DistrictName ORDER BY UpdatedDate DESC, ISNULL(Content, 'zzzzz')) seq FROM PublishedData) dt INNER JOIN ( ...
Check out something like this (I don't have your tables, but you will get the idea where to follow with your query): ``` SELECT DirectName, MAX(UpdatedDate), MAX(LastPublished), ( SELECT COUNT(*) FROM PublishedData inr WHERE inr.DirectName = outr.DirectName ...
Group by not working to get count of a column with other max record in sql
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]