Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have this table ``` ID Name Price 1 John 12 € 2 John 35 € 3 Alex 15 € 4 Alex 12 € 5 James 10 € ``` I need a query that update a field in another table, summing up all the values in price field that have the same name. For example the r...
With Access 2010 and later we can use [Data Macros](http://office.microsoft.com/en-ca/access-help/create-a-data-macro-HA010378170.aspx) to accomplish this: ![MacroList.png](https://i.stack.imgur.com/5MZRW.png) ![AfterDelete.png](https://i.stack.imgur.com/ulXuZ.png) ![AfterUpdate.png](https://i.stack.imgur.com/5PSoY....
``` INSERT INTO tableName2(name, price) SELECT name, SUM(price) FROM tableName GROUP BY name ``` TableName2 is the second table you wrote on your question, while the tableName is the first one. Notice this would ADD them into the table, not really update (since otherwise you'd have to insert all the data manually).
Update totals in another table when changes made to the current table
[ "", "sql", "ms-access", "sql-update", "ms-access-2013", "" ]
I'm a complete SQL novice. I want to display a simple grid..... 1. **Sign up......>30.....30-60.....60-90.....>90.....Total** 2. **Feb**...............4..........30........... 6 ......... 0 .......40 3. **Mar** ............. 0 .........11 ...........1 ..........4 .......16 4. **Apr** 5. **May** etc 6. **Jun** etc Whe...
First select the time span per record, then group and count. Be careful not to have overlapping ranges. ``` select monthname, isnull(sum(lessthan30),0) as lt30, isnull(sum(between30and59),0) as btw30a59, isnull(sum(between60and89),0) as btw60a89, isnull(sum(between90and119),0) as btw90a119, isnull(sum(more...
I think something like this would fit your needs better. You can use Sum Function and a case statement to work like a count if. ``` SELECT DATENAME(MM,Datecreated), --This Function automatically gets the name of the month --Here is where you can use case statements like a count if. SUM(CASE WHEN DATE...
Running a select statement for each case
[ "", "sql", "" ]
``` SELECT *, COUNT(examID) AS ExamCount FROM ExamSession GROUP BY [examID], [userID], [sessionID] ``` This gives me a result set, but the `ExamCount` has a '1' in each row even if an exam is displayed in more than 1 row... I'm trying to get the number of times an `examID` appears in the result set. SO th...
# Code: ``` COUNT(examID) OVER(PARTITION BY examID) AS ExamCount ```
To elaborate a bit on jbarker answer ``` if object_id(N'dbo.groupTry',N'U') is not null drop table dbo.groupTry create table dbo.groupTry ( examID int, userID int, sessionID int, ExamCount int ) insert into dbo.groupTry values (1111, 1234, 4321, 1), (1111, 9876, 6789, 1), (1111, 8765, 5678, 1), (2...
count and group by to get totals
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table with the following columns: ``` Id [int] UserId [int] ProductId [int] Created [datetime] ``` Every user can select any product at any time. No restrictions. For a report I have to select all products which haven't been chosen for four weeks. I tried the following approach: ``` SELECT DISTINCT Product...
Using a simple GROUP BY query, you can select distinct products their respective last `Created` dates: ``` SELECT ProductId, MAX(Created) AS LastCreated FROM table GROUP BY ProductId ; ``` Now, this would just return all the products without filtering but you need to filter on `LastCreated`. Since that column...
if you use MSSQL: ``` SELECT DISTINCT ProductId FROM table WHERE Created BETWEEN dateadd(week,-3,getdate()) and dateadd(day,-1,getdate()) ; ``` **Edit:** Exclude today
Select fields from table which weren't added for the last four weeks
[ "", "sql", "" ]
I have two stored procedures. The first stored procedure value's using in second stored procedure. So I want to combine the two stored procedures into a single one. ``` Create procedure [carcallD] @carid varchar(10) as Begin select t.dtime, t.locid, t.vtid from Transaction_tbl t where ...
Try this ``` ALTER procedure [dbo].[Weekend] @carid varchar(50) as begin Declare @wday datetime, @yr varchar(50), @vtid integer, @locid integer, @day varchar(10), @year integer -- taking parameter value select @wday = t.dtime from Transaction_tbl t where Tbarcode=@carid set @day=datename(Weekday,@wday) ...
You can use output parameteres: ``` CREATE PROCEDURE GetImmediateManager @employeeID INT, @managerID INT OUTPUT AS BEGIN SELECT @managerID = ManagerID FROM HumanResources.Employee WHERE EmployeeID = @employeeID END ``` Get a look in this link: <http://technet.microsoft.com/en-us/library/ms378108(v=s...
Stored procedure take value from stored procedure itself in SQL Server
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a schema that looks like this: ``` create table image_tags ( image_tag_id serial primary key, image_id int not null ); create index on image_tags(image_id); ``` When I execute a query with two columns, it is ridiculously slow (eg, `select * from image_tags order by image_id desc, image_tag_id desc lim...
For `order by image_id desc, image_tag_id desc` sorting to be optimized via indexes you need to have this index: ``` create index image_tags_id_tag on image_tags(image_id, image_tag_id); ``` Only having a composite index (with little exceptions I presume, but not in this case) would help optimizer to use it to determ...
``` create index on image_tags(image_id, image_tag_id); ``` try indexing..
ORDER BY with two columns is much slower than ORDER BY on either column
[ "", "sql", "postgresql", "" ]
I have a table in SQL Server with two numeric columns. At least one of these numeric fields must be filled. How do I write a check constraint to verify this?
This can be done with a check constraint that verifies null value and matches the result with `or` ``` create table #t (i int , j int , constraint chk_null check (i is not null or j is not null)) ``` The following are the test cases ``` insert into #t values (null, null) --> error inser...
late answer, but here is a solution for Sql Server for any number of columns to check: ``` CONSTRAINT CK_one_is_not_null CHECK (COALESCE(col1, col2, col3) IS NOT NULL ) ```
I need a check constraint on two columns, at least one must be not null
[ "", "sql", "sql-server-2012", "" ]
I have the following query: ``` SELECT ShipperName, S.ShipmentID, DepartureDate FROM SHIPMENT S, SHIPMENT_ITEM SI WHERE S.ShipmentID = SI.ShipmentID AND Value > 1000 ORDER BY ShipperName ASC, DepartureDate DESC; ``` Returns these results: ``` International 4 2013-06-02...
You are selecting data that appear to come exclusively from the Shipment table (`ShipperName`, `S.ShipmentID`, `DepartureDate`), but you are joining that table to the `ShipmentItem` table, which apparently may have more than one row per Shipment. Your joined table has one row for each item (that is related to a shipmen...
You may need to add the DISTINCT keyword on your select statement. Like: ``` SELECT DISTINCT ShipperName, S.ShipmentID, DepartureDate FROM SHIPMENT S, SHIPMENT_ITEM SI WHERE S.ShipmentID = SI.ShipmentID AND Value > 1000 ORDER BY ShipperName ASC, DepartureDate DESC; ```
Microsoft SQL Server duplicate results from query
[ "", "sql", "join", "duplicates", "" ]
I want to find a credit card numeric value in a sql string. for example; ``` DECLARE @value1 NVARCHAR(MAX) = 'The payment is the place 1234567812345678' DECLARE @value2 NVARCHAR(MAX) = 'The payment is the place 123456aa7812345678' DECLARE @value3 NVARCHAR(MAX) = 'The payment1234567812345678is the place' ``` The resu...
You can write as: ``` SELECT case when Len(LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1)) = 16 then LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1) else '' end FROM ( SELECT subsrt = SUBSTRING(string, pos, LEN(string)) FROM ( SELECT string,...
You can use PathIndex as ``` PATINDEX('%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', yourStr) ``` if the result is 0 then it doesnt containg 16 digits other was it contains. It can be used withing a `Where` statement or `Select` statement based on your needs
search in a string creditcard numeric value
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table with ``` Name EnteredDateID RecvdDateID A 20140901 20240901 B 20140901 20140901 C 20140901 20140901 D 20140901 20140901 E 20140901 20110901 F 20140901 20140901 G 20140901 20110901 ``` I need to write a query that would...
You can use ``` SELECT * FROM TABLEA WHERE 20140630 < CASE WHEN RecvdDateID > GETDATE() THEN EnteredDateID ELSE RecvdDateID END ```
``` SELECT * FROM TABLEA WHERE (RecvdDateID > GETDATE() AND EnteredDateID > 20140630) OR (RecvdDateID <= GETDATE() AND RecvdDateID > 20140630) ```
Using IF or Case to determine what field to use in a WHERE statement
[ "", "sql", "sql-server-2008", "t-sql", "" ]
I have a table filled with profile IDs in a sql server database: ``` select WhateverID from Whatevers ``` With each ID return from this query, I need to run a series of 5 stored procs in order against it, like so: ``` EXEC MyStoredProc WhateverID, 'Value 1' EXEC MyStoredProc WhateverID, 'Value 2' EXEC MyStoredProc W...
You can use dynamic sql here quite effectively by building your dynamic string and then executing the whole thing in one step. Here is a simple example of how you could do this. The exec statement is commented out but you should get the idea. ``` create table #Something ( WhateverID int ) insert #Something (Whate...
Don't use a cursor, a simple, narrow (Ids only) table-valued in-memory variable will suffice. ``` declare @Ids table (id integer primary key not null) Insert @ids(id) Select whateverId from whatevers Declare @id integer While exists(Select * from @ids) Begin Select @id = Min(id) From @ids EXEC MyStoredProc @id, ...
running a stored proc from a select statement with or without loop
[ "", "sql", "sql-server", "t-sql", "" ]
I am trying to get row count in SQL Server 2008. I am using join which works perfect, I just want to get the total records because at the moment total records go beyond thousand. ``` select tablet.Approach.ApproachId,StartDateTime,QuestionId from Tablet.Approach join tablet.DataCapture on tablet.Approa...
You can achieve it like this - **Solution: 1** ``` SELECT tablet.Approach.ApproachId ,StartDateTime ,QuestionId ,COUNT(*) OVER () AS TotalRowCount FROM Tablet.Approach JOIN tablet.DataCapture ON tablet.Approach.ApproachId = tablet.DataCapture.ApproachId WHERE QuestionId = 25 ``` **Solution: 2** (Using CT...
try this ``` select count(*), tablet.Approach.ApproachId,StartDateTime,QuestionId from Tablet.Approach join tablet.DataCapture on tablet.Approach.ApproachId = tablet.DataCapture.ApproachId where QuestionId = 25 group by tablet.Approach.ApproachId,StartDateTime,QuestionId ```
How to use Count(*) with sql joins
[ "", "sql", "sql-server", "" ]
I am trying to migrate a Drupal site to a new host. In the tutorials I read I need an .sql export of the database, as well as the files (I have these). I don't have access to the old hosting phpmyadmin method but I used backup and migrate module on Drupal which created a file with .mysql extension. After a few failed ...
You should try back up & migrate module to import the file smoothly. .mysql file may not work if you try to import from phpmyadmin. Instead, install backup & migrate and then restore the db.
**Yes**, you can just change it to SQL. Every relational database server uses a SQL a bit different from the SQL standard, but usually they use the same extension: sql.
Can I change a .mysql file to .sql or is it more complex than that?
[ "", "mysql", "sql", "drupal", "" ]
I have the following table containing data about how each group solves problems: ``` PROB | GROUP | REPNO | STATUS -----+---------+-------+------- 1 | Juniors | 0 | 1 | Seniors | 1 | 1 | Juniors | 2 | 1 | Experts | 3 | SOLVED 2 | Juniors | 0 | 2 | Seniors | 1 | SOLVED ``` C...
USE RANK() `SQL FIDDLE` ``` select PROB, GROUP1, REPNO, DECODE(GROUP1,'Juniors', rank() over (partition by prob, group1 order by repno) - 1) as REPNO_J, DECODE(GROUP1,'Seniors', rank() over (partition by prob, group1 order by repno) - 1) as REPNO_S, DECODE(GROUP1,'Experts', rank() over (partition by pro...
Use the ROW\_NUMBER windowing function to get the number per group: ``` select prob, "GROUP", repno, case when "GROUP" = 'Juniors' then try end as repno_j, case when "GROUP" = 'Seniors' then try end as repno_s, case when "GROUP" = 'Experts' then try end as repno_e, status from ( select prob, ...
Reorder within a group
[ "", "sql", "oracle", "" ]
We are using the following trigger in SQL Server to maintain the history now I need to identify the operations just like insert,update or delete. I found some information [HERE](https://stackoverflow.com/questions/2965521/oracle-and-triggers-inserted-updated-deleted) but it doesn't works with the SQL Server. ``` CREAT...
For Inserted : Rows are in inserted only. For Updated: Rows are in inserted and deleted. For Deleted: Rows are in deleted only. ``` DECLARE @event_type varchar(42) IF EXISTS(SELECT * FROM inserted) IF EXISTS(SELECT * FROM deleted) SELECT @event_type = 'update' ELSE SELECT @event_type = 'insert' ELSE IF EXI...
This is a simplified version of Mikhail's answer that uses a [searched CASE expression](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver15). ``` DECLARE @Operation varchar(7) = CASE WHEN EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted) TH...
How to identify the operation type(insert,update,delete) in SQL Server trigger
[ "", "sql", "sql-server", "triggers", "" ]
I am accesing to the database using a Dto with some entities and I want to improve the request without modifing my dto and removing the fetch so hibernate don´t return all the data from all the entities (hibernate is set to lazy), I tried with the next, but it´s not working: ``` StringBuilder hql = new StringBuild...
At the end I just create a dto like this: ``` DocumentDto{ private id private String clasificacionEntityDtoCod; } ``` and set it like this: ``` StringBuilder hql = new StringBuilder(); hql.append(" select d.id as id, ce.cod as clasificacionEntityDtoCod "); hql.append(" from Document d"); hql....
When you write this code: ``` hql.append(" select d.id as id, ce.cod as clasification.cod "); ``` You tell on parser `d.id` named `id` and `ce.cod` named `clasification.cod` The last alias is wrong! A correct name is `clasification` or `cod`. If you want to point properties of ce.cod (cod which data type has?) you ...
Hql query using dot´s in the response parameters
[ "", "sql", "spring", "hibernate", "hql", "dto", "" ]
I have a stored procedure which takes into input two table types (each of which contain only one ID column). These are filters which need to be applied to the main query inside the stored procedure. I was doing it by joining the main query with these two table type parameters. Something like below: ``` SELECT <cols...
Something like this maybe - instead of inner joins, I have used left joins and then all 4 conditions go into the where clause. ``` declare @countv1 int, @countv2 int select @countv1 = COUNT(1) from @tableVar1 select @countv2 = COUNT(1) from @tableVar2 SELECT <cols> FROM <table> t left join @tableVar1 v1 ...
You can achieve conditional Join using [`Dynamic SQL Query`](http://msdn.microsoft.com/en-us/library/ms188001.aspx) like ``` Declare @CntVar1 int Declare @CntVar2 int Declare @ExSQL nvarchar(max) select @CntVar1 = COUNT(1) from @tableVar1 select @CntVar2 = COUNT(1) from @tableVar2 Set @ExSQL= 'Select <cols> FROM <ta...
Conditionally Adding / Removing Joins in a SQL statement
[ "", "sql", "sql-server", "t-sql", "" ]
When I am using **rownum** and **between** keywords then the query doesn't return any rows. Can anyone explain the reason why query is not retrieving any rows? ``` select * from cus where rownum between 2 and 6; ``` I just want to check whether rownum will work when it is used with between keyword .So ,I just tried t...
Oracle rownum starts at 1, so you will never get the first rownum if you say `between 2 and N`. It takes a row to "initiate" the rownum pseudocolumn sequence, so by eliminating rownum 1 in your criteria, you eliminate all rownums (or every row essentially has rownum `0`). Look at it like this. You don't get a ROWNUM ...
> select \* from cus where rownum between 2 and 6; That is completely wrong. Because, `ROWNUM` is a pseudo-column which increments to 2 only when it started at `ROW` one(random, of course). In your query, the predicate `ROWNUM BETWEEN 2 AND 6` is meaningless, since ROWNUM has not yet been assigned. Let's understand t...
row num is not displaying any rows when using between keyword
[ "", "sql", "oracle", "oracle11g", "between", "rownum", "" ]
This is probably a pretty basic question but I'm trying to produce a histogram of order total values (exclusive of shipping & tax) for a given month. Unfortunately there's no column in the table for the total, so it needs to be calculated from the subtotal minus any discounts or applied credits. I thought something l...
This should work: ``` select t.range as [price range], COUNT(*) as [orders] from ( select case when (o.subtotal - o.discount - o.credit) between 0 and 49.99 then '0-49.99' when (o.subtotal - o.discount - o.credit) between 50 and 99.99 then '50-99.99' when (o.subtotal - o.discount - o.credit...
Try this format for your case statmenets ``` select sum(case when o.subtotal - o.discount - o.credit between 0 and 49.99 then 1 else 0 end) as bucket1, sum(case when o.subtotal - o.discount - o.credit between 50 and 99.99 then 1 else 0 end) as bucket2, sum(case when o.subtotal - o.discount - o.credit betw...
SQL select case with SUM?
[ "", "sql", "sql-server", "" ]
How can I avoid getting this MySQL error **Incorrect column specifier for column topic\_id** ? MySQL Error... ``` #1063 - Incorrect column specifier for column 'topic_id' ``` SQL Schema... ``` CREATE TABLE discussion_topics ( topic_id char(36) NOT NULL AUTO_INCREMENT, project_id char(36) NOT NULL, topic...
To use `AUTO_INCREMENT` you need to deifne column as `INT` or floating-point types, not `CHAR`. `AUTO_INCREMENT` use only unsigned value, so it's good to use `UNSIGNED` as well; ``` CREATE TABLE discussion_topics ( topic_id INT NOT NULL unsigned AUTO_INCREMENT, project_id char(36) NOT NULL, topic_subj...
The `auto_increment` property only works for numeric columns (integer and floating point), not `char` columns: ``` CREATE TABLE discussion_topics ( topic_id INT NOT NULL AUTO_INCREMENT, project_id char(36) NOT NULL, topic_subject VARCHAR(255) NOT NULL, topic_content TEXT default NULL, date_created ...
How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?
[ "", "mysql", "sql", "auto-increment", "ddl", "" ]
I've seen a few answers to questions similar to mine but I cannot get them to work. I have several date fields in my query that return the date and time like such 7/1/2014 12:00:00 AM. Is there a way I can just have the fields show 7/1/2014? ``` SELECT DISTINCT C.RECEIPTDATE, (I.CLIENTID ||' - '||PO.CLIENTNAME) AS CLI...
Use to\_char function: ``` SELECT DISTINCT to_char(C.RECEIPTDATE,'DD/MM/YYYY'), (I.CLIENTID ||' - '||PO.CLIENTNAME) AS CLIENT, D.INVOICEID, D.SVCFROMDATE, D.SVCTODATE, D.SVCCODE FROM M_EQP_ORDERS WHERE..... ```
Just use the function TRUNC. ``` SELECT DISTINCT TRUNC(C.RECEIPTDATE), (I.CLIENTID ||' - '||PO.CLIENTNAME) AS CLIENT, D.INVOICEID, TRUNC(D.SVCFROMDATE), TRUNC(D.SVCTODATE), D.SVCCODE FROM M_EQP_ORDERS WHERE..... ```
Convert datetime field to just a date field in SQL (Oracle)
[ "", "sql", "oracle", "datetime", "" ]
How do we check version of Oracle on which we are working? How do we check the version of the interface on which we are working? I have tried ``` select v$ from version ; ```
`select banner from v$version;` should work. you can also use. `select version from PRODUCT_COMPONENT_VERSION where rownum = 1;`
There are multiple ways, to list a few of them : 1. ``` SQL> select banner from v$version where rownum=1; BANNER -------------------------------------------------------------------------------- Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production ``` 2. ``` SQL> set serveroutput on; SQL> ex...
How do we check version of Oracle
[ "", "sql", "oracle", "version", "" ]
Why won't `SSMS` process this script for me? ``` DECLARE @containsReturn AS CHAR(500) = 'ME@ME.co.uk; YOU@YOU.co.uk;' CREATE TABLE #x(ProblemColumn CHAR(500)); INSERT INTO #x VALUES(@containsReturn); SELECT * FROM #X; UPDATE #x SET ProblemColumn = REPLACE(ProblemColumn, char(13), '') WHERE CONTAINS(Pro...
One quick thing why you even care where clause in this case, just run the update statement like this ``` UPDATE #x SET ProblemColumn = REPLACE(ProblemColumn, char(13), '') ``` it will do the right thing. it will perform better too
Because the TSQL [`CONTAINS`](http://msdn.microsoft.com/en-us/library/ms187787.aspx) method takes a `NVARCHAR` as the second parameter and it cant implicitly convert `CHAR(13)` so you need to declare it as a variable which can be: ``` DECLARE @srch NVARCHAR(1) = CHAR(13) UPDATE #x SET ProblemColumn = REPLACE(Pro...
CONTAINS unhappy with char(13)
[ "", "sql", "sql-server", "" ]
If I have the following sample data: ``` ╔══════════════╦══════════════════╦════════════╦═══════╗ ║ Client ║ con_id ║ mat1_07_03 ║ Ccode ║ ╠══════════════╬══════════════════╬════════════╬═══════╣ ║ Clients Name ║ C13109BBFD511534 ║ $1,062.00 ║ NOFL ║ ║ Clients Name ║ C11AC9BBF74D6882 ║ $879.73 ║ N...
Just use conditional aggregation: ``` SELECT m.Client, CaseCount = COUNT(m.con_id), CONVERT(varchar(255), SUM(Convert(money, m.mat1_07_03)), 101) as AmtInDispute sum(case when cCode = 'NOFA' then 1 else 0 end) as NOFACaseTotal, sum(case when cCode = 'NOFL' then 1 else 0 end) as NOFLCaseTotal, FROM...
You can use conditional aggregation to get the other 2 columns. Using an aggregate function with a CASE expression to count the `Ccode` values that you want for each of the columns. ``` SELECT [Client]=MAX(m.Client) ,[CaseCount]=COUNT(m.con_id) ,NOFACaseTotal = sum(case when m.Ccode = 'NOFA' then 1 else ...
SQL GROUP BY with FILTER IN SELECT
[ "", "sql", "sql-server", "t-sql", "pivot", "" ]
I have two tables SurrogateKeys and SurrogateKeyRelatives. I will find out of there are records that satisfy a query joining both tables. I am playing with two options: ``` select count(*) from ( select top(1) sk.Username from SurrogateKeys as sk inner join SurrogateKeyRelatives as skr on sk.Id = skr.S...
``` select count(*) from ( select top(1) sk.Username from SurrogateKeys as sk inner join SurrogateKeyRelatives as skr on sk.Id = skr.SurrKeyId where sk.Username='John.Doe' and skr.SomeField = 1 ) Q1 ```
``` select top(1) CASE WHEN skr.SurrKeyId is null THEN 0 ELSE 1 END from SurrogateKeys as sk left join SurrogateKeyRelatives as skr on sk.Id = skr.SurrKeyId and sk.Username='John.Doe' and skr.SomeField = 1 ```
Select count from subselect syntax
[ "", "sql", "sql-server", "t-sql", "left-join", "" ]
I have a table with data like: ``` col1 col2 col3 col4 1 A B Z-A.P-E-001.02 2 A B Z.01 3 A B Z.02 4 A B Z-A.P-E-001.01 5 C D M.01 6 C D M.02 ``` I want to find values in col4 having numbers at the end (number after last '.'). e.g. in this scenario expected o...
This is how I came to an answer with the help from Melvin Smith: ``` SELECT SUBSTR(col4, 0, instr(col4, regexp_substr(col4, '\.\d+$')) -1) AS VALUE, col4 FROM new_test where regexp_like(col4, '\.\d+$'); ``` @Melvin: Thanks a ton!!!!!
Use Orace's regex functions, `regexp_substr()` and `regexp_like()` I'm not sure what your actual requirements are, but something like this (off top of my head): ``` -- will match up to dot, but not including select regexp_substr(col4, '^\w+') as value, col4 from tab where regexp_like(col4, '\d'); -- ...
Find value and corresponding entries with number at the end
[ "", "sql", "oracle", "" ]
A very simple representation of my problem is: Reviews ``` | mentor_id | mentee_id | status | created | | 1 | 2 | active | 2014-08-13 | | 1 | 2 | inactive | 2014-08-20 | | 1 | 2 | inactive | 2014-08-27 | | 1 | 3 | inactive | 2014-08-20 | | 1 ...
Your question isn't crystal clear, but I think you are asking for: ``` SELECT DISTINCT u.* FROM reviews r JOIN mentorship m ON m.mentee_id = r.mentee_id AND m.mentor_id = r.mentor_id JOIN user u ON u.id = r.mentee_id WHERE r.status = 'inactive' AND DATEDIFF(r.created, m.created) >= 14 ...
Check this ``` select user.id,user.first_name,user.last_name,max(Reviews.created) RCreated, Mentorship.created MCreated from Reviews inner join User on Reviews.mentee_id=USer.id inner join Mentorship on Reviews.mentee_id=Mentorship.mentee_id where status='inactive' group by User.id havi...
Get results depending on time-based conditions
[ "", "mysql", "sql", "" ]
I need to be able to change an AND condition of an inner join based on a flag. I tried the following based on [this SO answer](https://stackoverflow.com/questions/10256848/can-i-use-case-statement-in-a-join-condition), and while it compiles, when you run it never completes. Any thoughts? ``` SELECT Stuff, ... FROM Tab...
``` SELECT Stuff, ... FROM Table t1 INNER JOIN ... INNER JOIN ... ... INNER JOIN OTHER_TABLE t2 ON t1.ID = t2.ID AND ( ( @ParticipantsFlag = 'S' AND t2.STUDENT_ID IS NOT NULL ) or ( @ParticipantsFlag = 'A' AND t2.ADULT_ID IS NOT NULL )...
`or` conditions in joins can be quite expensive. I would recommend that you join the table twice: ``` LEFT JOIN OTHER_TABLE t2s ON @ParticipantsFlag = 'S' and t1.ID = t2.ID AND t2.STUDENT_ID IS NOT NULL LEFT JOIN OTHER_TABLE t2a ON @ParticipantsFlag = 'A' AND t1.ID = t2.ID AND t2.ADULT_ID IS NOT NULL ``...
Changing AND condition of a INNER JOIN based on a flag?
[ "", "sql", "sql-server-2008", "t-sql", "case", "inner-join", "" ]
We already have this table (`IPConfig`) in db. (Sql Server 2k8) ``` IP | Member ----------------------- 10.1.2.100 | Joe 10.2.2.200 | Maley ``` Now, I should have a query which should do this: 1. Leave current table intact. If table is not there, create one. 2. Insert new records (defined in the next versi...
If I understand correctly you only insert new unmatched IPs to dbo.IPConfig. Left outer join is the best choice here. Insert the results to your target table. ``` INSERT INTO dbo.IPConfig([IP], [Member]) SELECT a.[IP], a.[Member] FROM @TempTable a LEFT OUTER JOIN dbo.IPConfig b ON a.[IP]=b.[IP] WHERE b.[IP] is null ``...
You don't need any temp table, you could create a stored procedure though. The simplest way is described here [INSERT VALUES WHERE NOT EXISTS](https://stackoverflow.com/questions/17991479/insert-values-where-not-exists) ``` INSERT IPConfig (IP, Member) SELECT '10.1.2.100', 'Joe' WHERE NOT EXISTS ( SELE...
Insert rows (if not already exist) to a already existing table (in MS-SQL / T-Sql)
[ "", "sql", "sql-server", "t-sql", "triggers", "" ]
I want to access a weather table and sumamrise it in terms of days and months. I want some of the values to be AVG and some to be SUM. I want to underpin the resulting record with values from the collective data that represent the maximum count but after a few combinations, I have not managed it. **EXAMPLE DATA:** `...
Looks like a correlated subquery would do it, but not sure how well this will scale. ``` SELECT DATE(`day_date`) AS day , ( SELECT w1.`main_weather` FROM `weather` w1 where DATE(w1.`day_date`) = DATE(`weather`.`day_date`) GROUP BY DATE(`day_date`) ...
Try something like (untested): ``` select day_date, (select top 1 main_weather from MyTable t2 where date(t1.day_date) = date(t2.day_date) group by main_weather order by count(*) desc) as Max_MainWeather, avg (temp) as AvgTemp from MyTable t1 group by (day_date) ```
SQL - return rows for values with MAX COUNT
[ "", "mysql", "sql", "" ]
I have 2 tables like this: ![enter image description here](https://i.stack.imgur.com/Bmxn9.png) ![enter image description here](https://i.stack.imgur.com/Eh9tM.png) For example in first row from table 2 col value is 3661 and its equal to 'med' from table 1 I want to update class from table 1 with 'MED' and ... This...
I edited your code. you did not mention which database you use, Anyway try this: ``` UPDATE table1 SET class = ( CASE WHEN table2.col = table1.med THEN 'MED' -------------------------------- WHEN table2.col = table1.mgl THEN 'MG...
You want something like this: ``` UPDATE table1 SET class = COALESCE((SELECT MIN(CASE WHEN table2.col = table1.med THEN 'MED' WHEN table2.col = table1.mgl THEN 'MGL' . . . END) as newval ...
Compare 2 table columns and update new column
[ "", "sql", "" ]
For example, something like: `SELECT * FROM myTable WHERE myColumn LIKE '[0-9]n.[0-9]n'` Of course I know the syntax above will not work, but I m trying to explain: n digits, followed by a period, followed by n digits. Thanks
You could use following patters for **unsigned** decimal values: ``` SELECT *, CASE WHEN (x.Col1 LIKE '%[0-9]%.%[0-9]%' /*OR x.Col1 LIKE '.%[0-9]%' OR x.Col1 LIKE '%[0-9]%.' OR x.Col1 LIKE '%[0-9]%'*/) AND x.Col1 NOT LIKE '%[^0-9.]%' THEN 1 ELSE 0 END AS IsDec...
Do you need exactly n or just anything that will cast to decimal ``` select cast(varDec as Decimal(p,s)) where varDec not like '%[^.1-9]%' and varDec not like '%.%.%' and len(varDec) > 0 and varDec <> '.' ```
Is there a way to match any decimal number with T-SQL 'LIKE' expression?
[ "", "sql", "sql-server", "regex", "t-sql", "" ]
``` UPDATE Contact_UDF SET hasAttendedEvent = ( SELECT CASE WHEN c.Contact_ID IN (SELECT DISTINCT Contact_ID FROM Action a WHERE a.Action_Type_ID =39) THEN 1 ELSE 0 END FROM Contact c) ``` I'm running this small bit of SQL to set a flag in the Contact\_UDF table but keep running int...
To see why this gives this error, simply execute the subquery and conclude that it indeed returns more than one row: ``` SELECT CASE WHEN c.Contact_ID IN (SELECT DISTINCT Contact_ID FROM Action a WHERE a.Action_Type_ID =39) THEN 1 ...
Popovitsj and Laurence have it fairly well covered: Your sub query can return multiple rows which don't behave like a list of values than you can use in 'in expression. However, you can use the exists function instead so : ``` UPDATE Contact_UDF udf SET hasAttendedEvent = (SELECT CASE WHEN exists ( ...
"Subquery returned more than 1 value." error in SQL Manager
[ "", "sql", "sql-server", "" ]
I have problem in Sql Server for select only date part from DateTime. The value of DateTime is 2014-05-01 00:00:00.000. If tried this query I don't have error and the output is correct: ``` SELECT CONVERT(VARCHAR(10),'2014-05-01 00:00:00.000',110) 2014-05-01 ``` If tried this other query in the doTable: ``` SELECT...
I think the following is a better way to do what you want: ``` where date >= dateadd(day, 0, datediff(day, 0, getdate()) - 1) ``` This truncates the current date to midnight yesterday, which I am guessing is what you really want. For your method, try using format 120: ``` SELECT TOP 100 * FROM [n].[a2].[DOTABLE] WH...
Verified your query in SQL server 2008. It's running fine may be a specific issue related to SQL server 2005 for conversion between varchar and date time. You can add explicit conversion to date type here ``` SELECT TOP 100 * FROM [n].[a2].[DOTABLE] WHERE CAST( CONVERT(VARCHAR(10),data,110) as datetime) ...
Sql Server Select Only Date Part From DateTime
[ "", "sql", "sql-server", "datetime", "" ]
I'm in the process of writing a stored procedure (for SQL Server 2012) that is supposed to calculate the number of hours for our employee from 16-15th of every month. I have the following database structure ![My Database Structure](https://i.stack.imgur.com/IxAr0.jpg) I have written a stored procedure to calculate t...
I'd probably just do it the simple way: ``` declare @today date = convert(date,current_timestamp) declare @prev_month_end date = dateadd( day , -day(@today) , @today ) declare @period_start date = dateadd( day , 16 , @prev_month_end ) -- 16th of THIS month declare @period_end date...
Always start with start or an end of a month. E.g. Here's some logic **Start Date = Start date of previous month + 16** **End Date = Start date of current month + 15** Following might help you figure out the dates ``` -- First Day of the month select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) -- Last Day of previou...
Stored Procedure for Calculating hours from 16th of Every Month to 15 of every month
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "stored-procedures", "" ]
I have a simple table structure in my postgres database: ``` CREATE TABLE device ( id bigint NOT NULL, version bigint NOT NULL, device_id character varying(255), date_created timestamp without time zone, last_updated timestamp without time zone, CONSTRAINT device_pkey PRIMARY KEY (id ) ) ``` I'm often que...
It seems, like time resolves everything. I'm not sure what have happened, but currently its working fine. From the time I've posted this question I didn't change anything and now I get this query plan: ``` "Bitmap Heap Scan on device (cost=5.49..426.77 rows=110 width=166)" " Recheck Cond: ((device_id)::text = '35756...
Indexes are not used when you cast a column to a different type: ``` ((device_id)::text = '352184052470420'::text) ``` Instead, you can do this way: ``` (device_id = ('352184052470420'::character varying)) ``` (or maybe you can change device\_id to TEXT in the original table, if you wish.) Also, remember to run `a...
Index doesn't improve performance
[ "", "sql", "postgresql", "indexing", "query-performance", "" ]
I am creating a table to store data from various government reports. An example row in the table would be: Values\_table ``` Date Location Report Attribute Value '2014-09-29' 'U.S.' 'LM_HG201' 'Price' 210 ``` Obviously I do not want to save strings for all of these columns, so I...
Normalization rules and business requirements ought to drive your design. If Location is repeated for several reports, it might make sense to normalize it. I would not split out Price, because that would appear to be unique to a report. Repetitions down to the penny would be serendipity. You should learn [how to des...
``` SELECT V.Value FROM Values_table V INNER JOIN locations_table L ON L.id = V.location INNER JOIN attributes_table A ON A.Id = V.attribute INNER JOIN descriptors_table D ON D.id = V.descriptor_id WHERE L.location = 'U.S' AND A.attribute = 'price' AND D.report = 'LM_HG201' ```
MYSQL - Should I use multiple subtables or one subtable for data descriptors?
[ "", "mysql", "sql", "" ]
I am very very new to SQL language, and trying to execute the following code. It gives me an error message below.. What did I do wrong? Error Message: ``` ORA-00928: missing SELECT keyword 00928. 00000 - "missing SELECT keyword" ``` Code: ``` WITH ABC(one,two,three) AS( select 25, 15,23 from dual ) INSERT INTO...
You need another "table" that returns the number of rows you want. In Oracle this is usually done using an undocumented feature of the `connect by` operator: ``` select level as rn from dual connect by level <= 100 ``` The "undocumented" part is the fact that no real "connect" is done and no `start with` is supplied...
Why don't you try with `union all` like this: ``` WITH ABC(one,two,three) AS( select 25, 15,23 from dual union all select 10,11,12 from dual ) select * from ABC ```
SQL insert statement - missing select keyword
[ "", "sql", "oracle", "" ]
I have a table in SQL Server with this fiels: t1(Amount, Tax, Extra, Option1, Option2, Option3) I have a query like this: ``` Select (Amount/Tax*Extra)+Option1 as Value1, (Amount/Tax*Extra)+Option2 as Value2, (Amount/Tax*Extra)+Option3 as Value3 From t1 ``` It's possible to precalculate (Amount/Tax\*Extra) and use...
I usually use a CTE as follows: ``` ;WITH cte AS ( SELECT (t1.Amount / t1.Tax * t1.Extra) AS [CalculatedValue], t1.Option1, t1.Option2, t1.Option3 FROM t1 ) SELECT cte.[CalculatedValue] + Option1 AS [Value1], cte.[CalculatedValue] + Option2 AS [Value2], cte.[Calculated...
I found the solution, the "persistent" command during creation was the solution. Ref. <http://blog.sqlauthority.com/2010/08/03/sql-server-computed-column-persisted-and%C2%A0performance/>
Avoid repetitive calculations in columns? SQL Server query
[ "", "sql", "sql-server", "calculated-columns", "" ]
I want to update a field when its Create date is from yesterday 2014-09-24 but the update does not happen although the conditions are fullfilled. I guess the problem is the time in the CreateDate field like "2014-09-24 12:25:00" so the match does not work. How can I compare only for the date? ``` UPDATE MyTable SET S...
Perhaps try to convert your column like this: ... AND CONVERT(VARCHAR(10), CreateDate,101) = '09/24/2014' -- SQL Server syntax used for conversion Another option would be to select a range ... AND CreateDate >= '2014-09-24' AND CreateDate < '2014-09-25'
Ideally, you'd do it this way: ``` UPDATE MyTable SET SentDate = NULL WHERE Category = 'test' AND CAST(CreateDate as Date) = '2014-09-24' ``` However, I see you're on Sql Server 2005, and the `Date` type isn't supported until Sql Server 2008. So instead, you should do it this way: ``` UPDATE MyTable SET SentD...
Query a datetime field without considering the time in T-SQL
[ "", "sql", "t-sql", "" ]
Hi i have the table **"users"** and **"jobs"** with following data USERS ``` +------+---------------+-----------+---------+---------------------+ | id | first_name | last_name | role_id | created | +------+---------------+-----------+---------+---------------------+ | 1026 | Administrator | Larvol ...
The expression `COUNT(NULLIF(Job.id, 0))` will be zero if there isn't an associated row in `Job`. Another way to check that there isn't an associated row in `Job` is to see if a required column in `Job` is null. I say *required column* because an optional column may be null anyway, whereas a required column will only ...
COUNT is an aggregation function. So without grouping something it doesn't mean anything. If you want an OR for those conditions then a solution might be a union of two queries with on one side the query without the having and just the role\_id = 3 condition and on the other side the query with the having COUNT conditi...
Use Count in mysql with AND, OR or NOT condition with or without HAVING?
[ "", "mysql", "sql", "database", "having", "" ]
I have a table where customer transactions are stored in this format: ``` Account Tran_type Tran_Amount tran_particular Tran_date 165266 C 5000 deposit 19_SEP-2014 165266 D 3000 withdrawal 20-SEP-2014 165266 C 8000 Deposit 21-SEP-2014 ...
``` select tran_date, tran_particular, Credit, Debit, SUM(Delta) OVER (ORDER BY tran_date) AS Balance from ( select tran_date, tran_particular, Case Tran_Type When 'C' THEN Tran_Amount Else 0 End AS Credit, Case Tran_Type When 'D' THEN Tran_Amount Else 0 End AS Debit, Case Tran_Type...
That will cost a sub-query: ``` SELECT tran_date, tran_particular, (CASE when tran_type = 'C' THEN tran_amt ELSE 0 end) CREDIT, (CASE when tran_type = 'D' THEN tran_amt ELSE 0 end) DEBIT, (SELECT SUM(CASE when type = 'C' tran_amt ELSE (-1) * tran_amt end) FROM tran_table trn2 WHERE trn2.Account = trn1.Acc...
Incremental adding in sql select
[ "", "sql", "oracle", "" ]
I want to create a stored procedure with the following parameter: `@WorkspaceID int` What I have now is this: ``` DECLARE @WorkspaceRuleIds varchar(max) SELECT @WorkspaceRuleIds = COALESCE(@WorkspaceRuleIds + ', ', '') + CAST(RuleID AS varchar(5)) FROM Dgn_Workspace_Rules WHERE WorkspaceID = @WorkspaceID; SELE...
Thanks guys for your help but.. I found an answer for my question. ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX)) RETURNS @TempTab TABLE (id int not null) AS BEGIN ;-- Ensure input ends with comma SET @InStr = REPLACE(@InStr + ',', ',,', ',') ...
1. there are several well know techniques to concatenating row values. Read [Concatenating Row Values in Transact-SQL](https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/) for pros and cons of each. 2. `ag.RuleID IN (@WorkspaceRuleIds)` this does not do anything close to what you...
How do I return a string of numbers separated by comma as an array parameter in SQL
[ "", "sql", "sql-server", "" ]
I have four tables ``` store[store_id(pk),name] itemsA(item_id(pk),store_id,name) itemB(item_id(pk),store_id,name) itemC(item_id(pk),store_id,name) ``` I want a query to retrieve a store and the number of items that he have. something like : ``` select s.store_id ,s.name,count() as numberOfItems from store limit 100...
I would recommend doing this with correlated subqueries: ``` select s.store_id, s.name, ((select count(*) from itemsA a where a.store_id = s.store_id) + (select count(*) from itemsB b where b.store_id = s.store_id) + (select count(*) from itemsC c where c.store_id = s.store_id) ) as numbe...
Stores with no items will not show up with this query. If this is a requirement it will have to be tweaked somewhat. ``` SELECT s.store_id, COUNT(*) FROM Store s JOIN ItemA a ON a.store_id = s.store_id JOIN ItemB b ON b.store_id = s.store_id JOIN ItemC c ON c.store_id = s.store_id GROUP BY s.store_id ``` A simple mod...
optimise query with calculate field from several tables
[ "", "mysql", "sql", "" ]
The simple version What is the correct syntax of this? ``` INSERT INTO foo(IP, referer) VALUES(SELECT bin FROM dbo.bar("foobar"),"www.foobar.com/test/") ``` I am getting syntax errors near 'SELECT' and ')' The long version: I want to insert using a Function and a string (this is simplified, in reality there will be...
It should be like this - ``` INSERT INTO foo (IP, referer) SELECT bin, 'www.foobar.com/test/' FROM dbo.itvfBinaryIPv4('192.65.68.201') ``` here assume `dbo.itvfBinaryIPv4("192.65.68.201")` is table valued function.
The `INSERT` command comes in two flavors: **(1)** either you have all your values available, as literals or SQL Server variables - in that case, you can use the `INSERT .. VALUES()` approach: ``` INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN) VALUES(Value1, Value2, @Variable3, @Variable4, ...., ValueN) ``` Note:...
SQL Server: Inserting from various sources
[ "", "sql", "sql-server", "" ]
I want to index this query clause -- note that the text is static. `SELECT * FROM tbl where flags LIKE '%current_step: complete%'` To re-iterate, the `current_step: complete` never changes in the query. I want to build an index that will effectively pre-calculate this boolean value, thereby preventing full table scan...
If you don't want to change the query, and it isn't just an issue of nor changing the data maintenance (in which case a virtual column and/or index would do the job), you could use a materialised view that applies the filter, and let query rewrite take case of using that instead of the real table. Which may well be ove...
A full text search index might be what you are looking for. There are a few ways you can implement this: * Oracle has Oracle Text where you can define which type of full text index you want. * Lucene is a Java full text search framework. * Solr is a server product that provides full text search.
Oracle index for a static like clause
[ "", "sql", "oracle", "database-performance", "" ]
``` Declare int @NumberofPriorYears=2; Declare int @currentYear=2014; SELECT * FROM MyTable a WHERE a.FiscalYear in ( ``` When @NumberofPriorYears is 2 then i want to pass `@currentYear-@NumberofPriorYears` (i.e 2014,2013,2012) or when `@NumberofPriorYears` is null then pass `@currentYear` i.e 2014. Appreciate any ...
Can you use a range? ``` a.FiscalYear >= @currentYear-isnull(@NumberofPriorYears,0) and a.FiscalYear < @currentYear+1 ```
Try this ``` Declare int @numberofyears=2; Declare int @currentYear=2014; set @currentYear = datepart(year,getdate()) SELECT * FROM MyTable a WHERE datepart(year,a.FiscalYear) between @currentYear and @currentYear+@numberofYears ```
SQL Where condition for number of years
[ "", "sql", "sql-server", "" ]
Below is my scenario I have a table with columns Country and State. I have only one row with values USA and NY. Now if the user chooses NY then I have to display 'New York' and if other than NY then display 'No Records'. I tried the below Oracle sql and it is failing for me. When I enter other state like MA, I am ex...
Use `ELSE` instead. ``` SELECT CASE WHEN STATE='NY' THEN 'New York' ELSE 'No Records' end from abc where state in ('&state') ```
If you want to be sure that you get at one row, use aggregation: ``` SELECT (CASE WHEN max(STATE) = 'NY' THEN 'New York' ELSE 'No Records' END) from abc where state in ('&state'); ```
Case statement for null Records
[ "", "sql", "oracle", "" ]
i m running a sql query to select data from a table . i want to include headers as the first row in the result of the query. headers will be coming from some other table or can we can sqlhardcode the values . below is my query to fetch data. ``` select invoice_type_code, shipper_short_code , charge_type_code , ...
I don't see any extra effort to have the column names in the header the way you want, just mention an `ALIAS` to the columns the way you want. For example : `select col1 as "header1", col2 as "header2".... from table` In any `GUI/non GUI based tool`, the `scroll pane` automatically places the `table header` at the t...
Assuming Oracle DBMS, you can create the header row manually using DUAL table and then union with the real data. Use a dummy psuedo-column ("rno" in the example below) to sort the data. However, you have to convert any other datatype to VARCHAR to make this work. Idea is illustrated below: ``` select 'header1', ...
to include a header into result of sQL query
[ "", "sql", "oracle", "" ]
``` MERGE DestinationTable AS D USING SourceTable AS S ON D.Alternate_ID = S.ID WHEN MATCHED AND ( D.ID <> S.ID OR D.col1 <> S.col1 OR D.col2 <> S.col2 OR D.col3 <> S.col3 OR D.col4 <> S.col4 OR D.col5 <> S.col5 OR D.col6 <> S.col6 OR D.col7 <> S.col7 OR D.col8 <> S.col8 ) ``` Hi all, ...
``` MERGE DestinationTable AS D USING SourceTable AS S ON D.Alternate_ID = S.ID WHEN MATCHED AND ( D.ID <> S.ID OR (D.col1 IS NULL AND S.col1 IS NOT NULL) OR (D.col1 IS NOT NULL AND S.col1 IS NULL) OR D.col1 <> S.col1 OR (D.col2 IS NULL AND S.col2 IS NOT NULL) OR (D.col2 IS NOT NULL ...
You could do it a lot simpler with [`BINARY_CHECKSUM`](http://msdn.microsoft.com/en-us/library/ms173784.aspx): ``` MERGE DestinationTable AS D USING SourceTable AS S ON D.Alternate_ID = S.ID WHEN MATCHED AND BINARY_CHECKSUM(d.col1, d.col2, ...,d.col8) <> BINARY_CHECKSUM(s.col1, ..., s.col8) ``` There is a small ...
Comparing NULL against strings in SQL Server
[ "", "sql", "sql-server", "t-sql", "" ]
I have column A B C D I am trying to update Column C with divide functionality e.g. If Column C contains value 0.9 then i want to update that value in to 1/0.9= 1.33333 (round it to 1.3) So the column has to update from 0.9 to 1.3. Is there a way to do by `SQL` query with out store procedure?
Since you haven't indicated which database you are using, I will offer a query that works for both mysql, postgres and sqlserver (that covers most database instances): ``` UPDATE mytable SET columnC = CAST( 1 / columnC AS DECIMAL(8,1)) WHERE columnC = 0.9 ```
Try this: ``` UPDATE table SET columnC = 1 / columnC where columnC = 0.9 ```
update a column with condition thru Sql Query
[ "", "sql", "" ]
I have a SQL table which hold unique REFID (int) and many other columns. I wanted to search a row using the half REFID . So if someone just search **0001** then 50001, 00015... comes up. I have tried: ``` SELECT TOP 10 REFID FROM Tablename where REFID LIKE '%' + cast(0001 as varchar(10)) +'%' ``` however the pr...
I have found: 1. `cast('0001' as varchar(10))` as 0001 === 1 thanks to ALEX K. 2. SQL will strip leading zero and there is no way of keeping the zero if you don't know the length. My solution: I will send a string from my application and let SQL search it using the string.
# Code: ``` SELECT TOP 10 REFID FROM Tablename where REFID LIKE '%0001%' ```
Search half the refID in SQL
[ "", "sql", "" ]
Is there a way to, in a single query, return rows of `my_table where column_1 = "xxx"` if it does have results, and if it doesnt, return `where column_2 = "xxx"` ? Like a `select * from my_table where column_1 = "xxx" or column_2 = "xxx"` but only displaying the `column_2= "xxx"` if there is no results for `column_1 =...
Try this: ``` select * from my_table where (column_1 = "xxx" and exists (select null from my_table where column_1 = "xxx")) or (column_2 = "xxx" and not exists (select null from my_table where column_1 = "xxx")) ```
You can try this query: ``` select t.* from my_table t where column_1 = 'xxx' union all select t.* from my_table t where column_2 = 'xxx' and not exists (select 1 from my_table where column_1 = 'xxx'); ``` This should have reasonable performance if you have an index on `column_1` and another index on `column_2...
How to query a table for different columns based on first column result
[ "", "sql", "oracle11g", "" ]
If primary keys are always sorted, how can I store Guids in random order as primary key.
Well, *primary keys* aren't necessarily stored in sorted order on the disk. But *clustered indexes* are. And in the vast majority of cases the primary key is the clustered index. Though this doesn't necessarily guarantee sorting of results, it's just that results are usually sorted by the clustered index by default. >...
No, the table data is not always stored in the order of the primary key, but usually the primary key has a clustered index, and the data is always stored in the order of the clustered index. If you don't want the data stored in the order of the primary key, you should use a non-clustered index for it. Note that event...
Are primay keys stored in sorted order or do they just appear sorted by SQL statement?
[ "", "sql", "sql-server", "guid", "" ]
I have to query from an `oracle 11` db. With the query below I get all recent `TAG_VALUE, TAG_DESC, INSERTION_DATE and PROJECT_ID` from my database. ``` SELECT * FROM (SELECT t.tag_value, t.tag_desc, u.update_as_of AS INSERTION_DATE, p.proj_id ...
Considering that your grouping happens within PROJECT\_ID for INSERTION\_DATE DESC and a positive TAG\_VALUE, I tweaked the analytical functions to achieve the result. This may not be a robust solution, but will certainly help you. **Data Setup:** ``` CREATE TABLE Table1 ("TAG_VALUE" varchar2(5), "TAG_DESC" varch...
Your question is: "How, can I basically ignore all null and also 0 values values" The simple answer is: By removing those records in the WHERE clause. I use `AND t.tag_value > 0` here. You can replace it with `AND t.tag_value <> 0 AND t.tag_value IS NOT NULL`, if you want to allow negative values. ``` SELECT * FROM...
Query only numeric values of the earliest possible date
[ "", "sql", "oracle", "oracle11g", "" ]
Using Oracle, how do you select current date (i.e. SYSDATE) at 11:59:59? Take into account that the definition of midnight [might be a little ambiguous](https://english.stackexchange.com/questions/6459/how-should-midnight-on-be-interpreted) (Midnight Thursday means Straddling Thursday and Friday or Straddling Wednesda...
To select current date (Today) before midnight (one second before) you can use any of the following statements: ``` SELECT TRUNC(SYSDATE + 1) - 1/(24*60*60) FROM DUAL SELECT TRUNC(SYSDATE + 1) - INTERVAL '1' SECOND FROM DUAL; ``` What it does: 1. Sum one day to `SYSDATE`: `SYSDATE + 1`, now the date is Tomorrow 2. R...
Personally, I dislike using one second before midnight. Among other things, if you're using a `timestamp`, there's a possibility that the value you're comparing to falls between the gaps (i.e. 23:59:59.1). Since this kind of logic is typically used as a boundary for a range condition, I'd suggest using "less than midni...
Oracle: How to select current date (Today) before midnight?
[ "", "sql", "database", "oracle", "" ]
I've only used MySQL before. Postgres is a little different for me. I'm trying to use the Postgres.app for OSX. I have a database dump from our development server, and I want to create the correct user roles and import the database to my local machine so I can do development at home (can't access the database remotely)...
It sounds like you probably loaded the dump into the database you were connected to. If you didn't specify a database when you started `psql` it'll be the database named after your username. It depends a bit on the options used with `pg_dump` when the dump file was created though. Try: ``` psql -v ON_ERROR_STOP=1 ...
**Mac users: If you are here in 2023 and are on the Mac operating system and you have created a database dump using pg\_dump utility** **A. The dump is taken in SQL format (simple one)** ``` pg_dump -U <USER_NAME> -h <DATABASE_HOST> <DB_NAME> > sample.sql ``` Then in order to restore it use the below command. First...
Import PostgreSQL dump on OSX
[ "", "sql", "database", "macos", "postgresql", "postgres.app", "" ]
I have a table with columns for a start- and enddate. My goal is to get a list of each year in that timespan for each row, so ``` +-------------------------+ | startdate | enddate | +------------+------------+ | 2004-08-01 | 2007-01-08 | | 2005-06-02 | 2007-05-08 | +------------+------------+ ``` should output th...
Try this Query ``` ; with CTE as ( select datepart(year, '2005-12-25') as yr union all select yr + 1 from CTE where yr < datepart(year, '2013-11-14') ) select yr from CTE ```
***Row Generator technique*** ``` SQL> WITH DATA1 AS( 2 SELECT TO_DATE('2004-08-01','YYYY-MM-DD') STARTDATE, TO_DATE('2007-01-08','YYYY-MM-DD') ENDDATE FROM DUAL UNION ALL 3 SELECT TO_DATE('2005-06-02','YYYY-MM-DD') STARTDATE, TO_DATE('2007-05-08','YYYY-MM-DD') ENDDATE FROM DUAL 4 ), 5 DATA2 AS( 6 SELEC...
List of years between two dates
[ "", "sql", "oracle", "" ]
After much searching the web and Stackoverflow, still looking for a way to use ALIAS to return columns without producing a new row/line. The following works create the columns "Sig\_1\_Emp" and "Sig\_3\_Staff", but the data for Sig\_1\_Emp and Sig\_3\_Staff are not in the same row, but two rows. ``` CASE WHEN Vis...
Given your update to the question, it's clear that what you're missing is a `GROUP BY` clause with appropriate aggregation functions. Note that in your sample result, the first four columns (`clientvisit_id`, `program_id`, `visittype`, `rev_timein`) contain identical values in both sample rows. If you `GROUP BY` those...
If I'm understanding your question correctly, you're trying to `pivot` your results. You can use the `max` aggregate with the `case` statement to do this: ``` select otherfields, max(CASE WHEN VisitSignatures.order = 1 THEN Employees.last_name END) AS Sig_1_Emp, max(CASE WHEN VisitSignatures...
sql, case when then as
[ "", "sql", "case", "alias", "" ]
``` table1 time userid id1 id2 9/1/2014 3:30 user1 123 555 9/1/2014 3:32 user1 123 555 9/1/2014 3:13 user1 123 555 9/1/2014 3:15 user1 123 555 9/1/2014 3:38 user2 321 555 9/1/2014 3:21 user2 321 555 9/1/2014 3:38 user2 456 666 9/1/2014 3:21 user2 456 666 table2 id1 orderi...
**Q: Does mysql do the left join first or where statement first? Should store the order 555 into different table then run they query?** In theory, the optimizer is free to choose any execution plan that produces the specified result. The optimizer is supposed to be smart enough to choose an order of operations that it...
The problem is your distinct operation, that one is very expensive. You might make it more efficient by putting an index on userid, the two keys also should have an index. I'm not sure what you are trying to do functionally but maybe something else is possible too as an alternative.
mysql query is slow, need help to optimize
[ "", "mysql", "sql", "" ]
So I have 1 **(one)** table contains a list of games. For example: 1st row: `team1 = abc; team2 = xyz;` 2nd row: `team1 = xyz; team2 = abc;` 3rd row: `team1 = asd; team2 = jkl;` I've got about 4,000 rows like this. 2 teams may have played each other many times. Each row is a separate game. A user enters a `team1` ...
Your query would return any game in which either `$team1` or `$team2` has played. From your question I understand that you really want any game where `$team1` played against `$team2`, so I'd try ``` SELECT * FROM matches WHERE (team1 = '$team1' AND team2 = '$team2') OR (team1 = '$team2' AND team2 = '$team1') ...
You could do this with logical operators: ``` SELECT * FROM matches WHERE (team1 = '$team1' AND team2 = '$team2') OR (team1 = '$team2' AND team1 = '$team2') ```
Only showing results that are the same from 2 queries
[ "", "mysql", "sql", "" ]
Can anyone with DEADLOCK experience enlighten me? I read that it can cause log file corruption - is that possible? I think MS would never do that. Also if "some situations", like mine, are okay with DEADLOCK, why not use it? I have no datasets, return tables (like other posts in Stack Overflow). I have one SQL statem...
After deep searches and asking questions to many experts I found out that using NOLOCK hint causes no problem in this scenario, yet its not advised. nothing wrong with NOLOCK but as I use sql2014 I "should" use ISOLATION LEVEL option. Its a method came instead of NOLOCK. For example for huge table selects that cause de...
`NOLOCK` has two main disadvantages: It can return uncommitted data (you don't seem worried about that) and it can cause queries to spuriously fail under very rare circumstances. Never will `NOLOCK` cause physical database corruption. Consider using snapshot isolation for transactions that only read data. Readers unde...
Using NOLOCK for reading single static row. Whats the harm?
[ "", "sql", "sql-server", "deadlock", "" ]
I have two tables (SQL Fiddle available [here](http://sqlfiddle.com/#!2/0bcb5b)): People ``` ID Company_ID Name 1 1 Jones 2 2 Smith 3 3 Kim 4 2 Takahashi 5 3 Patel 6 ...
You should `join` both tables: ``` SELECT p.* FROM People p JOIN Companies c ON c.ID = p.CompaniyID WHERE --(Some where clause) ORDER BY c.Name ASC ```
``` SELECT * FROM People INNER JOIN Companies ON Company_ID = Companies.ID ORDER BY Companies.Name ```
Order BY one table in MySQL
[ "", "mysql", "sql", "" ]
I have the following scenario. **SOURCE TABLE 1** ``` CREATE TABLE #Table1 ( Div varchar(10), Dept varchar(10), States varchar(10) ) INSERT INTO #Table1 SELECT 'Div1','Dept1','CA,NV,TX' UNION ALL SELECT 'Div2','Dept2','MI,OH,IN' UNION ALL SELECT 'Div3','Dept2','NY,NJ,PA' UNION ALL...
Your requirements are very nasty but as developers we have to work with what we've got. Here's a solution using Common Table Expression (CTE) extensively: ``` ;WITH CTE1 AS ( SELECT Div, Dept, REPLACE(States,' ','') + ',' AS States FROM Table2 ), CTE2 AS ...
Ok, so first of all, you'll need to split the concatenated values in `#Temp1` and `#Temp2`. There are various methods for doing so, I'll use the **numbers table** one that is described [in this awesome blog](http://sqlperformance.com/2012/07/t-sql-queries/split-strings) post from Aaron Bertrand. So, we'll need a number...
T-SQL | String "Manipulation" and Aggregation
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
In the spark docs it's clear how to create parquet files from `RDD` of your own case classes; (from the docs) ``` val people: RDD[Person] = ??? // An RDD of case class objects, from the previous example. // The RDD is implicitly converted to a SchemaRDD by createSchemaRDD, allowing it to be stored using Parquet. peop...
The best solution I've come up with that requires the least amount of copy and pasting for new classes is as follows (I'd still like to see another solution though) First you have to define your case class, and a (partially) reusable factory method ``` import org.apache.spark.sql.catalyst.expressions case class MyCl...
An easy way is to provide your own converter `(Row) => CaseClass`. This is a bit more manual, but if you know what you are reading it should be quite straightforward. Here is an example: ``` import org.apache.spark.sql.SchemaRDD case class User(data: String, name: String, id: Long) def sparkSqlToUser(r: Row): Optio...
How to convert spark SchemaRDD into RDD of my case class?
[ "", "sql", "apache-spark", "parquet", "" ]
I know that you can get column names from a table via the following trick in hive: ``` hive> set hive.cli.print.header=true; hive> select * from tablename; ``` Is it also possible to **just** get the column names from the table? I dislike having to change a setting for something I only need once. My current solutio...
If you simply want to see the column names this one line should provide it without changing any settings: ``` describe database.tablename; ``` However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using: ``` use database; describe...
you could also do `show columns in $table` or see [Hive, how do I retrieve all the database's tables columns](https://stackoverflow.com/questions/29239565/hive-how-do-i-retrieve-all-the-databases-tables-columns/33154251#33154251) for access to hive metadata
Just get column names from hive table
[ "", "sql", "hadoop", "hive", "" ]
I have data of the following format: ``` Date Value 08/28 100 09/01 1 09/01 5 09/10 2 ``` I would like my output to be: ``` Date Value 08/28 100 08/29 100 08/30 100 08/31 100 09/01 106 09/02 106 . . . 09/10 108 ``` I'm just g...
First, you can use a sub query to get the aggregate values ``` SELECT Date, (SELECT SUM(Value) FROM Directory d WHERE d.Date <= Directory.Date) FROM [Directory] WHERE Date <= @myDate ORDER BY Date ``` Which would give you something that looks like this: ``` Date Value 08/28 100 09/01 101 09/01 ...
Based on sgeddes suggestion: SELECT a.Date, COUNT(DISTINCT(d.Service)) AS Value ``` FROM [Directory] d LEFT OUTER JOIN [Date Table] a on d.Date = a.Date WHERE Date <= @myDate GROUP BY Date ORDER BY Date ```
Query to aggregate totals between dates
[ "", "sql", "aggregate-functions", "" ]
I'm new to SQL and am having trouble understanding why there's a `FROM` keyword in a `JOIN` statement if I use dot notation to select the `tables.columns` that I want. Does it matter which table I choose out of the two? I didn't see any explanation for this in w3schools definition on which table is the `FROM` table. In...
The order doesn't matter in an `INNER JOIN`. However, it does matter in `LEFT JOIN` and `RIGHT JOIN`. In a `LEFT JOIN`, the table in the `FROM` clause is the primary table; the result will contain every row selected from this table, while rows named in the `LEFT JOIN` table can be missing (these columns will be `NULL`...
The from statement refers to the join not the table. The join of table will create a set from which you will be selecting columns.
Explain which table to choose "FROM" in a JOIN statement
[ "", "mysql", "sql", "join", "" ]
I have the following table: ``` ID GROUPID oDate oValue 1 A 2014-06-01 100 2 A 2014-06-02 200 3 A 2014-06-03 300 4 A 2014-06-04 400 5 A 2014-06-05 500 FF. until the end of the month 30 A 2014-06-30 600 ``` I have 3 kinds of GROUPI...
You can use a correlated subquery to get this: ``` SELECT T.ID, T.GroupID, t.oDate, T.oValue, ct.TotalToEndOfMonth FROM T OUTER APPLY ( SELECT TotalToEndOfMonth = SUM(oValue) FROM T AS T2 WHERE T2.GroupID = T.GroupID AND ...
If you want grouped per GROUPID, year and month this should do it: ``` SELECT GROUPID, [MONTH] = MONTH(oDate), [YEAR] = YEAR(oDate), tot_oValue = SUM(ovalue) FROM your_table WHERE DAY(odate) > 1 GROUP BY GROUPID, YEAR(oDate), MONTH(oDate) ORDER BY GROUPID, YEAR(oDate), MONTH(oDate) ```
SUM from Specific Date until the end of the month SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'd like to insert these values in the following fashion: ``` insert into table (name, action-id) values ('user', select action from actions where name='user2'); ``` The result being: Inserts along the line of, `('user', 1) ('user', 2) ('user', 3)` I'm noticing this isn't correct sql. How would I go about accomplis...
You can do it with a loop: ``` BEGIN FOR x IN (select action from actions where name='user2') LOOP insert into table (name, action-id) values ('user', x.action) END LOOP; END; ``` or you could use the [INSERT/SELECT](http://docs.oracle.com/cd/E17952_01/refman-5.1-en/insert-select.html) syntax: `...
Add the fixed value as a column in your query, and use insert-select instead of insert-values: ``` insert into table (name, action-id) select 'user', action from actions where name='user2'; ```
Oracle) Insert multiple rows with one fixed value
[ "", "sql", "oracle", "" ]
I have a table with 782,856 records. There is a column PEOPLE\_TYPE in this table that is varchar(20). I don't think table schema matters but if it does I will gladly post it. It has these distinct values (parens is a count of each type): ``` NULL (782,101) ANONYMOUS (1) BOARD (530) USER (224) ``` So why does this s...
NULL is a strange thing. Any comparison with NULL is false: NULL = NULL is false NULL != anything is false NULL != NULL is also false. You have to say things like column is null, or column is not null. Your query would need ``` select * from people where PEOPLE_TYPE != 'BOARD' or PEOPLE_TYPE is null ```
You can read this for details on why records with NULL are not being returned: <http://msdn.microsoft.com/en-us/library/ms188048.aspx> If you want records with NULL to be returned you need to write the query like this: ``` select * from people where ISNULL(PEOPLE_TYPE, '0') != 'BOARD' ``` Or this: ``` select * from...
Why Select eliminating NULL records on a varchar comparison
[ "", "sql", "sql-server", "t-sql", "" ]
How to write a query to just determine that the values in a column are unique?
Try this: ``` SELECT CASE WHEN count(distinct col1)= count(col1) THEN 'column values are unique' ELSE 'column values are NOT unique' END FROM tbl_name; ``` Note: This only works if 'col1' does not have the data type 'ntext' or 'text'. If you have one of these data types, use 'distinct CAST(col1 AS nvarchar(4000))' (o...
``` select count(distinct column_name), count(column_name) from table_name; ``` If the # of unique values is equal to the total # of values, then all values are unique.
SQL query to determine that values in a column are unique
[ "", "sql", "sql-server", "t-sql", "" ]
I am having a bit of trouble with a query for SQL Server 2008. I have a table with some values and a category. This category can be e.g. Stock, Bond or NULL. Then I may want to see everything in my table that is not bonds: ``` SELECT Value, Name, Currency, Assetclass FROM MyTable WHERE Assetclass <> 'Bond' ``` Here...
As others have pointed out, this is the expected behavior. If you don't want to do an `OR` you could always replace null with something else in your comparison: ``` WHERE ISNULL(Assetclass, 'Anything but Bond') <> 'Bond' ```
This is the expected behaviour. You are asking for all the rows that have a value that is different from 'Bond'. `NULL` is not a value but a 'marker' stating that the system have no clue about the content of that field; being the content unknown the system cannot say for sure that the value is different from 'Bond' h...
Query not returning values for NULL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have the following table: ``` A B C D E F James Michael 123 Hello World 1 James Michael 123 Hello World 5 James Michael 123 Hello World 7 Harold Reynolds 345 There Poop 1 John Lowland 555 Woh Pop...
You can do this with the `ROW_NUMBER()` function: ``` ;with cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY "C" ORDER BY "F" DESC) AS RN FROM Table1) SELECT "A", "B", "C", "D", "E" FROM cte WHERE RN = 1 ``` Demo: [SQL Fiddle](http://sqlfiddle.com/#!15/a5878/3/0) The `ROW_NUMBER()` function generates a ...
We can use row\_number and partition the result and get only 1 row from the partition ``` Select * from ( select *, row_number() over ( partition by A, B, C,D ,E order by F desc ) as seq from tableA) T Where T.seq =1 ```
How do I select distinct data in a table based on a max value of one column?
[ "", "sql", "postgresql", "" ]
I need to select rows from BUNDLES table which have one of several SAP\_STATE\_ID values. Those values depends on whether respective SAP status is supposed to be exported or not. This query runs really fast (there is index on SAP\_STATE\_ID field) - ``` SELECT b.* FROM BUNDLES b WHERE b.SAP_STATE_ID IN (2,3,5,6) ``` ...
I am pretty sure your statistics are off on the tables. If you want to get it working in a hurry I would write the query as: ``` SELECT b.* FROM SAP_STATES s INNER LOOP JOIN BUNDLES b ON s.SAP_STATE_ID = b.SAP_STATE_ID WHERE s.EXPORT_TO_SAP = 1 ``` This forces a nested loops join over `SAP_STATES` which fil...
When you use tables(temporary or physical), the SQL engine builds statistics against it and thus has a very clear idea on the number of rows in it and which is the best execution approach for it. On the other hand, a computed table(sub query) doesn't have statistics against it. So while it might be seemingly simple fo...
Why is subquery and join so slow
[ "", "sql", "sql-server", "join", "" ]
So Im stumped at the approach I need to take. have a query here: ``` select type_type, RCD_REASON, rc.description, MATERIAL_ID, USERID, DATETIME_SCRAPPED, ORDER_NUMBER, TRIMDATE, SUBSTR(SALES_ORDER,3,8) || '-' || SUBSTR(SOL_LINE_NUMBER,3,4) AS SalesOr...
This is usually solved using window functions (you didn't specify your DBMS, but this is ANSI standard SQL supported by a wide range of DBMS). ``` select * from ( select type_type, RCD_REASON, rc.description, MATERIAL_ID, USERID, DATETIME_SCRAPPED, ...
Would it be something like? ``` select type_type, RCD_REASON, rc.description, MATERIAL_ID, USERID, (MAX)DATETIME_SCRAPPED as DATETIME_SCRAPPED, ORDER_NUMBER, TRIMDATE, SUBSTR(SALES_ORDER,3,8) || '-' || SUBSTR(SOL_LINE_NUMBER,3,4) AS SalesOrder, ...
Select Distinct or Group By for all but one column
[ "", "sql", "performance", "group-by", "duplicates", "distinct", "" ]
I have two tables with similar fields but the query is failing when I am doing a `SELECT` subquery in a `WHERE` clause. ``` SELECT foo FROM bar WHERE fizz IN (SELECT fizz FROM fuzz) ``` I deleted the `error.log` from AWS but the error was something to the extent that HIVE did not recognize the `SELECT`. How do I...
From the Subqueries in the WHERE Clause section of the [HIVE Language Manual](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SubQueries): ``` SELECT b.foo FROM bar b WHERE b.fizz IN (SELECT f.fizz FROM fuzz f) ```
Hive has problems with subquery in the WHERE clause use a JOIN ``` SELECT foo FROM bar JOIN fuzz ON bar.fizz=fuzz.fizz ```
HIVE SQL Subquery in WHERE Clause
[ "", "sql", "hive", "" ]
I have a function in a VB .NET class library, which inserts XML text into a VARCHAR(MAX) column. The column results in an extra "?" at the front of the data in the column. I do not want that character in my data. The column data starts like : ``` ?<?xml version="1.0" encoding="utf-8"?><Registration xmlns:xsi="http:...
First, all XML in SQL Server is in Unicode (UCS-2, to be precise), and data access libraries probably know that. So storing their output in `varchar` column isn't the best idea - you might run into various issues with implicit conversion, and such. Try switching the column data type to `nvarchar` and look whether it he...
Varchar can only hold characters in the ascii code page. My guess would be you have some unicode character at the beginning of that string. Switch to nvarchar, you won't get rid of that initial character but you won't lose it either
XML text in Varchar(max) mysterious question mark
[ "", "sql", ".net", "sql-server", "xml", "vb.net", "" ]
I have a requirement, in which I need to output group the result based on rowCount. Here is the result set which I get from my SQL: ``` ID Date Count 1 10/01/2013 50 1 10/02/2013 25 1 10/03/2013 100 1 10/04/2013 200 1 10/05/2013 175 1 10/06/2013 45 2 10/01/2...
For such a task, you could use a [pipelined table function](http://www.oracle-base.com/articles/misc/pipelined-table-functions.php) to generate the required result. There is a little "plumbing" as it requires to define some additional types, but the function by itself is a simple loop over a cursor, accumulating value...
You can do this in Oracle 12c with a [`MATCH_RECOGNIZE`](http://docs.oracle.com/database/121/DWHSG/pattern.htm#DWHSG8956) pattern matching technique. Setup (added a few rows, including some with a count above 200, for testing): ``` create table stuff (id int, stamp date, num int); insert into stuff values (1, to_date...
Group the Result based on RowCount in Oracle
[ "", "sql", "oracle", "plsql", "" ]
I would like to determine the ownership of a folder. Therefore every folder has a constant naming convention, which is stored in the table OWNER(ident\_string). Using the ident\_string I want to determine the owner\_id and write it (update) into table FOLDER(owner\_id). I have following tables in Postgresql: ``` crea...
Try this: ``` update folder as f set owner_id = o.owner_id from owner as o where o.ident_string = left(f.folder_name,length(o.ident_string)); ``` -g
Maybe something similar to the following? `update folder set folder.owner_id = owner.owner_id from folder join owner on folder_name like owner.ident_string + '%'` (like is the method for regexs in sql)
SQL - Dynamic Lookup with Regex
[ "", "sql", "postgresql", "plpgsql", "" ]
If I have three tables such as `dog`, `cat`, and `animal`, where a property of `animal` is `name`, how can I join `dog` and `cat` and return both names? The structure would look something like this: ``` ---Dog--- AnimalID char(9) ChasesID char(9) ---Cat--- AnimalID char(9) --Animal-- AnimalID char(9) Name cha...
I'm not sure what are you trying to do this way, but if you only want to get names of the animals you can try with something like this: ``` SELECT Animal.Name AS Name FROM (SELECT AnimalID FROM Cat UNION SELECT AnimalID FROM Dog) AS AnimalsUnion LEFT JOIN Animal ON Animal.AnimalID = AnimalsUnion.Ani...
You need two joins for this: ``` select ad.name as dogname, ac.name as chases from dog d join animal ad on d.animalid = ad.animalid join animal ac on d.chasesid = ac.animalid; ``` From what I can tell, the `cat` table is superfluous. It doesn't have a separate id, so you don't need it. You can get...
SQL Joins and Renaming columns
[ "", "mysql", "sql", "join", "inner-join", "renaming", "" ]
I'm building a query to display the names of athletes based on the fact that they have participated in more than one event. For this I have to use 2 tables as shown: ``` CREATE TABLE ATHLETE( ATHLETEID CHAR(4), ATHLETEFIRSTNAME VARCHAR2(20), ATHLETELASTNAME VARCHAR2(20), ATHLETEDOB DATE, REPCOUNTRY VARCHAR2(12), COAC...
ShoutCase SQL aside, you'll need to join back to athlete and then group by all non-aggregated columns, like so (note I've switched your aliasing to align to the table names): ``` SELECT a.ATHLETEID, a.ATHLETEFIRSTNAME, a.ATHLETELASTNAME, COUNT(r.EVENTID) as NumEvents FROM RESULTS r INNER JOIN ATHLETE a ...
simply Use join with count (**Subquery Not Needed**) ``` SELECT A.ATHLETEID,ATH.ATHLETEFIRSTNAME FROM RESULTS A JOIN ATHLETE ATH ON ATH.ATHLETEID =A.ATHLETEID GROUP BY A.ATHLETEID,ATH.ATHLETEFIRSTNAME HAVING COUNT(*) > 1; ```
SQL query that displays the names of Athletes who have participated in more than one event
[ "", "mysql", "sql", "sql-server", "" ]
I have two tables. I want to select 1 record from first table if condition is true in second table (active = 0) table Lead: ``` ------------- | id | name | ------------- | 1 | abc1 | | 2 | abc2 | | 3 | abc3 | | 4 | abc4 | | 5 | abc5 | ------------- ``` table LeadsDetails: ``...
This should run faster than not exists because the subquery won't run for every row; in this case I'm counting the number of situations where the active field value on table leadsdetails is not 0, for the given ID, and showing only rows where that count is 0 (ie. for the given id the active field is ALWAYS 0) ``` sele...
As you need to get the records only when active column doesn't have 1 use `NOT EXISTS` SQL FIDDLE DEMO : <http://www.sqlfiddle.com/#!2/00970/1> ``` SELECT * FROM Lead L WHERE NOT EXISTS ( SELECT 1 FROM LeasdDetails LD where L.id = LD.lead_id AND LD.active =1 ) ```
Select 1 record from first table if condition is true in second table (all refeance rows active = 0)
[ "", "mysql", "sql", "join", "phpmyadmin", "inner-join", "" ]
I have this query: ``` SELECT `shift`.`uid`, `shift`.`activity`, `users`.`fname`, `users`.`lname` FROM `shift`, `users` WHERE `shift`.`uid` = `users`.`id` ``` It works fine just like that, but I need to add a new column from another table and order by it. `times` : ``` | uid | User | time | ++...
You could join on an aggregate query: ``` SELECT `shift`.`uid`, `shift`.`activity`, `users`.`fname`, `users`.`lname` , t.max_time FROM `shift` JOIN `users` ON `shift`.`uid` = `users`.`id` JOIN (SELECT `uid`, MAX(`time`) AS max_time FROM `times` ...
``` SELECT s.uid, s.activity, u.fname, u.lname, MAX(t.time) as maxtime FROM shift s, INNER JOIN users u ON u.id = s.uid INNER JOIN times t ON t.uid = u.id GROUP BY s.uid, s.activity, u.fname, u.lname ORDER BY maxtime ```
Joining Max Row where Col
[ "", "mysql", "sql", "aggregate-functions", "" ]
I have following data set returned by query is following, i am displaying some rows down below, but actual data returned is over 500k rows. ``` Date | amount 01-01-2010 | 200 01-02-2010 | 50 01-03-2010 | 400 01-04-2010 | 50 01-05-2010 | 0 01-06-2010 | 0 01-07-2010 | 100 ``` I would like query to...
You can use oracle analytic functions ``` SELECT DATE, AMOUNT, (SUM (AMOUNT) OVER ()) - (SUM (AMOUNT) OVER (ORDER BY DATE)) AS REMAINING FROM TABLE ```
You can also use the [Windowing Clause](http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#SQLRF06174) to avoid the `SUM(AMOUNT) - (...)`: ``` SELECT dt, AMOUNT, nvl(sum(amount) over (order by dt desc rows between unbounded preceding and 1 preceding) , 0) as REMAINING FROM yourtable or...
How to write oracle sql query for remaining totals
[ "", "sql", "oracle", "oracle11g", "" ]
I am trying to query from two databases - located on the same server. The first database query is a bit complex with a JOIN and UNION clauses, but joining to the other database is pretty straight forward. I keep getting an error on the last line of code - `SITE_ID_NUMBER`. I have never attempted this - any clues as to...
`Msg 8156, Level 16, State 1, Line 32 The column 'RECORD_DATE_TIME' was specified multiple times for 'P'.` RECORD\_DATE\_TIME is nowhere in the query you gave. Anyway, the error is clear. I'll show you a simple example which reproduces your error. Use this example to fix your code. ``` CREATE TABLE [dbo].[t1]( [id...
At the outermost level you have 2 table aliases accessible: * P : Which is the result set from the sub query with the Union * S : Which is an alias for the table [ADI\_USER.MAINTAINED].dbo.SiteDataAdiRbk The very first item in your select list is *P.[6] + SUBSTRING(**A**.SHIP\_TO,6,3) AS 'STORE'* You are referencing...
Joining multiple Database on same server SQL Server
[ "", "sql", "sql-server", "join", "" ]
I would like to apply total $10.00 discount for each customers.The discount should be applied to multiple transactions until all $10.00 used. Example: ``` CustomerID Transaction Amount Discount TransactionID 1 $8.00 $8.00 1 1 $6.00 $2.00 ...
The query below keeps track of the running sum and calculates the discount depending on whether the running sum is greater than or less than the discount amount. ``` select customerid, transaction_amount, transactionid, (case when 10 > (sum_amount - transaction_amount) then (case when transaction_amount >...
You can do this with recursive common table expressions, although it isn't particularly pretty. SQL Server stuggles to optimize these types of query. See [Sum of minutes between multiple date ranges](https://stackoverflow.com/questions/13464281/sum-of-minutes-between-multiple-date-ranges) for some discussion. If you w...
SQL Deduct value from multiple rows
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Hi how can I get the percentage of each record over the total? Lets imagine I have one table with the following ``` ID code Points 1 101 2 2 201 3 3 233 4 4 123 1 ``` The percentage for `ID 1` is `20%` for `2` is `30%` and so one how do I get it?
try like this ``` select id,code,points,(points * 100)/(select sum(points) from tabel1) from table1 ```
There's a couple approaches to getting that result. You essentially need the "total" points from the whole table (or whatever subset), and get that repeated on each row. Getting the percentage is a simple matter of arithmetic, the expression you use for that depends on the datatypes, and how you want that formatted. ...
SQL percentage of the total
[ "", "sql", "percentage", "" ]
I'm stuck. I've looked for an answer, but can't seem to find subtracting time in the same table from two different rows of the same table that fits. I'm having a difficult time with the following query. In the table below, I want to differentiate the TimeOut from one row to the TimeIn of the next row. Consider in the f...
I have solved this for similar problems and it need not be that the rows even be sorted: ``` select t1.EmpID, t1.TimeIn, t1.TimeOut, datediff(minute, max(t2.TimeOut), t1.TimeIn) as minutes from timesheet t1 left join timesheet t2 on t1.EmpID = t2.EmpID and t2.TimeOut < t1.TimeIn group by t1.EmpID, t1.T...
try something like that: ``` select *, DATEDIFF(minute, ( select max(b.TimeOut) from TIMESHEET as b where a.EmpID=b.EmpID and b.ROW<a.ROW ), a.TimeIn ) as diff from TIMESHEET as a ```
Find the time difference between two consecutive rows in the same table in sql
[ "", "sql", "sql-server", "sql-server-2008", "ssms", "" ]
I wrote a query in mysql using group\_concat like ``` SELECT c1,group_concat(c2) FROM table1 where sno in(1,4,8,10) group by c1; ``` and gives my expected result. Now the same query I want to write using hibernate criteria.
Simple answer is **No** **Why?** Hibernate support only common function/syntax used in multiple database. There ain't any `group_concat` function in Microsoft SQL Server and may be in other database as well. **Solution:** You have to execute it as Simple SQL Query.
You have two options (depending on your hibernate version). **Override the dialect class** *any hibernate version* You will need to subclass your dialect to add `group_concat()` 1. Introduce the dialect override class Create the following class somewhere in your app (e.g. util package) ``` package com.myapp.util; ...
How to use group_concat in hibernate criteria?
[ "", "sql", "hibernate", "" ]
I'm using JavaDB and working with two tables in the same database. I'm trying to update the PrevSales column in the "SalesResp" table with the values that are in the "SellDate" column of the "Vehicles" table when the Vehicle table's SellDate is before a the specified date. I'm matching the data between the two tables ...
Use the following code and see, replace your date instead of sysdate. ``` UPDATE SALESRESP SET SALESRESP.PrevSale = (SELECT VEHICLES.SELLDATE FROM VEHICLES WHERE SALESRESP.VIN = VEHICLES.VIN AND VEHICLES.SELLDATE <'2013-09-24'); ```
OK, let's try being more explicit: `UPDATE SALESRESP SET SALESRESP.PrevSale = VEHICLES.SELLDATE FROM VEHICLES JOIN SALESREP ON (SALESRESP.VIN = VEHICLES.VIN) WHERE (((VEHICLES.SELLDATE)<'2013-09-24'))` See if that will work.
UPDATE with INNER JOIN
[ "", "sql", "sql-update", "inner-join", "javadb", "" ]
I have a joomla website and I want to make a query that it could run with a cronjob every day. It would look for any articles 30 days old and delete the articles this specific day. I can make a simple query like this: ``` SELECT * FROM `ibps6_content` WHERE created > '2013-10-16' AND created < '2013-10-16' ``` ...
You need mysql [DATE\_FORMAT(date,format)](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format) function. Please try to set your query as: ``` DELETE FROM `ibps6_content` WHERE created > DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-%d'); ``` Hope this helps
If created is a date datatype in the table ``` DELETE FROM ibps6_content WHERE created = CURRENT_DATE -INTERVAL 30 DAY ``` If it's datetime use DATE(created)
MySQL query to select a certain day in the past?
[ "", "mysql", "sql", "joomla", "" ]
Is there any way to insert data into table from a variable? Variable contents example: ``` 123;1;500;some text here; 145;0;250;and some more text; 146;1;0;; 146;0;3;this field in previous line is empty; ``` * Column dividers: `;` * Line dividers: `\r\n`
If the ;-seperated contents were in a file you could use [BULK INSERT](http://msdn.microsoft.com/en-us/library/ms188365.aspx). A StackOverflow question about this with solution you can find [here](https://stackoverflow.com/questions/15242757/import-csv-file-into-sql-server). So dumping the contents of your variable to ...
``` DECLARE @table_var TABLE( col_list VARCHAR(50) ) INSERT INTO @table_var VALUES ('123;1;500;some text here'); INSERT INTO @table_var VALUES ('145;0;250;and some more text;'); INSERT INTO @table_var VALUES ('146;1;0;;'); INSERT INTO @table_var VALUES ('146;0;3;this field'); SOL 1 : SELECT DISTINCT S.a.value('(/H/r...
Insert data into table from a CSV-formatted text variable using T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I'm have a problem with my MySQL query, currently I have the following ``` SELECT DISTINCT members.userid, messaging.toName, members.url, messaging.timestamp AS utime FROM messaging JOIN members ON members.userid = messaging.senderid WHERE ( messaging.userid = '$profileid' OR messaging.se...
One way to do that would be (using your query) to limit the output to 1 row, since you've already descending ordered your resultset by column timestamp. ``` SELECT DISTINCT members.userid, messaging.toName, members.url, messaging.timestamp AS utime FROM messaging JOIN members ON members.userid = me...
just add `LIMIT 1` at the end of your query
Retrieve MAX timestamp from query
[ "", "mysql", "sql", "" ]
I want to select `Cars` from database with where clause looking for best DRY approach for my issue. for example I have this two parameters ``` params[:car_model_id] (int) params[:transmission_id] (int) params[:from_date] params[:to_date] ``` but I dont know which one will be null ``` if params[:car_model_id].nil? &...
You can do: ``` car_params = params.slice(:car_model_id, :transmission_id).reject{|k, v| v.nil? } ``` and then: ``` Car.where(car_params) ``` **Explanation:** Since, you're checking if the particular key i.e.: `:car_model_id` and `transmission_id` exists in `params`. The above code would be something like this when...
> what is best approach to avoid such bad code and check if parameter is > nil inline(in where) Good Question ! I will make implementation with two extra boolean variables (`transmission_id_is_valid` and `car_model_id_is_valid`) ``` transmission_id_is_valid = params[:car_model_id].nil? && !params[:transmission_id].n...
Rails ActiveRecord where clause
[ "", "sql", "ruby-on-rails", "ruby", "activerecord", "ruby-on-rails-4", "" ]
I was working in Access to make a query of a few tables, and realized that a column of a table does not meet a specific requirement. I have a field that consists of thousands of records, and it contains "years" in the following format (an example) : `1915-1918`. What I want to accomplish is to make that value individ...
When your field value consists of 4 digits followed by a dash followed by 4 more digits, this function returns a comma-separated list of years. In any other cases (Null, a single year such as "1915" instead of a year range, or anything else), the function returns the starting value. ``` Public Function YearList(ByVal...
You can use the `Split` function to return an array from the "years" field that contains the upper and lower year. Then loop from the lower year to the upper year and build the concatenated string. For example: ``` Public Function SplitYears(Years As String) As String Dim v As Variant Dim i As Long Dim s A...
How do I split up a year range into individual years in a given field?
[ "", "sql", "ms-access", "vba", "ms-access-2013", "" ]
Using the [w3schools db](http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_groupby), I have to create these queries. I am stuck on a couple questions and thought I'd ask.. Q2: Show top 5 employees, excluding the top employee (show employees ranked 2-5) in terms of total sales done by those employees. In t...
Since the WebSQL database used for w3schools doesn't seem to support year() I think you could use this instead: ``` SELECT e.LastName, e.FirstName, SUM(od.Quantity*p.Price) AS OrderTotal FROM [Employees] AS e JOIN [Orders] AS o ON o.EmployeeID=e.EmployeeID JOIN [OrderDetails] AS od ON od.OrderID=o.OrderID JOIN [Produ...
You can use the YEAR() function. Check out this list of useful [datetime](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html) functions. Try this new query: ``` SELECT e.LastName, e.FirstName, SUM(od.Quantity*p.Price) AS OrderTotal FROM [Employees] AS e JOIN [Orders] AS o ON o.EmployeeID=e.EmployeeI...
SQL Grouping by Year
[ "", "sql", "" ]
I have read many threads on this subject now and tried a few things but it has not worked as I hoped. I need some clarification and apologize if this is considered a duplicate thread. A client of mine hosts a Postgres database where one table holds a little more then 12 million records. They have tasked me with findin...
Need to use `GROUP BY` and `HAVING` to get duplicate records instead of `DISTINCT` subquery will find all duplicate records ``` SELECT * FROM my_table mt JOIN ( SELECT num_1, num_2, num_3, num_4, num_5, my_date FROM my_table...
Another way using analytic functions ``` select * from ( select * , count(*) over (partition by num1,num2,num3,num4,my_date) cnt from mytable ) t1 where cnt > 1 ```
Find duplicate records in large table on multiple columns the right way
[ "", "sql", "postgresql", "postgresql-8.4", "" ]
I have two tables, `follow` and `followed`. I want to get all the rows in the `follow` table such that `follow.screen != followed.following_screen_name`. **follow table** ``` ID screen_name ----------------- 1 eddie 2 jason 3 omar 4 jonathan 5 jack ``` **followed table** ``` ID my_scr...
you can get this by doing a `LEFT JOIN` ``` SELECT F.screen_name FROM follow F LEFT JOIN followed FD on F.screen_name = FD.my_screen_name OR F.screen_name = FD.following_screen_name WHERE FD.my_screen_name IS NULL and FD.following_screen_name IS NULL ``` Another way is to use `NOT EXISTS`, get all rows that exists in...
There are plenty of ways to solve this, but common to all is that you need to compare the follow.screen\_name to both followed.my\_screen\_name and followed.following\_screen\_\_name. One way is to use NOT IN with a UNION: ``` select screen_name from follow where screen_name not in ( select following_screen_name ...
MySQL table comparison between two tables
[ "", "mysql", "sql", "" ]
I only found slightly different examples I couldn't adapt to my needs due to my very limited sql skills. I have a table with 3 revelant columns: ``` ItemID Date Result 1 1.2.2014 A 5 6.4.2014 B 9 7.4.2014 A 1 8.4.2014 A 1 9.4.2014 A 1 10.4.2014 A ``` I want to find the ...
Not sure if this is the *best* way of of achieving it, but it works. I created the following table to put your example data into: ``` CREATE TABLE DATE_RESULT( ITEM_ID INT, DATE_COL DATE, RESULT_COL VARCHAR2(255 CHAR) ); ``` Then ran this query: ``` SELECT ITEM_ID FROM( SELECT ITEM_ID, TO_CHAR(DATE_C...
``` SQL> WITH DATA AS( 2 SELECT 1 ITEM_ID, TO_DATE('1.2.2014','DD.MM.YYYY') DT, 'A' RSLT FROM DUAL UNION ALL 3 SELECT 5, TO_DATE('6.4.2014','DD.MM.YYYY') , 'B' RSLT FROM DUAL UNION ALL 4 SELECT 9, TO_DATE('7.4.2014','DD.MM.YYYY') , 'A' RSLT FROM DUAL UNION ALL 5 SELECT 1, TO_DATE('8.4.20...
Sql query to find items that had n consecutive failed attempts
[ "", "sql", "oracle", "find-occurrences", "" ]