Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want to use `IFNULL()` in such a way that I can select the record containing NULL or, if a value is present, then select the record matchinga particular value. My query is: ``` SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave FROM `CompanyLeave` CL WHERE(IFNULL(CL.EmploymentType,0)=3); ``` column `Employmen...
I am interpreting the question as a prioritization. If a record with `3` exists, choose that. Otherwise, choose the one that is `NULL`, if it exists. If so, this might do what you want: ``` SELECT (@v:=2) AS Row, CL.LeaveTypeId, CL.NumberOfLeave FROM `CompanyLeave` CL WHERE CL.EmployementType = 3 or CL.EmployementTyp...
The expression `IFNULL(CL.EmploymentType, 3)` basically means: if `CL.EmploymentType IS NULL` then use `3` instead. The original value of `CL.EmploymentType` is used if it is not `NULL`. If I understand correctly your question, you need to select the rows having `NULL` or `3` in the column `CL.EmploymentType`. The q...
How can i use IFNULL in Where clause
[ "", "mysql", "sql", "ifnull", "" ]
I have a table of doctor names and states. ``` f_name | l_name | state MICHAEL | CRANE | HAL | CRANE | MD THOMAS | ROMINA | DE ``` And so on. What I want is to get all doctors that are NOT in MD. However, if I write this expression I'm missing those with NULL values for state. ``` SELECT * FROM doctors WHE...
Yes, there is an alternative - you would use the `NVL()` function (or `COALESCE()` if you want to stick to the ANSI standard): ``` SELECT * FROM doctors WHERE NVL(state, '@@') NOT IN ('MD') ``` However you don't really need to use `NOT IN` here - it's only necessary when you have multiple values, e.g.: ``` SELECT *...
As noted already, you don't know that Michael Crane's state isn't Maryland. It's NULL, which can be read as representing "don't know". It might be Maryland, or it might not be. `NOT IN ('MD')` only finds those values *known* not to be `'MD'`. If you have a filter `WHERE x`, you can use `MINUS` to find exactly those re...
Missing records if add "NOT IN"
[ "", "sql", "oracle", "" ]
Suppose I had a table with the following format: ``` | dbo.ROUTES | ---------------------------------------- | ID | ROUTE | LOWER_LIMIT | UPPER_LIMIT | ---------------------------------------- | 0 | A | 0 | 10 | | 1 | B | 11 | 500 | | 2 | C...
As you can not use lead/lag functions, i have used alternate way to achieve this. Edit boundary conditions in output columns (missing\_val, overlapping) as per your need by adding/subtracting 1 Input: ``` ID LOWER_LIMIT UPPER_LIMIT 0 0 10 1 11 500 2 600 1000 3 980 1100 ``` Output: ``` ID LOWER_LIMIT U...
This should show rows that have gaps on either side of it: ``` SELECT * FROM ROUTES WHERE NOT Exists(SELECT ID FROM ROUTES as sub WHERE sub.Lower_Limit = ROUTES.Upper_Limit + 1) OR NOT Exists(SELECT ID FROM ROUTES as sub1 WHERE sub1.Upper_Limit = ROUTES.Lower_Limit - 1) ```
Finding gaps or overlaps in ranges
[ "", "sql", "sql-server", "" ]
I have a report with Reporting Services, in my local pc it works. But if I try to run it on Internet Explorer, I have this error message: ``` Errore durante l'elaborazione del report. (rsProcessingAborted) Query execution failed for dataset 'chartArea_monthly'. (rsErrorExecutingCommand) Per ulteriori informazioni su q...
You need to check if the online report server has access to that function this error generates when database is unable to populate the result set. Check the database which is getting hit by online report and see that function exists there and the user under which the `SSRS` tool is running has access to that function
This is very commonly observed problem that people runs into. I had this problem many a times when I used to work on SSRS reports. When you run report on your local machine then it uses the Database which is installed on your machine (of course you select the database while configuring report). But when you deploy thi...
Reporting services error if I try to run report online
[ "", "sql", "reporting-services", "" ]
I am attempting to do the following 1. Link two tables via a join on the same database 2. Take a column that exists in both FK\_APPLICATIONID(with a slight difference, where one = +1 of the other I.e. Column 1 =1375 and column 2 = 1376 3. In one of the tables exist a reference number (QREF1234) and the other con...
I think you are after something like this. You are trying to "normalize" un-normalized columns and search for all those values in another table. You need to union the results together into a temp table, then search for the values. ``` Use Database 1 Create Table #tmp(PhoneNums varchar(50)) INSERT INTO #tmp SELECT D...
A variable can only hold a single value. Instead of using the `in` operator, you could accompish this same thing with a join... ``` Use Database1 SELECT distinct T3.* FROM Table1 JOIN TABLE2 D on D.FK_ApplicationID= D.FK_ApplicationID JOIN Database2.dbo.Table3 T3 on T3.PhoneNum = D.PhoneNum...
SQL How to make multiple values use the same Declare Variable?
[ "", "sql", "sql-server", "declare", "" ]
I have a unique circumstance here. I have a concatenated field I call address and as part of this address I have the phone number of that address on the last line. currently the phone number is formatted like: ``` 8885551212 ``` I want it to format like: ``` (888) 555-1212 ``` Below is my INSERT into my temp table ...
You can use the SUBSTRING function: change ``` + p.phone ``` to ``` + '(' + SUBSTRING(p.phone,1,3) + ') ' + SUBSTRING(p.phone,4,3) + '-' + SUBSTRING(p.phone,7,4) ```
Use **[`Stuff`](http://msdn.microsoft.com/en-IN/library/ms188043.aspx)** string function to insert the required special into the string. Try this. ``` SELECT '('+ Stuff(Stuff('8885551212', 4, 0, ') '), 9, 0, '-') ```
Format Phone Number inside of concat field SQL
[ "", "sql", "sql-server-2008-r2", "" ]
I have a table called `team_members` with this structure and contents: ``` +---------+---------+ | team_id | user_id | +---------+---------+ | 1 | 18 | +---------+---------+ | 1 | 7 | +---------+---------+ | 3 | 18 | +---------+---------+ ``` What i am trying to do is to find a team ...
Use `Case statement` in `Having` clause and `Count` only the required user\_id's. Try this. ``` select teamid from yourtable group by teamid having count(case when userid=7 then 1 end)=1 and count(case when userid=18 then 1 end)=1 and count(1)=2 ```
Something to think about (and assuming a PK on team\_id,user\_id)... ``` SELECT x.*, COUNT(*),SUM(user_id IN(7,18)) FROM my_table x GROUP BY team_id; ```
SQL find team that only contains specified 2 users
[ "", "mysql", "sql", "" ]
I have two tables name `cars` and `booking`. What i want to find is the available cars for booking which in simple is selecting the car details from `cars` whose id is not in booking table on specific date and time. the booking table has the columns `pick_date(date),drop_date(date),pick_time(time),drop_time(time),car_...
Try this: ``` SELECT c.car_id FROM cars c LEFT JOIN ( SELECT car_id FROM bookings WHERE '2015-01-15 11:00:00' BETWEEN CAST(CONCAT(Pick_Date, ' ', Pick_Time) AS DATETIME) AND CAST(CONCAT(Drop_Date, ' ', Drop_Time) AS DATETIME) ) AS A ON c.car_id = A.car_id WHERE A.car_id IS NULL `...
You can do this with a `left join` or `not in` or `not exists`. The `left join` looks like ``` select c.* from cars c left join bookings b on c.car_id = b.car_id and @pickdt <= addtime(drop_date, drop_time) and @dropdt >= addtime(pick_date, pick_time) where b.car_id is null; ``` The variable...
MySQL select id which is not in specific date and time
[ "", "mysql", "sql", "date", "datetime", "select", "" ]
I have three tables `#temp`, `tbProducts` and `tbVendor` ``` tbVendor(States, AgentId, Products) tbProduct(ProductId, ProductName) #temp(ProductName) ``` **SAMPLE DATA** ``` tbVendor -------------------------------- ----------- -------------------- States AgentId Products ------------...
Write as: ``` ;WITH cte AS ( SELECT AgentId, CAST('<r>' + REPLACE(States, ',', '</r><r>') + '</r>' AS XML) AS States, CAST('<r>' + REPLACE(Products, ',', '</r><r>') + '</r>' AS XML) AS Products FROM @tbVendor ) ,FinalList AS ( SELECT AgentId, RTRIM(LTRIM (sTable.sColumn.value(...
TRY THIS: ``` DECLARE @state varchar(25) = 'New York', @agentId int = 1 SELECT STUFF((SELECT ', ' + Products FROM tbVendor tv WHERE tv.AgentId = @agentId AND tv.States Like '%' +@state + '%' FOR XML PATH('')), 1, 2, '') AS products INTO #tmp ;with tmp(product, products) as ( select LTRIM(...
How to join more than two tables on the basis of two parameters?
[ "", "sql", "sql-server", "sql-server-2008", "join", "" ]
I have a SQL table which look like : ``` Date temp dewpoint humidity 10/12/15 5.1 2.4 57 11/12/15 4.1 5.8 69 12/12/15 20.6 3.6 56 13/12/15 13.0 2.5 21 14/12/15 5.6 13.6 15 15/12/15 5.1 2.4 56 ``` I would like to know i...
In MySQL, the easiest way is probably to use the `substring_index()`/`group_concat()` trick: ``` select substring_index(group_concat(date order by temp asc), ',', 1) as minTempDate, substring_index(group_concat(date order by temp desc), ',', 1) as maxTempDate, substring_index(group_concat(date order by d...
It is exactly what you want to receive, but it's looks terrible. ``` SELECT date, 'temp-min' dataName, temp dataValue FROM numbers WHERE temp = (SELECT min(temp) FROM numbers) UNION SELECT date, 'temp-max' dataName, temp dataValue FROM numbers WHERE temp = (SELECT max(temp) FROM numbers) UNION SELECT date, 'humidity-m...
Request multi column min/max with date in SQL
[ "", "mysql", "sql", "database", "minmax", "" ]
This query returns a set of dates from tblValue whose FieldValue is type nvarchar(4000) ``` SELECT t1.FieldValue FROM (SELECT FieldValue FROM tblValue WHERE FieldID = 4) t1 WHERE DateAdd(day, -90, t1.FieldValue) <= GETDATE() ``` This works, but instead of hard-coding the FieldID of 4, I'd like to get all FieldValues ...
This happens because of the particular execution plan that the optimizer produces. Depending on how it chooses to combine the comparison and filtering operations of the various clauses, it can do either one or the other first. In this case, it's trying to perform the date conversion and comparison before applying the ...
I guess you want this? ``` SELECT * FROM tblValue v JOIN tblField f ON v.FieldID = f.FieldID WHERE f.FieldType = 'Expiration' AND DateAdd(day, -90, v.FieldValue) <= GETDATE() ```
Main T-SQL WHERE function seems to be wrongly applied to a subquery
[ "", "sql", "t-sql", "" ]
I am trying to select records that appear more than once and are part of a specific department plus other departments. So far the query that I have is this: ``` SELECT employeeCode, employeeName FROM Employees WHERE Department <> 'Technology' AND employeeCode IN (SELECT employeeCode FROM Emp...
If you want employees that could be in the technology department *and* another department: ``` select e.employeeCode, e.employeeName from employees e group by e.employeeCode, e.employeeName having sum(case when e.department = 'Technology' then 1 else 0 end) > 0 and count(*) > 1; ``` This assumes no duplicates ...
Try this: ``` SELECT E.employeeCode, E.employeeName FROM Employees E INNER JOIN (SELECT DISTINCT E1.employeeCode, E1.employeeName FROM Employees E WHERE E.Department = 'Technology' ) AS A ON E.employeeCode = A.employeeCode AND E.employeeName = A.employeeName GROUP BY E.employeeCode,...
Select records that appear more than once
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to get my EntryDate column in this format 'YYYY\_m' for example '2013\_04'. This code has been unsuccessful ``` DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate) ``` Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ',' after the M. What code would work inst...
How about `date_format()`? ``` select date_format(EntryDate, '%&Y_%m') ``` This is the MySQL way. Your code looks like an attempt to do this in SQL Server. EDIT: The following should work in SQL Server: ``` select DATENAME(year, EntryDate) + '_' + RIGHT('00' + DATEPART(month, EntryDate), 2) ``` Personally, I migh...
``` select DATENAME (YYYY, EntryDate) + '_' + right('0' + convert(varchar(2),datepart (MM, EntryDate)), 2) ``` You have to convert the result of `DATEPART()` to a character string in order for the `+` to perform an append. FYI - in the future "unsuccessful" doesn't mean anything. Next time post the actu...
DATENAME and DATEPART in SQL
[ "", "sql", "sql-server", "datepart", "" ]
Below is my `MDX` query to generate aging report. I want to use a named `SET` inside a calculated measure. I am getting this error: > Query (3, 1) The function expects a tuple set expression for the 1 > argument. A string or numeric expression was used. Can this be resolved? ``` WITH SET [Cnt] AS {'FILTER( ...
I think it is just the first section of your script. Why are you using a string? Try deleting the apostrophies and just add in `.MEMBERS` for clarity: ``` WITH SET [Cnt] AS {FILTER( [Cheque Detail Fact Keys].[Cheque Master ID].[Cheque Master ID].MEMBERS ,[Measures].[Paid Amt]<>0 ) ...
The [Cnt] set looks expensive...is that based on a fact table? If so, what's the granularity? Perhaps you can add a calculated field in the DSV for the base table of the measure group (e.g. IIF(Paid Amt <> 0, 1, 0) ) and then create a SUM-based measure on the field. Then your query becomes... ``` WITH SET [x] AS ...
Aging Report MDX query issue?
[ "", "sql", "sql-server", "reporting-services", "ssas", "mdx", "" ]
I am wanting to insert a record into a database table (website) by using a procedure with parameters. The SQL code has been tested in mysql workbench and works properly to insert new data. However, with delphi i am getting an 'SQL Syntax error near [insert whole line of code here]'. I was wondering if one of you could ...
You have quite a few problems in your code. A) Don't exaggerate with function parameters, if you have a lot of variables, assemble them in a record or class depending on your needs. B) Your SQL code is vulnerable for SQL injection. You probably never heard of SQL injection, please Google it or read this [really good ...
Please replace `'+CID+';)');` with `'+CID+');');` in the end of your query line. The **`;`** was in wrong place.
Insert into SQL syntax error delphi
[ "", "mysql", "sql", "database", "delphi", "" ]
Is there a way to update only parts of a database record? I have a table that lists a bunch of different items followed by their cost, but I would like to remove the cost from the item. For example: Current table looks like this ``` ---Item------------- Apple- 1.35 Orange - 1.24 Grape - 2.00 ETC.. -----------...
I think I would go for Mid: ``` SELECT t.ExistingField, Trim(Mid([existingfield],1,InStr([existingfield],"-")-1)) AS NewData FROM Table t ``` So: ``` UPDATE Table SET Table.UpdatedField = Trim(Mid([existingfield],1,InStr([existingfield],"-")-1)) WHERE Table.ExistingField Like "*-*" ```
If the part you want to remove always begins with a hyphen, and there won't be any hyphens as part of the item name then this code should do what you want: ``` update YourTable set item = left(item, instr(item,"-")-1) ``` Before you run the update you might want to try it as a select: ``` select left(item, instr(ite...
Updating parts of a record in Access
[ "", "sql", "database", "ms-access-2010", "" ]
I have two tables: ``` create table books ( id int ,bookname text ); ``` --- ``` create table users( id int ,name text ,book_1 int ,book_2 int ,book_3 int ); ``` Now, 'book\_1', 'book\_2', 'book\_3' contains id of table 'books'. I am trying to create a single que...
You can use *sub-selects* to get *bookname* of each *username* in a single row (**if *id* in table *books* is unique**) ``` select name username ,(select bookname from books where id=book_1) book1_name ,(select bookname from books where id=book_2) book2_name ,(select bookname from books where id=book...
``` SELECT user.name ,books.name FROM user LEFT JOIN books ON books.id=user.book_1 OR books.id=user.book_2 OR books.id=user.book_3; ``` join on all `id's`
How to get data by using different column values refrencing same table
[ "", "sql", "postgresql", "" ]
I have done much searching on StackOverflow and have been unable to adapt other SQL Join "Top 1" answers to my own case, so I am hoping someone else can point out what I am missing. ### TableA ``` UniqueTableID TaskID ReferenceID 1 Task_1 Group_1 2 Task_2 Group_2 3 ...
If you want the first GroupName alphabetically for each task, you can use `min`: ``` SELECT A.TaskID, min(B.GroupName) as GroupName FROM [TableA] A JOIN [TableB] B ON B.GroupID = A.ReferenceID GROUP BY A.TaskID ```
I think the best way to do this is with row number. While you can do a group by on the main table (like Ron Smith's answer), you have to group by all columns which are not GroupName. Joining to a table using row number you don't. Here is an example of how to do it for your data: ``` SELECT A.TaskID, s.GroupName FROM...
SQL Join Tables from Top 1
[ "", "sql", "sql-server", "join", "" ]
I have two tables, one called facebook\_posts and the other called facebook\_post\_metrics. facebook\_posts looks like ``` NAME id a 1 b 1 c 4 d 4 ``` facebook\_post\_metrics looks like ``` number FBID Date_Execute...
With a problem like this, I recommend breaking it down into pieces and putting it back together. Finding the date of the most recent facebook\_posts\_metrics row is easy, like this: ``` SELECT fbid, MAX(date_executed) AS latestDate FROM facebook_post_metrics GROUP BY fbid; ``` So, to get the entire row, you want to ...
you need a `subquery` that calculated the `max` using `group by` and then join again with same tables to get all the details As per the latest edit, the update\_at column is no longer there in posts as there are two entries, you can get only one by doing a group by if you want all the entries then remove the aggregat...
Using MAX within INNER JOIN - SQL
[ "", "sql", "" ]
I have these two tables: ``` actions action_data ``` `action_data` belongs to actions and has the columns: `action_id`, `name`, `value` The contents may look like this: `Actions`: ``` id | ----- 178| 179| ``` `action_data`: ``` action_id | name | value ------------------------------------- 178 | pl...
Since you don't know the number of meta data to search for, I wouldn't recommend unknown/unlimited number of `joins`. Instead use `group concatenation`: ``` select * from actions join ( select action_id, group_concat(name,'=',value order by name separator ',') as csv // MySQL // string_agg(name || '='...
If you **don't** want a DBMS-specific syntax, you could use an auto-join. I would do it like this: ``` SELECT DISTINCT action_id FROM action_data a1 JOIN action_data a2 USING(action_id) WHERE a1.name = 'planet' AND a1.value = 'earth' AND a2.name = 'object' AND a2.value = 'spaceship_a'; ``` This works for **...
SQL - Select by condition based on multiple rows
[ "", "sql", "" ]
I'm currently working on a small project that uses USA county data. I have no problems ordering the data in a `Seq.orderBy`, but as there is a `sortBy` in the query expression I would expect the results to be sorted. This is not the case. ``` type SysData = SqlDataConnection<"Data Source=ROME\SQLEXPRESS;Initial Catalo...
The order of the keywords is important. If you read the description carefully, then SortBy will sort the elements that have been selected so far. Distinct will remove duplicates so far (but there is nothing in there about keeping order), etc. Each of these keywords acts on the one before it, but keep in mind that it ma...
Came across this today. Here's an alternate solution using a subquery: ``` let counties = let db = SysData.GetDataContext() query { for result in (query { for c in db.CountyMatrix do select { State = c.State; SSA = c.Countyssa } distinct }) do sortBy ...
Why does orderBy in F# not result in an ORDER BY in SQL?
[ "", "sql", "linq", "f#", "sql-order-by", "" ]
Using MySQL, I'm looking to write a single insert query that will take a single string and insert it multiple times, each time removing the last character. So the query would be something like ``` INSERT INTO table (str) VALUES ("string") ..... ``` and would result in the following values being inserted ``` string ...
The simplest way is to write a stored procedure and then just call it to do the inserts. ``` DELIMITER # CREATE PROCEDURE 'insert_string_rows' (IN 'str' text) BEGIN DECLARE len int unsigned; SET len = CHAR_LENGTH(str); WHILE len > 0 DO INSERT INTO table VALUES (str); SET str = SUBSTR(str, 1, len - 1); ...
If you have a table of numbers, you could do: ``` insert into table(str) select left(@str, n.n) from (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9 ) n where length(@st...
Insert string into mysql multiple times, removing last character each time, with one query
[ "", "mysql", "sql", "insert", "" ]
I am doing an advanced search functionality for a recipes website where the users can query; * Recipes **with** the presence of certain ingredients (up to 3 ingredients) * Recipes **without** the presence of certain ingredients (up to 3 ingredients) * Under specific cooking time The above-mentioned points can be comb...
You can use ``` SELECT r.Recipe_name, r.Recipe_ID FROM Recipes AS r INNER JOIN Recipe_Ingredients AS ri ON r.Recipe_ID = ri.Recipe_ID INNER JOIN Ingredients AS i ON ri.Ingredient_ID = i.Ingredient_ID WHERE i.Ingredient_Name IN ( 'penne', 'onion', 'butter' ) ...
Use NOT EXIST clause with a subquery: ``` NOT EXISTS( SELECT 1 FROM Ingredients i WHERE ri.Ingredient_ID = i.Ingredient_ID AND i.Ingredient_Name IN ('butter') ) ``` A full query: ``` SELECT count(*) as rowcount, r.Recipe_name FROM Recipes AS r INNER JOIN Recipe_Ingredients AS ri ON r.Recipe_ID = ri.Recipe_I...
SQL query recipes with these ingredient(s) but NOT these ingredient(s)
[ "", "mysql", "sql", "relational-division", "" ]
``` StudentID | SubCode | SubName ------------------------------- 1 1 Math 1 2 Science 1 3 English 2 1 Math 2 2 Science 3 2 Science 4 1 Math 4 3 English ``` This is my subject...
try these two queries, both are similar but shows the data in different ways: ``` SELECT StudentID, CASE WHEN Sum(CASE WHEN SubCode IN( 1, 2, 3 ) THEN 1 ELSE 0 END) = 3 THEN 'All' WHEN Sum(CASE WHEN SubCode IN( 1, 3 ...
You need to filter the group using `Having Clause`. I don't know why you need all the results in a single query. Try this. ``` SELECT StudentID, 'Only Maths' as Subjects FROM #testt GROUP BY StudentID HAVING Count(CASE WHEN SubCode = '1' THEN 1 END) = 1 AND Count(*) = 1 UNION ALL SELECT StudentID, ...
Find Students who have registered in multiple subject by subject name
[ "", "mysql", "sql", "select", "join", "" ]
I currently have two separate queries in SQL Server that count the number of times a table contains a unique ID in a week. I would like to display these using one query, not two. This data is held in two separate views, hence my writing two queries. These are `ActivityPointer` and `Asp_dealercallreport`. Query #1: `...
Maybe you can simply use INNER JOIN operator? Like this: ``` SELECT ap.OwnerIDName, COUNT(Distinct ap.ActivityID) AS CalendarEvents, COUNT(Distinct a_dcr.Asp_dealercallreportId) AS DealerVisits FROM ActivityPointer ap INNER JOIN Asp_dealercallreport a_dcr ON ap.OwnerIDName=a_dcr.OwnerIDName WH...
Use conditional aggregation: ``` SELECT OwnerIDName, COUNT(Distinct case when ScheduledStart >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) / 7 * 7, 0) AND ScheduledStart <= DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()), 0) then ActivityID end) AS CalendarEven...
SQL Count between two tables
[ "", "sql", "sql-server", "join", "count", "" ]
I am new to databases and I needed help with something. I have one table in my database which contains information about all the events. So for example, there are rows, each one describing a different event. Now, I also need to keep track of users attending events. So how would I design this? I was thinking that if th...
A better way of doing this would be to have something like the following: ``` Create table events( id integer, <OTHER EVENT DETAILS HERE (i.e. start time, location, duration etc> primary key (event_id) ); Create table users( id integer, <OTHER USER DETAILS HERE (i.e. name, email, phone etc)> primar...
> ... would it be a good idea to just add a column in the main events table, with names of people attending delimited by a comma or a semicolon or something? Hmm you may want to read up on [joins](http://www.tizag.com/mysqlTutorial/mysqljoins.php) first this will help with relations between tables. You would create an...
Having SQL Automatically Create a Table
[ "", "mysql", "sql", "database", "database-design", "" ]
I would like to count students by their current age for all students registered since 2010. i.e. 16 - 2 17 - 5 19 - 5 In the current "student" table, I have the student's DOB and registration\_date. I am using Management Studio. So far I have: ``` SELECT COUNT (*) FROM db.student WHERE DATEDIFF(year, DOB, CU...
try this. ``` select DATEDIFF(Year,DOB,CURRENT_TIMESTAMP) age,Count(ID) users from dbo.student where DatePart(year,registration_date)>=2010 GROUP BY DATEDIFF(Year,DOB,CURRENT_TIMESTAMP) ```
You might need a GROUP BY. Probably something like this? ``` SELECT DATEDIFF(year, DOB, CURRENT_TIMESTAMP), COUNT (*) FROM db.student WHERE registration_date >= '2010-01-01' GROUP BY DATEDIFF(year, DOB, CURRENT_TIMESTAMP) ```
DATEDIFF and COUNT
[ "", "sql", "datediff", "" ]
I'm trying to figure out from the past two days how to perform an count function on the following query: For each module, list the module title and the number of activities scheduled for the module. My two tables that are needed for this are : TblActivity - ID, Name, Type, ModuleID, Day, Time, RoomID. TblModule - ID, T...
Join the tables on the `ID` column, group by the `Title` column, and then select the `Title` column and the number of matched activities (`COUNT(TblActivity.ID)`). ``` SELECT Title, COUNT(TblActivity.ID) FROM TblModule JOIN TblActivity ON TblActivity.ID=TblModule.ID GROUP BY Title ``` Hope this helps!
``` SELECT M.Title, COUNT (A.ModuleID) AS NUMBER_OF_ACTIVITIES FROM TblModule M LEFT JOIN TblActivity A ON M.ID = A.ModuleID GROUP BY Title ```
SQL Count using two people
[ "", "sql", "sql-server", "count", "" ]
My Table: ``` ID|Col1|Col2| 1 |abc |1 | 2 |abc |0 | 3 |xyz |0 | 4 |xyz |0 | 5 |jkl |1 | ``` **Q1.** I want to return a list of records grouped by Col1 where all of the records in that group have Col2 = 0. I don't mind if it returns all of them (record 3 and 4) or just unique one(e.g. just 'xyz'). **Q2.** I...
``` select col1 from your_table group by col1 having sum(case when col2 = 1 then 1 else 0 end) = 0 ``` and ``` select col1 from your_table group by col1 having sum(case when col2 = 1 then 1 else 0 end) > 0 ```
And another ways, using EXISTS and sub-queries: ``` select * from your_table where not exists (select * from your_table t2 where col1 = t2.col1 and col2 <> 0) ``` And ``` select * from your_table where exists (select * from your_table t2 where col1 = t2.col1 and col2 = 1) ```
Select from table group by id where all records in that group have a flag = false
[ "", "sql", "sql-server", "" ]
Oracle database allows the following queries: ``` select col1 from table order by col2; select count(col1) from table group by col2; ``` It appears that the columns in the order / group by clause don't need to be in the select clause. However, [tutorialspoint: SQL - ORDER BY Clause](http://www.tutorialspoint.com/sql...
The tutorial is just plain wrong. An `order by` can include any columns in the queried objects whether they are in the select list or not. A `group by` goes the other way. Any non-aggregated columns in the select list must be included in the `group by`.
I don't think it's the case that columns mentioned in the `GROUP BY` must be in the `SELECT`. However, if there is a `GROUP BY` then columns in the `SELECT`, that aren't aggregated, must be in the `GROUP BY`! Anyway, please see [SQL Fiddle demo here](http://sqlfiddle.com/#!2/2469f6/1) for MySQL. So you can see that it ...
Are the columns used in the order / group by clause(s) mandatory in the select clause?
[ "", "mysql", "sql", "oracle", "" ]
I have field endTime has DateTime data type and status (int). I want to update my status field from 1 to 0 if hour and minute from endTime is equal to hour and minute of current time. the day is absolutely same. so the day is doesn't matter. How do I do ?
You can use `datepart()`: ``` select (case when datepart(hour, EndTime) = datepart(hour, getdate()) and datepart(minute, EndTime) = datepart(minute, getdate()) then 1 else 0 end) as status ``` You can also put this into an update, if that is what you really want. EDIT: The upda...
``` UPDATE <table> SET status = 0 WHERE datepart(hour, endTime) = datepart(hour,getdate()) AND datepart(minute, endTime) = datepart(minute,getdate()); ``` This is How I do on my SQL-Server 2008.
How to compare Hour and Minute only from DateTime data type
[ "", "sql", "sql-server-2008", "datetime-format", "" ]
I am calling a stored procedure called `Searchprocedure`. I get an error at line where I am calling it. I have not made any changes to the parameters passed in the procedure and it was called just fine with same calling statement earlier. ``` Exec SearchProcedure @firstname = 'Simran', @middlename = 'kaur', @lastname ...
``` --Setting variable in Dynamic SQL DECLARE @sql NVARCHAR(MAX), @Name NVARCHAR(100) SET @Name = '#B2E0EB1A' SET @sql = ' DECLARE @MyVar NVARCHAR(100) SELECT TOP 1 @MyVar = name FROM sys.objects WHERE name LIKE ''%a''--Escaping single quote with double quote PRINT @MyVar ' EXEC(@sql) SET @sql = ' DECLARE ...
I can't find any error and can run the exec without anerror message. Edit: After I created the (now avialbe) output procedure and uncomment its call, I'm getting the error too... Still investigating Edit2: In the Output procedure you have to use `set @sql = 'declare ' + '@Temp'+ @colVar + ' int'` (@ before Temp) and...
Incorrect syntax near '=' while trying to call a stored procedure in T-sql
[ "", "sql", "sql-server", "t-sql", "ssms", "" ]
I'm new to SQL queries and I'm trying to join two tables I need to get all data of the followers of userID = 2 here's the error i get : `Syntax error: Encountered "INNER" at line 1, column 39.` and here's the SQL query I ran : ``` SELECT * FROM FOLLOWER WHERE userID = "2" INNER JOIN USERS ON FOLLOWER.Follower_use...
position of where clause was incorrect structure of SELECT query is ``` SELECT fields FROM tables WHERE conditions ORDER BY fields ``` so you query should be ``` SELECT * FROM FOLLOWER INNER JOIN USERS ON FOLLOWER.Follower_userID = USERS.userID WHERE userID="2" ORDER BY USERS.follower_count ASC ```
Try this statement: ``` SELECT * FROM FOLLOWER Fl WHERE userID="2" INNER JOIN USERS Us ON Us.userID = Fl.Follower_userID ORDER BY USERS.follower_count ASC ``` Let me know if it's works
SQL INNER JOIN exception
[ "", "sql", "exception", "syntax-error", "derby", "" ]
Essentially, I want to partition my table by person and add a row number (EVENT) for each record within a n month window of the most recent date in that window. For the example below n = 3. Sample Data: ``` PERSON DATE (yyyy-mm-dd) A 2014-05-02 A 2014-01-09 A 2014-01-08 A 2014-01-07 A ...
Another example with a ROW\_NUMBER(): ``` with a AS(SELECT *, ROW_NUMBER() OVER (PARTITION BY PERSON ORDER BY DT DESC) AS rn FROM #Records), c AS( SELECT PERSON AS PERSON, DT, DT AS eventStart, 1 AS EVENT, rn FROM a WHERE rn=1 UNION ALL SELECT c.PERSON, r.DT, CASE WHEN r.DT < DATEADD(MONTH, -3, c.eventSt...
This might work for you - an Oracle solution will be very similar: ``` WITH x1 AS ( SELECT person, MAX(dt) AS max_dt FROM person_event GROUP BY person ) SELECT p1.person, p1.dt, FLOOR(DATEDIFF(month, p1.dt, x1.max_dt)/3) + 1 FROM person_event p1 INNER JOIN x1 ON p1.person = x1.person ``` [Please see SQ...
Row number over a partition and sliding window
[ "", "sql", "sql-server", "" ]
I want a query to count duplicate values in a column,is there any query for this or i was thinking as ``` total records=SELECT COUNT(column_name) FROM table_name; distinct records=SELECT COUNT(DISTINCT column_name) FROM table_name; duplicate count=total records-distinct records; ```
Looking at your sql, it can be simplified as below : ``` SELECT Count(Column) - Count(DISTINCT Column) FROM yourTable ```
``` select column_name, count(*) from table_name group by column_name having count(*) > 1 ```
count duplicate values in a column sql
[ "", "sql", "oracle", "" ]
I have resources each represented by a guid and they have attribute name-value pairs. I would like to query for resources which have the given attribute name value pairs. So, suppose the table looks like: ``` GUID ATTR_SUBTYPE ATTR_VAL 63707829116544a38c5a508fcde031a4 ...
Assuming you don't have *duplicate* attributes per GUID you can achieve the desired result without a `JOIN`: ``` SELECT "GUID" FROM T WHERE ( "ATTR_SUBTYPE" = 'location' AND "ATTR_VAL" = 'US' ) OR ( "ATTR_SUBTYPE" = 'owner' AND "ATTR_VAL" = 'himanshu' ) GROUP BY "GUID" HAVING COUNT(*) = 2 -- <-- keep only GUID have...
Insert your targets into a temp table then join to it. ``` select t.guid from table as t join temp on t.attr_subtype = temp.attr_subtype and t.attr_value = temp.attr_value ```
sql query for multi valued attributes
[ "", "sql", "oracle", "" ]
I have a table that has records for multiple session events. Each row is an event in a session, and a session can have multiples of the same event. Those are basically game sessions and each event is round start or round end. My data looks something like ``` Session_id | Event_type | Event_Time 1 | round_start | 12:01...
A subquery, as opposed to a nested query, should only return one value. Your requirement is an example where you want data from pairs of rows. The subquery is only used to connect the pair, not supply data. `Fiddle` ``` select e1.SessionID, e1.EventType, e1.EventTime, e2.EventType, e2.EventTime, TimeStampDiff( minute...
I would suggest that you approach this with a correlated subquery: ``` select RS.session_id, RS.Event_Time as StartTime, (select smin(event_time) from amp_event_mamlaka em where em.session_id = RS.session_id and em.Event_Type = 'Round End' and em.event_time > RS.Eve...
Referencing a column in a sub-query's where clause
[ "", "mysql", "sql", "left-join", "where-clause", "" ]
I am new in the SQL. Where I work I got a new type of job about automatize a Full SQL backup. Almost got it, it is working from the SQL Server Management Studio as a query. (by the way I have to do it on the Server) So I am trying to execute this query like this way "- sqlcmd -E -S EUTAX-WS\REMEK -i D:\Programs\FastGla...
``` sqlcmd -U "username" -P "password" -i D:\Programs\FastGlacier\backupAllDB.sql ```
**Please try giving permission to script containing folder i.e d:\backup** In Windows Explorer, right-click the file or folder you want to work with. From the pop-up menu, select Properties, and then in the Properties dialog box click the Security tab. In the Name list box, select the user, contact, computer, or gro...
Can not execute a Full SQL backup
[ "", "sql", "batch-file", "backup", "database-backups", "" ]
Does anyone know why sql server chooses to query the table 'building' twice? Is there any explanation? Can it be done with only one table seek? This is the code sample: ``` DECLARE @id1stBuild INT = 1 ,@number1stBuild INT = 2 ,@idLastBuild INT = 5 ,@numberLastBuild INT = 1; DECLARE @nr TABLE (nr INT); IN...
You can try the following, which gives only one seek and a slight performance improvement. As @Martin\_Smith says what you have coded is the equivalent of a `Union` ``` SELECT * FROM building b WHERE b.id IN (@id1stBuild , @idLastBuild) AND ( (b.id = @id1stBuild AND b.number = @number1stBuild...
It's not scanning twice. It is seeking twice. Your query is semantically the same as the below. ``` SELECT * FROM building b WHERE b.id = @id1stBuild AND b.number = @number1stBuild UNION SELECT * FROM building b WHERE b.id = @idLastBuild AND b.number = @numberLastBuild ``` And the execution plan ...
SQL Server - why is scanning done twice for the same table?
[ "", "sql", "sql-server", "sql-execution-plan", "" ]
I have to find the timediff in minutes for a order lifetime. i.e time from order was received(Activity ID 1) to keyed(2) to printed(3) to delivered(4) for each order for eg I am completely lost at which approach should i take?? use case or if then statement ?? something like for each to loop thru each record? what sh...
You can do this easily by `pivoting` the data.It can be done in two ways. 1.Use `Conditional Aggregate` to pivot the data. After `pivoting` you can find `datediff` between different stages. Try this. ``` SELECT orderid,Received,Keyed,Printed,Delivered, Datediff(minute, Received, Keyed) TurnTime1, Dat...
At first I make a list of all orders (`CTE_Orders`). For each order I get four dates, one for each ActivityID using `OUTER APPLY`. I assume that some activities could be missing (not completed yet), so `OUTER APPLY` would return `NULL` there. When I calculate durations I assume that if activity is not in the database,...
how to loop thru a table to find data set?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
``` ALTER PROCEDURE [dbo].[bulk_import_csv_from_dir] -- Add the parameters for the stored procedure here @ext varchar(10), @likefilename varchar(max), @tablename varchar(max), @tabeltemplate varchar(max), @directory varchar(8000) AS BEGIN --DECLARE @da...
At the beginning you are Deallocating the **cur\_files** `Cursor` you are not declaring the **cur\_files** `Cursor` after that,replace ``` execute ('IF OBJECT_ID(''cur_files'') IS NOT NULL DEALLOCATE cur_files'); SELECT subdirectory as fname FROM @directory_table WHERE isfile = 1 AND RIGHT(subdirectory,4) = @ext AND ...
You never declare your cursor. I suspect you want something like ``` --fill temp table with listed files INSERT into @directory_table (subdirectory,depth,isfile) EXECUTE master.sys.xp_dirtree @directory,1,1; DECLARE cur_files CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR SELECT subdirectory AS fname FROM ...
SQL Cursor (A cursor with the name 'cur_files' does not exist.)
[ "", "sql", "sql-server", "" ]
I have a table named `trades` for holding currency trading data with the following schema: ``` id - uuid timestamp - timestamp without time zone price - numeric ``` I would like to be able to query in a way that I can build a candle chart. For this I need the *first price*, the *last price*, the *max price...
I think this is the query you want: ``` SELECT ts_round( timestamp, 300 ) AS interval_timestamp, max(firstprice) as firstprice, max(lastprice) as lastprice, max(price) AS maxprice, min(price) AS minprice FROM (SELECT t.*, first_value(price) over (partition by ts_round(timestamp, 300) ...
This uses a *single* window for all window functions and no subquery. Should be faster than the currently accepted answer. ``` SELECT DISTINCT ON (1) ts_round(timestamp, 300) AS interval_timestamp , min(price) OVER w AS min_price , max(price) OVER w AS max_price , first_value(pric...
Selecting first and last row within a time interval
[ "", "sql", "postgresql", "aggregate-functions", "greatest-n-per-group", "window-functions", "" ]
**Table**: table\_name ``` create table table_name ( given_dates timestamp, set_name varchar ); ``` **Insertion of records**: ``` insert into table_name values('2001-01-01'),('2001-01-05'),('2001-01-10'), ('2001-01-15'),('2001-01-20'),('2001-01-25'), ('2001-02-01'),('2001-02-05'),('...
Clean setup: ``` CREATE TABLE tbl ( given_date date , set_name varchar ); ``` Use a singular term as column name for a *single* value. The data type is obviously [`date` and not a `timestamp`](https://www.postgresql.org/docs/current/datatype-datetime.html). To transform your text parameters into a useful table: ...
**String\_to\_array** ``` declare p_dates varchar[] := string_to_array('2001-01-01,2001-01-05, 2001-01-10,2001-01-15*2001-01-01,2001-01-05,2001-01-10,2001-01-15','*'); declare p_sets varchar[] := string_to_array('s1,s2',','); declare p_length integer=0; declare p_str varchar[]; declare i integer; select array_length...
Split given string and prepare case statement
[ "", "sql", "postgresql", "postgresql-9.3", "set-returning-functions", "unnest", "" ]
I have two tables, **PERSON** and **FRIENDS**. FRIENDS has the fields NAME and SURNAME. A person has N friends. **I want to retrieve all the PERSONs that have atleast two FRIENDs, one with name ="mark", and the other with name="rocco" and surname ="siffredi".** Example: if I have a person that has 5 friends, one of ...
I had to guess your column names and make up a table: Use EXISTS: ``` CREATE table FRIENDS(person_id INT, friend_id INT) go SELECT * FROM person WHERE EXISTS (SELECT * FROM friends f JOIN person per ON f.friend_id = per.id WHERE per.name ='mark' AND person.id = f.person_id) AND...
Your schema design isn't very good for what you are trying to do... I would have a Person table as you have, which would also contain a unique identifier called PersonId. I would then have a Friends table which took two fields - Person1Id and Person2Id. This gives you a couple of important advantages - first of all yo...
SQL Query JOIN or IN operator?
[ "", "sql", "sql-server", "logical-operators", "" ]
I am having a heck of a time getting this query to work. Basically I need to do a CASE statement to get the person's NickName if they have one, otherwise use their FirstName. Then in the WHERE statement, do a LIKE statement on that above CASE statement. I've been able to get it to work if I **only** do the FirstName/N...
You can use a Common Table Expression or Subquery to create the FName as a kind of virtual column of a new resultset. You can that use the resultset as a kind of virtual table and filter on that in the where clause. ``` SELECT * FROM ( SELECT LastName , Company , Status , CASE WHEN NickName I...
Use `CROSS APPLY` to create an alias ``` SELECT LastName , Company , Status , FName FROM database CROSS APPLY ( SELECT CASE WHEN NickName = '' THEN FirstName WHEN NickName IS NULL THEN FirstName ELSE NickName END AS FName ) AS ...
SQL - using SELECT Alias in WHERE
[ "", "sql", "sql-server", "alias", "" ]
How can I remove any white space from substring of string? For example I have this number '+370 650 12345'. I need all numbers to have this format `country_code rest_of_the_number` or in that example: `+370 65012345`. How could you achieve that with PostgreSQL? I could use `trim()` function, but then it would remove ...
Assuming the column is named `phone_number`: ``` left(phone_number, strpos(phone_number, ' ')) ||regexp_replace(substr(phone_number, strpos(phone_number, ' ') + 1), ' ', '', 'g') ``` It first takes everything up to the first space and then concatenates it with the result of replacing all spaces from the rest of th...
If you are able to assume that a country code will always be present, you could try using a regular expression to capture the parts of interest. Assuming that your phone numbers are stored in a column named `content` in a table named `numbers`, you could try something like the following: ``` SELECT parts[1] || ' ' || ...
Postgresql - remove any whitespace from sub string
[ "", "sql", "regex", "postgresql", "" ]
Having the following structure: ``` Table Auction (Id_Auction (Pk), DateTime_Auction) Table Auction_Item (Id_Auction_Item (Pk), Id_Auction (Fk), Id_Winning_Bid (Fk), Item_Description) Table Bid (Id_Bid (Pk), Id_Auction_Item (Fk), Id_Bidder (Fk), Lowest_Value, Highest_Value) Table Bidder (Id_Bidder (Pk), Name) ``` Ind...
Ok, I think that after a lot of research (and learn a bit more about how joins really work behind the scenes) I figured it out. By now, I'll post it only as a theory, til some SQL Master say that it's wrong and show me the light, or I really be sure I'm right. The point is that MSSQL is choosing what is fastest to th...
A covering, correctly-sorted index is rarely not used by SQL Server. Only pathological cases come to mind such as extremely low page fullness or huge unneeded additional columns. You index is simply not covering. Look at the columns that are output. You'll discover one that you have not indexed. That column is `Id_Au...
MSSQL Server Not Using NonClustered Composite Key Index (PK + FK) on InnerJoin
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm working on a Point of Sale System developing in Java, and for backend I am using a SQL Server database. As I'm new to database and confuse that I'm doing write in database. For ever sale I'm making invoice, the table design is like that 1. `Invoice` table has columns `InvoiceID`, `InvoiceDate`, `CutomerID`, `Meth...
Its recommended to make a separate table for the pending debits, and the the pending debits will be dynamic which means when ever the invoice collected completely the delete its record. And your invoices table will be as its.
Some sample data might help us understand the problem a bit better. if I try to read between the lines, you are asking whether it is better to have one record for each invoice which you update when the customer makes a payment, or whether you have a separate record for each payment associated with an invoice which you...
Credit debit and balance of a customer in a SQL Server database
[ "", "sql", "sql-server", "accounting", "" ]
I'm trying to alter the course\_id column in the table 'course' but I keep getting this error: ``` CREATE TABLE course ( course_id varchar(10) PRIMARY KEY, title varchar(30), dep_name varchar(10), credits numeric(2,2) CHECK (credits>0) ); ALTER TABLE takes ALTER COLUMN course_id varchar(10) REFERENCES course(...
Altering a column's type and adding a foreign key on it are two different statements: ``` ALTER TABLE takes ALTER COLUMN course_id TYPE VARCHAR(10); ALTER TABLE takes ADD CONSTRAINT takes_course_fk FOREIGN KEY (course_id) REFERENCES course(course_id); ```
Your syntax is worng. It must be: ``` ALTER TABLE takes ALTER COLUMN course_id TYPE varchar(10) ; ```
PostgreSQL ERROR: syntax error at or near "varchar"
[ "", "sql", "postgresql", "foreign-keys", "ddl", "" ]
I have a view in one of my databases that is retrieving the previous and current case officers(think person) from a few tables and views. The issue is these records are only linked by the end date(saoh.Date\_TO) being the same as another case officers start date (saoh.Date\_FROM). To create a join between these record...
Its hard not having anything to test against so just treat this as a starting point ``` SELECT sp.SNAPSHOT_PERIOD_START_DATETIME, sp.SNAPSHOT_PERIOD_END_DATETIME, aes.APPLICATION_RID, aes.ESTATE_RID, aes.TRUSTEE_NUMBER, aes.TRUSTEE_TYPE, aes.TEAM_CODE, saoh.POSITION, saoh.DATE_FROM,...
In this case you may be able to turn the "inner join in the outer join" into multiple left joins, though your where clause will then need to handle the situations that the inner join in the subquery was dealing with, for example: ``` ... query same up to the left join ... /*This should be inner joining to ...
An Inner join in an Outer Join leading to peformance shortfalls, what is a different approach?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "dimensional-modeling", "" ]
I have a visitor system. when the visitor checks in, it sets a date\_in. and when the visitor checks out it sets a date\_out. but if a visitor forget to check out. it says he has no date\_out so I try to figure out how to set the date\_out if the visitor didn't check out. an example: Check in: 2015-01-19 12:00:00 vi...
My suggestion - rather than editing the data (and subsequently not being able to identify genuine check-outs at 23:59), just update the query: ``` SELECT * /* TODO - actual columns */ FROM visits WHERE date_out IS NULL AND date_in >= DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0) ``` Where the expression `D...
You could create a job that runs 23:59:59 every day that fills the date\_out with data.
SQL set date_out automatically if today ends
[ "", "sql", "sql-server-2008", "" ]
Is there any way to simply add not null unique column to existing table. Something like default = 1++ ? Or simply add unique column? I tried to add column and then put unique contrain but MS SQL says that: The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name (...) The dupli...
1. Add not null column with some default. 2. Update column to be a sequential integers (see row\_number() function) 3. Add UNIQUE constraint or UNIQUE index over new column You can add IDENTITY column to a table (but from question it is not clear if you need it or not).
[IDENTITY](http://blog.sqlauthority.com/2013/05/30/sql-server-add-identity-column-to-table-based-on-order-of-another-column/) is all you need: ``` ALTER TABLE TestTable ADD ID INT IDENTITY(1, 1) ```
How to add not null unique column to existing table
[ "", "sql", "sql-server", "unique", "" ]
``` IF OBJECT_ID('Tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable CREATE TABLE #TempTable ( [ID] INT NOT NULL , [Value] VARCHAR(50) NULL , [Date] DATE NULL , [Time] TIME(7) NULL , [Duration] INT NULL , [srcFile] VARCHAR(50) NULL, ) INSERT #TempTable ( ...
This should give you exactly what you're after: ``` With CTE as (Select T.ID ID1, T.srcFile + ' - ' + c.srcFile over1, '1' as isDup from #TempTable T INNER JOIN #TempTable c on T.Value = c.Value and c.ID <> T.ID and (Cast(C.Date as datetime) + Cast(C.Time as datetime)) = (Cast(T.Date as datetime) + Cast(T.Time as date...
code follows your requirement (hopefully). i tested it with adding more overlaps and duplicities, it work not only with 2 duplicates, overlaping files (e.g. srcFile='sF3'), but with these observations: 1. DupFile - list always ordered by filename 2. overlapfile - if there is only one file, there is no pair "sF1 - sF1"...
T/SQL - Time related calculations
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am getting an error message when I'm trying to give an Alias to a Sub-Query and then reference it in a Where clause: *Unknown column 'point\_status' in 'where clause'* ``` SELECT goals.id, goals.status, ifnull((SELECT point_status FROM pts WHERE point_id = ?), goals.status) as point_status FROM goals WHERE goals...
You cannot use the `Alias name` in same select statement `where` clause. You can make it as a `Sub-select` and use the `alias name` in the `outer query` to filter the records. ``` select * from (SELECT goals.id, goals.status, ifnull((SELECT point_status FROM pts WHERE point_id = ?), goals.status) as point_status FROM...
> It is not allowable to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. That means that you can't use aliases in a `where` clause. Try replacing `where` with `having`.
Why am I getting Unknown column in 'where clause' using a sub-query alias with MySQL?
[ "", "mysql", "sql", "" ]
Say I have two tables: Product ``` product_id (other fields are of no concern) ``` Sku ``` product_id sku_id color_id color_name (other fields such as size but unimportant) 001 11 5 green 001 12 1 black 001 13 3 red 002 21 1 ...
This might work for you: ``` SELECT p.product_id , LISTAGG(s.color_id, ',') WITHIN GROUP ( ORDER BY s.color_id ) AS colorIds , LISTAGG(s.color_name, ',') WITHIN GROUP ( ORDER BY s.color_id ) AS colorNames FROM product p LEFT JOIN ( SELECT DISTINCT product_id, color_id, color_name FROM sku ) s ON p.prod...
This will achieve the `distinct` effect (you cannot use `distinct` with `listagg`): ``` select product_id, listagg(color_id, ',') within group(order by color_id) as colorids, listagg(color_name, ',') within group(order by color_id) as colornames from (select distinct product_id, color_id, color_name fr...
Order By in subselect using concat and decode
[ "", "sql", "oracle", "select", "oracle11g", "" ]
I currently have an inelegant solution that requires iterating through thousands of rows one at a time and I would like to know if it's possible to do this with a single SQL statement. I have a database table called `history` that holds a record of all transactions on another database called `inventory`. Both database...
When you need to perform SELF-JOIN, you have to give an alias to the copy of your table being joined. Please find the query below - here both sides were aliased: ``` SELECT history_AB.pKey FROM history AS history_AB INNER JOIN history AS history_CD ON history_AB.pKey = history_CD.pKey WHER...
You have to identify the two instances of history as separate elements. Using your "ABCD" example instead of your statement: ``` SELECT * FROM history h1 INNER JOIN history h2 ON h1.pKey=h2.pKey WHERE h1.fieldName = 'A' AND h1.oldValue = 'B' AND h2.fieldName = 'C' AND h2.oldValue = 'D' ```
Is there a way to do a SELF JOIN on on the same column?
[ "", "mysql", "sql", "inner-join", "one-to-many", "foreign-key-relationship", "" ]
I have a `ActiveRecord` model `Post` that contains the fields `created_at` and `score`. I want to order the `Posts` by score in the last 50 ones created. So basically the SQL would be ``` SELECT * FROM (SELECT * FROM Posts ORDER BY created_at DESC LIMIT 50) Sorted_Posts ORDER BY score DESC ``` Unfortunately I'm not s...
Maybe something like this: `Order.where(id: Order.order(:created_at => :desc).limit(50).ids).order(:score => :desc)`
Try this: ``` Post.order('created_at DESC').limit(50).order('score DESC') ```
Greatest-n-per-group rails ActiveRecord SQL
[ "", "mysql", "sql", "ruby-on-rails", "activerecord", "greatest-n-per-group", "" ]
How can query **table1** with a list of values for **colA** and get back the the list of the values that were not found? i.e. **all\_values** = ["a","b","c","d"] Table1 already has rows with **colA** for "b","c" I want to create a query that can I send in the entire **all\_values** list and get back **new\_values** ...
Your best option is to create a temporary table (which will be visible only to the current session and dropped when that session ends), inserting all the values in `all_values`, then comparing that to the existing table. For example, ``` CREATE TEMPORARY TABLE `all_values` ( `myvalue` VARCHAR(30) ); -- insert val...
You can use a derived table: ``` SELECT * FROM ( SELECT "a" AS colA UNION ALL SELECT "b" UNION ALL SELECT "c" UNION ALL SELECT "d" ) all_values WHERE all_values.colA COLLATE utf8_general_ci NOT IN (SELECT colA FROM table1); ``` I use COLLATE to avoid a collation conflict between table1 and values from all\_va...
How to return a list of unfound values in MySQL
[ "", "mysql", "sql", "ruby", "" ]
I have the following mysql statement based on [Mysql intersection based on single field](https://stackoverflow.com/questions/27997211/mysql-intersection-based-on-single-field): ``` SELECT m1.* FROM mytable m1 INNER JOIN mytable2 m2 ON m1.history = m2.history WHERE `insert_date` >= DATE_SUB(CURDATE(), IN...
mysql will handle that for you, you can put columns from either table in the where clause. Think of the join as producing a new table with columns from both tables in it, then the where clause applies that that result set. If you have the same columns in both tables you just need to provide the name of the table or ali...
I believe you can add the condition to either the ON clause or the WHERE clause. However, per [the documentation](http://dev.mysql.com/doc/refman/5.0/en/join.html) the ON conditions (ideally) are used to describe how the tables should be joined while the WHERE conditions are for everything else. I'm still fairly new to...
How to apply where cause in mysql join query to different tables
[ "", "mysql", "sql", "" ]
My database is listing Jobs. I want a user to be able to query jobs from a particular industry but chose as many work-types from the `type` column as they want, eg: ``` SELECT * FROM `rec_jobs` WHERE `industry` LIKE '%Security%' AND (`type` LIKE '%Full-Time%' OR 'type' LIKE '%Part-Time%' OR 'type' LIKE '%Casual%'...
you should use the same quotes around the column name type: ``` SELECT * FROM `rec_jobs` WHERE `industry` LIKE '%Security%' AND ( `type` LIKE '%Full-Time%' OR `type` LIKE '%Part-Time%' OR `type` LIKE '%Casual%' OR `type` LIKE '%Contract%'); ```
If you know the exact strings you are looking for then use `IN()` ``` SELECT * FROM `rec_jobs` WHERE `industry` = 'Security' AND `type` IN ('Full-Time', 'Part-Time', 'Casual', 'Contract') ```
Querying using multiple LIKEs from same column?
[ "", "mysql", "sql", "" ]
``` Select FirstName + ' ' + LastName from Members ``` Gives error: > Implicit conversion of varchar value to varchar cannot be performed because the collation of the value is unresolved due to a collation conflict. But it works fine when I take `FirstName` and `LastName` in separate columns like ``` Select FirstNa...
Seems you have different collation within the same table - very unusual Try this: ``` SELECT FirstName COLLATE DATABASE_DEFAULT + ' ' + LastName COLLATE DATABASE_DEFAULT AS FullName FROM Members ``` If this works, I suggest you change collation to be the same for FirstName and LastName rather than correcting...
Try this ``` select CAST(FirstName AS VARCHAR) + ' ' + CAST(LastName AS VARCHAR)from Members or select CONVERT(VARCHAR(100),FirstName) + ' ' + CONVERT(VARCHAR(100),LastName )from Members ```
(Select FirstName + ' ' + LastName from Members gives error Implicit conversion of varchar value to varchar cannot be performed
[ "", "sql", "sql-server", "sql-server-2008", "correlated-subquery", "" ]
I want to generate a SQL query to get null count in a particular column like ``` SELECT COUNT (column) AS count FROM table WHERE column = null ; ``` This is returning 0, but I want how many null values are present in that column like ``` SELECT COUNT (column) AS count FROM table WHERE column = 'some value'; ``` ...
`NULL` value is special in that you cannot use `=` with it; you must use `IS NULL` instead: ``` SELECT COUNT (*) AS count FROM table where column IS null ; ``` This is because `NULL` in SQL does not evaluate as equal to anything, including other `NULL` values. Also note the use of `*` as the argument of `COUNT`.
You can use a conditional `sum()` ``` SELECT sum(case when column is null then 1 else 0 end) AS count FROM table ```
SQL query to get null count from a column
[ "", "sql", "oracle", "count", "" ]
I am trying to get records from the last 24 hours, grouped by hour with counts in SQL Server? I have sample data like: ``` ID Dat 1 2015-01-19 10:29:00.000 2 2015-01-19 11:29:00.000 3 2015-01-19 11:29:00.000 4 2015-01-19 11:29:00.000 5 2015-01-19 12:29:00.000 6 2015-01-19 12:29:00.000 7 2015-01...
Try this, it will also count the hours without data: ``` DECLARE @t table(ID int, Date datetime) INSERT @t values (1,'2015-01-19 10:29:00.000'), (2,'2015-01-19 11:29:00.000'), (3,'2015-01-19 11:29:00.000'), (4,'2015-01-19 11:29:00.000'), (5,'2015-01-19 12:29:00.000'), (6,'2015-01-19 12:29:00.000'), (7,'2015-01-19 1...
You can [round your values to the nearest hour](https://stackoverflow.com/questions/6666866/t-sql-datetime-rounded-to-nearest-minute-and-nearest-hours-with-using-functions) and then simply GROUP and COUNT: ## [SQL Fiddle Demo](http://sqlfiddle.com/#!3/baa4f/2) **MS SQL Server Schema Setup**: ``` CREATE TABLE DateTab...
Return records with counts for the last 24 hours
[ "", "sql", "sql-server", "database", "sql-server-2012", "" ]
I have two tables namely "CProduct" and "DProduct".Below are the examples: CProduct : ``` EffectiveDate CFund 2014-01-03 0.06 2014-01-03 0.12 2014-01-06 0.11 ``` DProduct : ``` EffectiveDate DFund 2014-01-03 0.06 2014-01-06 0.12 2014-01-08 0.09 ``` I want to get a result like belo...
This gets your desired results - not quite sure why the other answerers think joins and `COALESCE` are so crucial: ``` SELECT a.EffectiveDate, SUM(a.CFund) AS CFund, SUM(a.DFund) AS DFund FROM ( SELECT c.EffectiveDate, c.CFund, NULL AS DFund FROM CProduct c UNION ALL SELECT d.EffectiveDate, NULL AS CFu...
Should just be some subqueries and a full outer join. Not sure why you think a `UNION` is required (especially because that eliminates duplicate rows): ``` SELECT COALESCE(t1.EffectiveDate,t2.EffectiveDate) as EffectiveDate, t1.Total, t2.Total FROM (select EffectiveDate,SUM(CFund) from CProduct ...
Using Left join , Union and Right Join to get a desired result
[ "", "sql", "ms-access", "ms-access-2007", "" ]
Consider the following table. ``` ----------------------------------------------------- | game_id | blue_player_id | red_player_id | turn_of | ----------------------------------------------------- | 1 | 4 | 5 | "blue" | ----------------------------------------------------- | 2 | ...
You can use CASE statement if SQL. ``` SELECT CASE <variable> WHEN <value> THEN <returnvalue> WHEN <othervalue> THEN <returnthis> ELSE <returndefaultcase> END as something FROM <table> ``` You need something like this ``` SELECT CASE WHEN turn_of='blue' then blue_player_id else red_player_id end as pl...
``` select gameId, case when turn_of = 'blue' then blue_player_id else red_player_id end as PlayerID from MYTable ```
SQL selecting column depending on the value of another column
[ "", "sql", "select", "" ]
when I select table like this: `select count(*) from products` is returning 12900 result. I have a relational query that returns multiple table relation reult like this: ``` SELECT category.name, manifacturer.name, supplier.name, product.name FROM products as product, suppliers as suppl...
You can see that not matched records with FULL OUTER JOIN like this: ``` SELECT prod.id, rel.id FROM ( SELECT category.name, manifacturer.name, supplier.name, product.name FROM products as product, suppliers as supplier, manifacturers as manifacturer, categories as categor...
First, you should learn to use proper, explicit `join` syntax: ``` SELECT category.name, manifacturer.name, supplier.name, product.name FROM products as product join suppliers as supplier on product.sid = supplier.id join manifacturers as manifacturer on product.manid = manifacturer.id jo...
How to use NOT in relational SQL query
[ "", "sql", "sql-server", "" ]
For the below given data set I want to remove the row which has later timestamp. ``` **37C1Z2990E5E0 (TRXID) should be UNIQUE** in the below dataSet JKLAMMSDF123 20141112 20141117 5000.0 P 1.22 RT101018 *2014-11-12 10:10:26* 37C1Z2990E5E0 101018 JKLAMMSDF123 20141110 20141114 50...
Try this: ``` ;WITH DATA AS ( SELECT TRXID, MAX(YourTimestampColumn) AS TS FROM YourTable GROUP BY TRXID HAVING COUNT(*) > 1 ) DELETE T FROM YourTable AS T INNER JOIN DATA AS D ON T.TRXID = D.TRXID AND T.YourTimestampColumn = D.TS; ```
Select the min of the timestamp column and group by all of the other columns. ``` SELECT MIN(TIMESTAMP), C1, C2, C3... FROM YOUR_TABLE GROUP BY C1, C2, C3.. ```
Remove duplicates based on a condition
[ "", "sql", "sql-server", "database", "" ]
I have a Three columns in the SQL table, I want to show the sum of the total of two columns in the third column. How can I show that using SQL query. This is my table structure ``` Id int Unchecked Col_A int Unchecked Col_B int Unchecked Total int Checked ```
You can use comuted column for this: ``` CREATE TABLE [dbo].[Test]( [a] [INT] NULL, [b] [INT] NULL, [c] AS ([a]+[b]) ) ON [PRIMARY] GO INSERT INTO dbo.Test ( a, b ) VALUES ( 1, -- a - int 2 -- b - int ) SELECT * FROM dbo.Test Results: a b c 1 2 3 ```
There is no need to store the total in the table, you can simply calculate it as part of your SQL query as follows: ``` SELECT Id, Col_A, Col_B, Col_A + Col_B AS Total FROM tablename ```
Total Sum of two columns and show in the third Column
[ "", "sql", "" ]
I have two tables and records in it as below: ``` User --------------------- ID UserId --------------------- 1 User1 2 User2 Department_User ------------------------------ ID DEPT_ID USER_ID ------------------------------ ...
This is an example of a set-within-sets query. I like to solve these using `group by` and `having`. Here is one method: ``` select user_id from department_user where dept_id in (1, 2) group by user_id having count(distinct dept_id) = 2; ```
``` select du1.user_id from department_user du1 where exists ( select * from department_user du2 where dept_id= 2 on du1.user_id = du2.user_id); and du1.dept_id = 1 ``` or ``` select user_id from department_user where dept_id = 1 and user_id in ( select user_id from department_user where dept_id= 2); ``` or `...
Need help in SQL join
[ "", "sql", "oracle", "" ]
I'm having trouble at query which displays the Employee Number, First Name, Last Name and the number of orders of each employee. Make sure that the Number of orders column name should be “OrderCount”. Order By the OrderCount then by employee ID. Null is allowed. employee\_data containing columns: `Emp_ID`, `F_Name`, `...
Try this: ``` SELECT od.Emp_ID, ed.F_Name, ed.L_Name, COUNT(DISTINCT od.O_ID) AS OrderCount FROM order_data od LEFT JOIN employee_data ed ON ed.Emp_ID = od.Emp_ID GROUP BY od.Emp_ID ORDER BY OrderCount ```
Aggregate functions cannot be used along with other fields in a query. You can use it in a sub-query, as follows: ``` Select order_data.Emp_ID, F_Name, L_Name, (select COUNT(employee_data.Emp_ID) from employee_data) as OrderCount FROM order_data LEFT JOIN employee_data ON employee_data.Emp_ID = order_data.Emp_ID GROUP...
COUNT() and Left Join not working
[ "", "mysql", "sql", "select", "group-by", "left-join", "" ]
I'm looking to create a new TABLE in my database but ran into a naming conundrum. I initially wanted to create the table as **people** But then I got to thinking... should I name the table **people** or **persons** ``` TABLE CREATE persons(name string, age integer) or TABLE CREATE people(name string, age integer) ```
The words people and persons can both be used as the plural of person,People is by far the more common of the two words and is used in most ordinary contexts: "a group of people"; "there were only about ten people" if you are going to have particular person's detail [attributes of individuals ] as `name`, `age`... the...
This is debated and often considered a matter of opinion, however I recommend always using singular. Your table name should be 'Person'. * A table should be named the 'object' of what it contains. Plural is 'redundant', the table may always have 0, 1 or more items in it, using a singular reference standardises this ac...
SQL TABLE naming. persons vs. people
[ "", "sql", "sqlite", "" ]
I have a table with a column DateTime datatype with default value null . I am using following code to update the Datetime to proper datetime , but it is not working . My code as below ``` declare @SomeDate datetime = GETDATE() update Testing set SomeDate = @SomeDate where SomeDate <> @SomeDate ```
Try below code ``` declare @SomeDate datetime = GETDATE() update Testingset set SomeDate = @SomeDate where SomeDate is null or SomeDate <> @SomeDate ```
Try this: ``` UPDATE Testingset SET SomeDate = @SomeDate WHERE SomeDate IS NULL OR SomeDate != @SomeDate ```
Update Datetime null value to not null
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Here is a little mind-breaker: Platform is MS SQL 2008, but the problem is general. I have a table table with 3 columns: CLIENT,DATE,DESTINATION\_PREFERENCE ``` TABLE1 ------------------------------------------------------- CLIENT |DATE |DESTINATION_PREFERENCE ---------------------------------------------...
You can use CTE with adding additional column, where you simply replace 6 with 3, 9 with 2 etc. ``` DECLARE @t TABLE ( client NVARCHAR(MAX) , date DATETIME , dest INT ) INSERT INTO @t VALUES ( 'Akme', '20140101', 1 ), ( 'Akme', '20140102', 3 ), ( 'Akme', '20140102', 6 ), ...
You could just put a case statement in your order by in the rank: ``` SELECT CLIENT,DATE,DESTINATION_PREFERENCE FROM ( SELECT CLIENT,DATE,DESTINATION_PREFERENCE, RANK() OVER (PARTITION BY CLIENT, DATE ORDER BY Case DESTINATION_PREFERENCE when 3 then 6 when 9 then 2 when 128 then 312 else DESTINATION...
SQL - Complex RANK
[ "", "sql", "sql-server", "ranking", "" ]
I have this table: ``` cart_item_id (primary key) user_id (int) shop_item_id (int) quantity (int) is_checked_out (tinyint) ``` from this table i want to get the most selling item, which is the item that have the maximum checked out quantities, i developed this query, but it returned errors: ``` SELECT `shop_item_id`...
Order by the quantity and take the first record only ``` SELECT `shop_item_id`, sum(`quantity`) FROM `cart` WHERE `is_checked_out` = 1 group by `shop_item_id` order by sum(`quantity`) desc limit 1 ```
The following code will do fine for you : ``` SELECT `shop_item_id` FROM `cart` WHERE `is_checked_out` = 1 and sum(`quantity`)>=max ( select sum(`quantity`) from `cart` where `is_checked_out` = 1 ...
how to perform query to get max sum in mysql?
[ "", "mysql", "sql", "max", "having", "" ]
Supporse I have the fllowing table with words from a dictionary: ``` Word --- cat dog giraffe zebra ``` I would like to find a word, and if it doesn't exist, the closest before it in [dictionary](http://en.wikipedia.org/wiki/Lexicographical_order) order, e.g. `aardvark` would return nothing, `cat` would return `cat`,...
Assuming that you have declared the column with the correct [collation](http://www.sqlite.org/datatype3.html#collation) for dictionary order (which might be the default, or `COLLATE NOCASE`, or a user-defined collation), getting an exact match is trivial: ``` SELECT Word FROM Dictionary WHERE Word = ? ``` and getting...
this may helps you ``` select a.word,b.word from dictionary a, words b where difference (a.word,'DOG') in(3,4) ``` or you can use `soundex` function
Select closest match in dictionary order
[ "", "sql", "sqlite", "" ]
Sorry for the rubbish title. I could quite articulate my problem in a few words. I have an SQL that gives a list of ids separate by a pipe (|). I want to pass these ids into another sql as a where clause. I can use replace to convert the values from pipe separate into comma separated. As an example the list of IDs mi...
There may be two cases: good and bad. Bad case is your pipe-separated string is stored somewhere in the database and you cannot change this design to something meaningful. If so, you'll need to use like operator, something like this: ``` select t2.* from my_table2 t2, my_table t where '|' || t1.value || '|' lik...
This is a complicated expression, but you can do it with `like` and `exists`: ``` select * from my_table2 where exists (select 1 from my_table t1 where '|' || value || '|' like '%|' || id || '|%' ); ``` However, you have a fundamental problem with the data structure in `my_tab...
output of replace SQL as a where clause in another SQL
[ "", "sql", "oracle", "casting", "" ]
I want a trigger that triggers whenever the loan table is updated (i.e. a book is returned). It should take values from the rows in the loan table only where the loan is overdue and insert them into a new table. --- the 'loan' table: ``` CREATE TABLE loan ( book_code INT NOT NULL, student_num INT NOT NULL, ...
Try this, You are missing semicolon in your syntax and delimiter ``` DROP TRIGGER IF EXISTS trg_overdue_loans; DELIMITER $$ CREATE TRIGGER `trg_overdue_loans` AFTER UPDATE ON loan FOR EACH ROW BEGIN IF NEW.return_date > OLD.due_date THEN INSERT INTO overdue (student_num, out_date, due_date...
## Storing the old and new row state in JSON The best way to store the old and new row state is to use JSON columns. SO, for each table that you want to enable audit logging, you can create an audit log table, like this one: ``` CREATE TABLE book_audit_log ( book_id BIGINT NOT NULL, old_row_data JSON, ne...
How to create audit trail or logging tables with triggers in MySQL
[ "", "mysql", "sql", "t-sql", "triggers", "audit-trail", "" ]
We have a DACPAC that has a create user script. The user has a log in that needs to be set to a windows domain user When we do a build for Test/Staging/Release we need to be able to apply a different domain and user for the users log in. I thought we might be able to use SQLCMD variables but I just get a SQL71501 Erro...
We ended up solving this by using a post deployment script in the dacpac and as long as you do a check before trying to call the user to see if they already exist it all works as that is the only place you can use them bar the pre deployment script.
My advice based on bitter experience is to keep anything that is environment specific out of your SQL Server Database Project. Rather, apply anything that is environment specific (permisins etc) as a separate T-SQL script after the DACPAC has been deployed. If you are doing this with Release Management I have a soup-to...
Create user script with variable domain user login
[ "", "sql", "sql-server", "release", "release-management", "dacpac", "" ]
I have a table containing some random natural numbers, for example: ``` number ------- 2 3 1 ``` I'd like to retrieve a set from this table where each row would included as many times as the value shows, for example above It would be: ``` number ------- 2 2 3 3 3 1 ``` I was thinking about a query like this: ``` s...
And this is query for Oracle database: ``` SELECT t1.number FROM t t1 JOIN (SELECT LEVEL FROM dual CONNECT BY LEVEL<=(SELECT MAX(number) FROM t)) t2 ON t2.level<= t1.number; ```
try this way: ``` select t.id from tab t join (SELECT ROWNUM as id FROM ALL_OBJECTS WHERE ROWNUM<=(select max(id) from tab)) t2 on t2.id <= t.id; ``` I'm not sure what about performance of this query but the result is as expected. **[Sql fiddle Demo](http://sqlfiddle.com/#!4/35921/7/0)**
How to pass number of lines in "select level from dual connect by level < "?
[ "", "sql", "database", "oracle", "" ]
I have two tables: ``` product table product_id product_name 1 sample1 2 sample2 3 sample3 product_child table pc_id product_id product_size 1 1 5 2 1 6 3 1 7 4 2 5 5 2 ...
Try this query: ``` SELECT p.* FROM products p JOIN product_child pc1 ON pc1.product_id = p.product_id and pc1.product_size in (5,9) JOIN product_child pc2 ON pc2.product_id = p.product_id and pc2.product_size = 6 ```
If I understand correctly you need all products which have both sizes. So you have different products and every product appears in different sizes. And you want only these products which appear in both (5 or 9) and 6 sizes at the same time. I think you need something like this: ``` SELECT * from products where pro...
MySQL query left join issue
[ "", "mysql", "sql", "join", "relational-database", "" ]
I have a list of parameters the first are a date range @start\_dt and @end\_dt one of my fields is mode. if mode = 1, the query is run one way if mode - 2, another, etc. I've got 7 possible versions. when mode = 6, what I want to say is pull all the columns between the date range list below and where one column pmt\_r...
``` SELECT a.customer_no, SUM(a.sli_paid_amt), MAX(a.pmt_rcvd_amt) AS [Payment Amount], MAX(some_other_field), ... from LV_CHC_TOURS_RSV_DATA a left outer join LT_CHC_TOURS_RSV_LANG b on a.language = b.id left outer join LV_CHC_TOURS_RSV_CS c on a.add_text = c.source_no Where a.create_dt betw...
If I understand you correctly, first you need to sum up sli\_due\_amt for each customer, and then you want to return the individual rows, excluding customers who have a pmt\_rcvd\_amt = the summed sli\_due\_amt. So: ``` WITH Summed as (select customer_no, sum(sli_due_amt) as sli_sum from LV_CHC_TOURS_RSV_DATA... GROU...
Error grouping by the sum of one column to the general value of the other
[ "", "mysql", "sql", "join", "having", "" ]
so i had to adjust a query i used because the limit at the end of the table would cause the entire first table to be read before limiting. this resulted in a timeout from my mysql server. now i created the query like i read in another post on stack overflow and came up with this: ``` SELECT a.title , a.lat ,...
Fixed it thanks to @Ravinder his comment about missing the on clause updated sql: ``` SELECT a.alerts, a.title, a.lat, a.lon, a.alert_content_id, a.date_added, r.countRep, i.countInt, ac.img, c.marker, c.subcatvan FROM (SELECT alerts, title, lat, lon, alert_content_id, date_added, cat ...
You need to fix the subqueries. They need to use `group by` rather than be correlated: ``` SELECT a.title, a.lat, a.lon, a.a_content_id, a.date_added, r.countRep, i.countInt, content.img, c.marker, c.subcatvan FROM (SELECT title, lat, lon, alert_content_id, date_added, cat FROM `alerts` LIMIT 10 ...
Error in MySQL Query with multiple joins and limit on first table
[ "", "mysql", "sql", "left-join", "limit", "" ]
I tried to execute an `SQL` `INSERT` with `Toad for oracle`: ``` INSERT INTO GRAT_ACTIVITY (UUID, IP_ADRESS, SEND_MAIL, DATE_CREA, DATE_UPD, CREATOR, CENTER, ETAT, REQUEST) VALUES('555-vgd9-pllkd-5513', '172.12.23.130', 'N', SYSDATE, SYSDATE, '1554', 'M18', 'I', 8842); --COMMIT; ``` the `GRAT_ACTIVITY` table stru...
The statement you're executing is valid. The error seems to mean that Toad is including the trailing semicolon as part of the command, which does cause an `ORA-00911` when it's included as part of a statement - since it is a statement separator in the client, not part of the statement itself. It may be the following c...
Remove the semicolon (;), backtick (``) etc. from inside a query
How can I solve ORA-00911: invalid character error?
[ "", "sql", "oracle", "toad", "" ]
If I have a table like this: ``` ------------------------------ |id |duration |date | |1 |20 |1392479451 |<-- |2 |20 |1392479451 | |3 |10 |1392478620 |<-- |4 |30 |1392479457 |<-- |5 |30 |1392479457 | |6 |30 |1392479457 | -----------------------------...
This should do it: ``` SELECT SUM(duration) FROM ( SELECT duration FROM tbl GROUP BY date ) t; ``` The `GROUP BY` in the inner query will select only one row per distinct date. Which row will be selected is not defined, but it doesn't matter as the durations should be identical. Then we just sum the durations. *...
You can try something like this: ``` SELECT SUM(IF(`date` = ( SELECT MIN(`date`) FROM table WHERE `date` = t.`date`), `duration`, 0)) FROM `table` t ``` Or ``` SELECT SUM(t1.`duration`) FROM `table` t1 JOIN ( SELECT MIN(`id`) AS `id` FROM `table` GROUP BY `date` ) t2 ON t1.`id` = t2.`id` ```
SQL sum one value for each unique value from another column
[ "", "mysql", "sql", "" ]
I have a number 000005500 and I want it to be in format 0000055.00 or 55.00 using an Oracle select query. I used this query: ``` select to_char(to_number(000005500),'99.99') from dual ``` but its displaying `#####` How can I display it in the format I need?
As written your `to_number()` call is just doing an implicit conversion to a string and then an explicit conversion back to a number, which seems pointless, but I assume you're actually dealing with a value from a `varchar2` column. In which case you see: ``` select to_char(to_number('000005500'),'99.99') from dual T...
Firstly, `000005500` is not a number. A number doesn't start with zero. You are dealing with a string. > I want it to be in format 0000055.00 You can only expect it to be a string as an output, and not a number. Anyway, to get the output as `55.00` as NUMBER, you could do the following - ``` SQL> WITH DATA AS( 2 ...
Change number format by adding decimal to it in oracle
[ "", "sql", "oracle", "" ]
Apologies if this question has already been asked, but i'm pulling my hair out! I have two tables, abbreviated to KI and UG. KI contains a list of people and their photos, UG contains another list of people. What I want to do is match the tables up and return a query that shows me a list of names where we have a match...
This will give you one row per person, but only one image file too; ``` SELECT ki.name, ug.name, max(ki.image_file) as image_file FROM kantechimages AS ki INNER JOIN user_group as UG ON ki.name like ug.name WHERE ki.image_file is not null GROUP BY ki.name, ug.name ``` Rhys
Your question seems to suggest that you are only interested in getting the names of people who have images tagged to them in the other table. If that is the case, you can just retrieve the distinct names from the join which satisfy your filter condition, like so: ``` SELECT DISTINCT ki.name FROM kantechimages AS ki IN...
How to remove duplicate entries? SQL Server 2008
[ "", "sql", "sql-server", "database", "sql-server-2008", "duplicates", "" ]
``` CREATION_DATE REJECTED_REASON PART_NAME REJECTED_QTY 03-03-2014 Metal chips in port face PEGEOUT 1.8 CYLINDER HEAD CASTING H29 15 03-03-2014 Angular hole Shrinkage ...
The best would be to use dynamic pivot as Aramillo said. Oracle has something like that, it's **pivot xml** clause, but I have some query for you which do the job dynamically without xml operations. As you said you need only display report so after some formatting the output of below query will be appropriate for your ...
Try this: ``` SELECT * FROM your_table_name PIVOT (COUNT(REJECTED_REASON) FOR REJECTED_REASON IN('reason1', 'reason2', 'reason3' ....)) ; ```
Count values of a particular column and display it monthwise and partwise
[ "", "sql", "oracle", "plsql", "oracle11g", "" ]
I have `Crea_Date` column which is a `DateTime` Column. I want to subtract the value in the `IST` column from `crea_date` Column and return a new column with the `DateTime` Value in it. My sample data is like this: ``` States crea_date IST AB 2014-12-30 15:01:00.000 12:30:00.0000000 AK 2014-12...
If `IST` is an integer number of seconds: ``` SELECT DATEADD(s, -IST, crea_date) FROM yourTable ``` If `IST` is of the `TIME` type: ``` SELECT DATEADD(ms, DATEDIFF(ms, IST, '00:00:00'), crea_date) FROM yourTable ```
As strange as it might seem, you *can* add/subtract `datetime` values and it seems it's "normal" behavior. Internally, datetime values are stored as the offset from `1/1/1900`. If I add `22/1/2015` and `1/1/2015` I get `22/1/2130` because the second value is actually `115` years after `1900`. When you cast a `time` v...
How to subtract Time Column from DateTime Column in SQL?
[ "", "sql", "sql-server", "datetime", "time", "subtraction", "" ]
Suppose I've next data ``` id date another_info 1 2014-02-01 kjkj 1 2014-03-11 ajskj 1 2014-05-13 kgfd 2 2014-02-01 SADA 3 2014-02-01 sfdg 3 2014-06-12 fdsA ``` I want for each id extract last information: ``` id d...
The most efficient way is to use Postgres' `distinct on` operator ``` select distinct on (id) id, date, another_info from the_table order by id, date desc; ``` If you want a solution that works across databases (but is less efficient) you can use a window function: ``` select id, date, another_info from ( select i...
``` select * from bar where (id,date) in (select id,max(date) from bar group by id) ``` *Tested in PostgreSQL,MySQL*
Postgresql extract last row for each id
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I know there are several examples of recursion with CTE and so on, but how can this be accomplished just by using window functions in SQL Server 2012: ``` CREATE TABLE #temp ( ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL, Percentage INT NOT NULL ) DECLARE @Calculated MONEY = 1000 INSERT INTO #temp ( Perce...
You need a running product of the percentages instead of always comparing 2 consecutive rows, which is why LEAD and LAG won't work here. You can use a windowed sum to keep a running product of the percentages against your variable to get your desired calculation: ``` SELECT ID, Expected, EXP(SUM(LOG(CONVE...
you can use `recursive cte` to get the desired result ``` with cte as ( select id, percentage, 1000 as calculated from #temp where id =1 union all select t.id, t.percentage, t.percentage*cte.calculated/100 as calculated from #temp t join cte on t.id = cte.id+1 ) select * from cte ```
SQL Server window function for running percentage
[ "", "sql", "sql-server", "" ]
I'm logging queries which have been sent to my API like this: ``` id | timestamp ----+--------------------- 1 | 2015-01-19 18:01:47 2 | 2015-01-19 20:41:37 3 | 2015-01-20 14:15:06 4 | 2015-01-21 13:02:51 5 | 2015-01-23 05:02:12 ``` Now, I need to know how much queries have been made in the last 60 mi...
``` select sum(case when timestamp between now() - interval 1 hour and now() then 1 else 0) hourly, sum(case when timestamp between now() - interval 1 day and now() then 1 else 0) daily, sum(case when timestamp between now() - interval 1 month and now() then 1 else 0) monthly from your_table ``` edited...
``` select sum(timestamp >= now() - interval 1 hour) as hour, sum(timestamp >= now() - interval 1 day) as day, sum(timestamp >= now() - interval 1 month) as month from your_table ``` ### [SQLFiddle demo](http://sqlfiddle.com/#!2/cb328a/2)
How to get data from last hour, last day and last month with one query?
[ "", "mysql", "sql", "database", "pdo", "" ]
I'm trying to write an 'idiot proof' SQL script that can be run by non-SQL literate users. My idea is to have a couple of variables defined at the top of the script, then run particular queries based on those variable. I'm testing on mySQL, but it will eventually run on SQL-Server. In pseudo-code this is what I'm tr...
This is for MSSQL. I think that you got everything down but the syntax. I hope this helps/works. ``` DECLARE @matchthis AS VARCHAR(MAX) DECLARE @update AS VARCHAR(1) SET @matchthis = 'matchme' --@update can be Y or N. User changes this here. SET @update = 'Y' IF @update = 'Y' UPDATE mytable SET myColumn = 'chang...
There are two questions here. One is why the `IF` statement doesn't work - because T-SQL doesn't have braces. The syntax is shown in [the documentation](https://msdn.microsoft.com/en-us/library/ms182717.aspx). The important question though is how to pass parameters to the script without having the users modify the scr...
Only run SQL query if condition met
[ "", "mysql", "sql", "sql-server", "" ]
I've got this: ``` SELECT COUNT(*) FROM TABLE1, TABLE2, TABLE3; ``` Say TABLE1 has 5 entries, TABLE2 has 5 entries, and TABLE3 has one, COUNT(\*) essentially becomes 5\*5\*1 = 25. Is there a reason for this? Ideally, I want the total rowcount from all 3 tables WITHOUT having to use multiple from stat...
``` SELECT COUNT(*) FROM TABLE1, TABLE2, TABLE3; ``` does a `CROSS JOIN`. It matches each record in `TABLE1` with each record in `TABLE2`, then matches eash result with each record in `TABLE3`, so for example if `TABLE1` contained 2 records, `TABLE2` contained 3 records and `TABLE4` contained 4 record...
The reason is you are making join 's (cross join) , is about the set theory from the school , if you want count 3 different tables and then sum that counts together , you can do this: ``` SELECT SUM(COUNT) FROM (SELECT COUNT(*) AS COUNT FROM TABLE1 UNION ALL SELECT COUNT(*) AS COUNT FROM TABLE2 UNION ALL SELECT COUNT...
Why does COUNT(*) multiply the results when there are several tables?
[ "", "sql", "" ]
I have list of file path stored in a column of a table. Now I need to extract only till last '\' in file path (i.e like below result set) Example: ``` column_A -------------- G:\REPORTS\DDMS\PCP0.txt G:\REPORTS\DPS\DEFAU.pdf ``` Result ``` G:\REPORTS\DDMS\ G:\REPORTS\DPS\ ```
Try this. ``` DECLARE @str VARCHAR(500)='G:\REPORTS\DDMS\PCP0.txt' SELECT Reverse(Substring(Reverse(@str), Charindex('\', Reverse(@str)), Len(@str))) ```
Try this ``` DECLARE @str VARCHAR(500)='G:\REPORTS\DDMS\PCP0.txt' SELECT LEFT(@str, len(@str) - CHARINDEX('\', REVERSE(@str))) ```
Find Path of the file using substring
[ "", "sql", "sql-server", "t-sql", "" ]
I'm attacking a problem, where I have a value for a a range of dates. I would like to consolidate the rows in my table by averaging them and reassigning the date column to be relative to the last 7 days. My SQL experience is lacking and could use some help. Thanks for giving this a look!! E.g. 7 rows with dates and va...
Am taking following as sample ``` CREATE TABLE some_data1 (unique_id text, date date, value integer); INSERT INTO some_data1 (unique_id, date, value) VALUES ( 'a', '2014-03-20', 2), ( 'a', '2014-03-21', 2), ( 'a', '2014-03-22', 3), ( 'a', '2014-03-23', 5), ( 'a', '2014-03-24', 1), ( 'a', '2014-03-25', 0), ( '...
For PostgreSQL a window function might be what you want: ``` DROP TABLE IF EXISTS some_data; CREATE TABLE some_data (unique_id text, date date, value integer); INSERT INTO some_data (unique_id, date, value) VALUES ( 'a', '2014-03-20', 2), ( 'a', '2014-03-21', 2), ( 'a', '2014-03-22', 3), ( 'a', '2014-03-23', 5)...
Get average of last 7 days
[ "", "sql", "postgresql", "amazon-redshift", "" ]
I need to find only one entry from db which is less than other row i have written this query , is there other method than this? ``` SELECT * FROM users WHERE birthdate < 1420239600 ``` It will return all users whose birthdate is less than 1320239600 but i need to show only one row like 1320239599 not 1 to 1320239...
**MYSQL** ``` SELECT * FROM users WHERE birthdate < 1420239600 ORDER BY birthdate DESC LIMIT 1 ``` **MSSQL** ``` SELECT TOP 1 * FROM users WHERE birthdate < 1420239600 ORDER BY birthdate DESC ``` This will select the first entry only
I think the safest option would be like this: ``` SELECT * FROM USERS WHERE birthdate < 1320239600 ORDER BY birthdate DESC LIMIT 1; ``` You had the less than operator the wrong way round. Arijit's answer is only valid for MS SQL Server or MS Access, this statement using ORDER BY and LIMIT is the equivalent in MySQL.
find only one entry from database with less than condition
[ "", "mysql", "sql", "select", "" ]
I have this table called myTable ``` Posting Date|Item No_|Entry Type| 2015-01-13|1234|1 2015-01-13|1234|1 2015-01-12|1234|1 2015-01-12|5678|1 2015-02-12|4567|1 ``` What I want, is only return result where a [Item No\_] is ind the table 1 time. So in this example of my table, i only want to return [Item No\_] 5678 an...
Remove `Posting Date` from `group by` ``` SELECT [Item No_],Entry Type, COUNT([Item No_]) AS Antal FROM myTable GROUP BY [Entry Type], [Item No_] HAVING COUNT([Item No_]) = 1 ``` or if you want other details use a `subquery` ``` SELECT [Item No_], Entry Type, Posting Date FROM myTable a WHERE ...
``` select [Item No_] from myTable group by [Item No_] having count(*)=1 ```
only return records count() = 1
[ "", "sql", "sql-server", "" ]
I am trying the following select statement including columns from 4 tables. But the results return each row 4 times, im sure this is because i have multiple left joins but i have tried other joins and cannot get the desired result. ``` select table1.empid,table2.name,table2.datefrom, table2.UserDefNumber1, table3....
If the duplicate rows are identical on each column you can use the `DISTINCT` keyword to eliminate those duplicates. But I think you should reconsider your `JOIN` or `WHERE` clause, because there has to be a reason for those duplicates: 1. The WHERE clause hits several rows in table2 having the same month on a single...
If your query is returning duplicates, then one or more of the tables have duplicate `empid` values. This is a *data* problem. You can find them with queries like this: ``` select empid, count(*) from table1 group by empid having count(*) > 1; ``` You should really fix the data and query so it returns what you want. ...
Joining multiple tables returning duplicates
[ "", "sql", "sql-server", "select", "join", "inner-join", "" ]
``` select * INTO [dbo].[aTable] from dbo.bt btg left join dbo.btt bta on btg.specialty = bta.specialty order by 1, 6 ``` I am getting the following error: > Column names in each table must be unique. Column name 'Specialty' in table 'aTable' is specified more than once. Columns for `bt` table: ``` Location Specia...
The issue here is the "Select \*", which will select all fields in your result set. Try specifying the specific fields that you want to insert. For instance: ``` SELECT Location, btg.Specialty, Provider, Topic INTO INTO [dbo].[aTable] from dbo.bt btg left join dbo.btt bta on btg.specialty = bta.specialty order by 1,...
**Alias name is all you need** to mention to avoid conflict when you join two tables with same column names. ``` SELECT btg.Location, btg.Specialty, btg.Provider,btg.Topic INTO INTO [dbo].[aTable] from dbo.bt btg join dbo.btt bta on btg.specialty = bta.specialty order by 1, 6 ```
How to merge two tables with having same column name
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I am looking for the simplest solution that will resolve following problem. I have a table: ``` Column1 Column2 ------- ------- A 11 A NULL B 12 B 14 B NULL C NULL ``` I would like to query(Select) this...
Try this: ``` SELECT column1, column2 FROM dummy t1 WHERE column2 IS NOT NULL OR NOT EXISTS (SELECT '' FROM dummy t2 WHERE t1.column1 = t2.column1 AND column2 IS NOT NULL) ``` Keeps all rows for which column2 either not NULL or are...
Should work like this ( there might be a more perfomant way though ) ``` select column1, column2 from table where column2 is not null union ( select column1, column2 from table where column2 is null and column1 not in ( select column1 from table where c...
Oracle function to distinct NULL values based on other column
[ "", "sql", "oracle", "function", "select", "null", "" ]