Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a query like so - ``` select CAST(jobrun_proddt as Date) as 'Date', COUNT(*) as 'Error Occurred Jobs' from jobrun where jobrun_orgstatus = 66 and jobmst_type <> 1 group by jobrun_proddt order by jobrun_proddt desc ``` Not every date will have a count. What I want to be able to do is the dates that are blank to...
Try this. Use `Recursive CTE` to generate the Dates. ``` WITH cte AS (SELECT CONVERT(DATE, '2014-11-18') AS dates --Max date UNION ALL SELECT Dateadd(dd, -1, dates) FROM cte WHERE dates > '2014-11-11') -- Min date SELECT a.dates, Isnull([Error_Occurred_Jobs], 0) FROM ...
If you have data for all dates, but the other dates are being filtered by the `where` clause, then you can use conditional aggregation: ``` select CAST(jobrun_proddt as Date) as [Date], SUM(CASE WHEN jobrun_orgstatus = 66 and jobmst_type <> 1 THEN 1 ELSE 0 END) as [Error Occurred Jobs] from jobrun gr...
how to include dates where no value
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to Copy ALL data (columns, too) from `Table1` in to `Table2` but ONLY where `Column1` is XYZ. I have something like: ``` INSERT INTO Table2 SELECT * FROM Table1 WHERE Column1='XYZ' ``` This errors telling me that `Column1` is an unknown field name.
Your column names must match, so alias them as they come out of `Table1` so they match `Table2` ``` INSERT INTO Table2 SELECT table1_column1 as table2_column1 FROM Table1 WHERE table1_column1='XYZ' ```
INSERT INTO table2 (column\_name(s)) SELECT column\_name(s) FROM table1;
Insert Into WHERE Data in a column is specific
[ "", "mysql", "sql", "ms-access", "" ]
I have a table called `profile` which has a column `region_code` and `country_code` and another table called `regions` which has columns `country_code`, `region_name` and `region_code`. I want to select the `region_name` from table `regions` based on the `region_code` and `country_code` from table `profiles`. I thought...
I would simplify your query, and use something like this one: ``` SELECT region_name FROM regions WHERE (country_code, region_code) IN (SELECT country_code, region_code FROM profiles WHERE account_name = 'me') ``` but if you still get empty re...
It sounds like you want a join? ``` SELECT r.region_name FROM regions r JOIN profiles p ON r.country_code = p.country_code AND r.region_code = p.region_code WHERE p.account_name = 'me' ``` This would list the region name for the region that maps to the specific users region code and country code.
selecting region names based on country and region codes
[ "", "mysql", "sql", "" ]
Can any one help me in solving this. In a table, I have the data like this right now. ![enter image description here](https://i.stack.imgur.com/ir0A7.jpg) How do i split the column Nodes which has delimiter TTBFA-TTBFB-TTBFC-TTBFD into 4 rows with other columns being same. california region GAXAEB 102,520,000 18.71 ...
you could use (whatever number is your max number of nodes) `UNION ALL` statements and `SUBSTRING` with INSTR for the possible locations for a node try something like: ``` SELECT region_name, nodes AS node, sgspeed, sgutil, portCount, WeekendingDate FROM t WHERE instr(nodes,'-'...
The function INSTR usually implies you're running TD14+. There's also the STRTOK function, better use this instead of SUBSTRING(INSTR). And instead of up to 15 UNION ALLs you can also cross join to a table with numbers: ``` SELECT region_name, STRTOK(nodes, '-', i) AS x FROM table CROSS JOIN ( -- better don't use s...
Split The Column which is delimited into separate Rows in Teradata 14
[ "", "sql", "teradata", "" ]
Where is a problem because I try count values using sql queries: `(SELECT quantity FROM db WHERE no='998')` this is fine but `(('500') - (SELECT quantity FROM db WHERE no='998'))` // incorrect syntax near - But I need to use constant 500. Where is problem
How about this? ``` SELECT 500 - quantity FROM db WHERE no = 998; ``` A `select` statement needs to start with a select. In addition, numeric constants should not use single quotes (although that has no effect on whether the query parses or runs).
`SELECT 500-quantity FROM db WHERE no='998'`
My sql query not work with math operators
[ "", "mysql", "sql", "" ]
I am trying to sort the numbers, ``` MH/122020/101 MH/122020/2 MH/122020/145 MH/122020/12 ``` How can I sort these in an Access query? I tried `format(mid(first(P.PFAccNo),11),"0")` but it didn't work.
You need to use expressions in your ORDER BY clause. For test data ``` ID PFAccNo -- ------------- 1 MH/122020/101 2 MH/122020/2 3 MH/122020/145 4 MH/122020/12 5 MH/122021/1 ``` the query ``` SELECT PFAccNo, ID FROM P ORDER BY Left(PFAccNo,9), Val(Mid(PFAccNo,11)) ``` returns ``` PFAccNo...
you have to convert your substring beginning with pos 11 to a number, and the number can be sorted.
How to sort the string 'MH/122020/[xx]x' in an Access query?
[ "", "sql", "sorting", "ms-access", "" ]
I am trying (and failing) to craft a simple SQL query (for SQL Server 2012) that counts the number of occurrences of a value for a given date range. This is a collection of results from a survey. So the end result would show there are only 3 lots of values matching '2' and 6 values matching '1'. Even better if the f...
You can use conditional aggregation: ``` SELECT SUM((CASE WHEN friendly = 0 THEN 1 ELSE 0 END) + (CASE WHEN professional = 0 THEN 1 ELSE 0 END) + (CASE WHEN comfortable = 0 THEN 1 ELSE 0 END) + (CASE WHEN rate = 0 THEN 1 ELSE 0 END) + (CASE WHEN recommend = 0 THEN 1 ELSE 0 E...
If I understand you correctly, you want to count the zeros, ones and twos for a particular (or each) column in your table. If this is correct, then you could do something like this: ``` select sum(case when your_column = 0 then 1 else 0 end) as zeros , sum(case when your_column = 1 then 1 else 0 end) as ones ...
SQL Query to COUNT fields that match a certain value across all rows in a table
[ "", "sql", "sql-server", "t-sql", "" ]
I wrote a CREATE FUNCTION script, and created a function. But I can't find it in the LONG list of functions under the programability folder in SSMS. Where did SQL Server put my function. It's not in any of the folders, or if it is, I missed it. And I looked twice. I did specify at the beginning of my script: ``` USE ...
Look under \Programmability\Functions. To use those objects refer to this post [SQLServer cannot find my user defined function function in stored procedure](https://stackoverflow.com/questions/4697241/sqlserver-cannot-find-my-user-defined-function-function-in-stored-procedure)
I apologise. The questioner is an idiot. All that I needed to do was right click on the Function folder in SSMS and choose "Refresh". Sorry for wasting your time.
I created a SQL Server function. Now I can't find it in SSMS
[ "", "sql", "sql-server", "ssms", "" ]
I have a table which have 2 columns of dates, and I want to look for the closest date in the future (Select min()?) searching in both columns, is that possible? For example, if I have `column1=23/11/2014` and `column2=22/11/2014`, in the same row, I want get `22/11/2014` I hope it is clear enough, ask me if it doesn'...
In a single table use [CASE](https://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions004.htm) ``` SELECT CASE column1 < column2 THEN column1 ELSE column2 END mindate FROM yourtable ``` If you have the date column in multiple tables, just replace `yourtable` with your tables ...
This is what the `least()` function is for: ``` select least(column_1, column_2) from your_table; ``` `min()` is an aggregate function that operates on a single column but multiple rows.
It is possible to do a SELECT MIN(DATE) searching in 2 or more columns?
[ "", "sql", "oracle", "function", "" ]
I have a student table where column is `name`, `attendance`, and `date` in which data is entered everyday for the students who attend the class. For example if a student is absent on a day, entry is not made for that particular student for that day. Finally. I need to find out students name whose `attendance` less tha...
You have to use [GROUP BY](http://www.w3schools.com/sql/sql_groupby.asp) clause to aggregate similar student in table and [HAVING](http://www.w3schools.com/sql/sql_having.asp) check your condition, to get your desired output. ``` SELECT name, count(name) FROM student GROUP BY column_name HAVING count(name)<50; ``...
You can use `GROUP BY` and `HAVING` statements for this. ``` SELECT name FROM student GROUP BY name HAVING COUNT(*) < 50; ``` Please note that above query is not tested.
find student name less than 50 attendance
[ "", "sql", "" ]
There are two tables, package table and product table. In my case, the package contains multiple products. We need to recognize multiple products whether they can match a package which is already in package records. Some scripts are below. ``` DECLARE @tblPackage TABLE( PackageID int, ProductID int ) INSE...
Try this. [***SQLFIDDLE DEMO***](http://sqlfiddle.com/#!3/fb8e1/16) ``` Declare @cnt Int Select @cnt = count(distinct ProductID) from tblProduct SELECT B.packageid FROM (SELECT packageid FROM tblpackage GROUP BY packageid HAVING Count(productid) = @cnt) A JOIN tblpackage B ...
This is a "set-within-sets" query. I would approach it using aggregation and `having`: ``` select p.PackageID from @tblPackage p left join @tblProduct pr on p.ProductId = pr.ProductId group by p.PackageId having count(*) = count(pr.ProductId) and count(*) = (select count(*) from @tblProduct); ``` The...
T-SQL How to Match Multiple Rows
[ "", "sql", "sql-server", "" ]
For example I have a table like given below .. I want to have separate columns on the basis of even/odd ids ``` ----------------------------------------------------- | ID | Names ----------------------------------------------------- | 1 | Name1 ----------------------------------------------------- | 2 | Name2 ...
``` select max(case id%2 when 1 then name end) as odd, max(case id%2 when 0 then name end) as even from your_table group by floor((id+1)/2) ``` `SQL Fiddle Demo`
If your Id column contain sequential number without any gap between number then : ``` SELECT t1.name as ODD, t2.name as EVEN FROM YourTable t1 left outer JOIN YourTable t2 ON t1.Id + 1 = t2.Id where t1.Id%2 = 0 ``` Note : if there are gaps between number then some of the `ODD` will be shown a...
how to get even odd ids in different columns on single query?
[ "", "mysql", "sql", "" ]
I have a table in mysql database. Like ``` +-----+------+------+--------+ | id | p_id | lang | title | +-----+------+------+--------+ | 1 | 1 | en | eng1 | | 2 | 1 | fr | fr1 | | 3 | 2 | en | eng2 | +-----+------+------+--------+ ``` I want to select records of `P_id` of `lang` = `fr...
Mysql Query (untested) ``` SELECT DISTINCT a.p_id FROM myTable a WHERE a.lang = 'fr' UNION SELECT DISTINCT b.p_id FROM myTable b WHERE b.lang = 'en' AND NOT EXISTS ( SELECT 1 FROM myTable c WHERE c.lang = 'fr' AND c.p_id = b.p_id ) ``` I take all the fr rows then i add all the en where does not exist a fr row.
``` SELECT id, p_id, lang, title FROM your_table WHERE lang IN ('fr', 'en') ORDER BY lang = 'fr' DESC /*optionally*/ LIMIT 1; ``` The `lang = 'fr'` in the `order by` returns 1 or 0, true or false. This makes sure, that the `fr` record is first. Or like this: ``` SELECT SQL_CALC_FOUND_ROWS id, p_id, lang, title FROM ...
How to get records if a column has value A, if not then B?
[ "", "mysql", "sql", "" ]
I have about 10000 rows in SQL table, and I need to add a prefix before each value of user column. Example: I have value names like John, Smith, and so on, and I need to set QA-John, QA-Smith, and so on. Is there an SQL function that can do it automatically or only can be done it one by one?
I got it. ``` UPDATE my table SET column_name = CONCAT('prefix', column_name) ```
If I haven't misunderstood, this is what You're asking.. ``` Update Table set name="QA-"+name ```
Adding prefix to value in SQL row values
[ "", "sql", "" ]
I have a table like this ``` Rules (RuleValue varchar (50)) ``` It has values like ``` A1B1C1 A1B1C0 A1B0C0 ``` There is another table ``` Input (RulePart varchar (2)) ``` It can have values like: ``` A1 B1 C1 ``` I want to get all RuleValues where all the RulePart matches anywhere in the RuleValue Following is...
One approach is: ``` Select r.RuleValue from Rules r join Input i on r.RuleValue like '%' + i.RulePart + '%' group by r.RuleValue having count(distinct i.RulePart) = 3 -- or (select count(*) from Input ) ``` **UPDATE** More elegant way is using `NOT EXISTS` to represent for `ALL` ``` select * from ...
```` ``` SELECT * FROM Rules a WHERE RuleValue LIKE '%'+(SELECT stuff((select '%' + cast(c.RulePart as varchar(512))from Input c for xml path('')),1,2,''))+'%' ``` ````
SQL query to select records that has matching substring in a field from another table
[ "", "sql", "sql-server-2012", "" ]
My apologies for a non-intuitive thread title. I have a table, `Jobs`, where each row represents a maintenance task performed by a computer program. It has this design: ``` CREATE TABLE Jobs ( JobId bigint PRIMARY KEY, ... Status int NOT NULL, OriginalJobId bigint NULL ) ``` When a Job is created/sta...
The following returns the result required: ``` SELECT J1.JobId, Retries = COUNT(J2.JobId) FROM Jobs AS J1 INNER JOIN Jobs AS J2 ON J1.JobId = J2.OriginalJobId WHERE J1.Status = 2 GROUP BY J1.JobId HAVING COUNT(CASE WHEN J2.Status = 1 THEN 1 END) = 0; ``` I have changed it to an `INN...
This should do the job. It does a COALESCE to combine `JobId` and `OriginalJobId`, gets the retry count by grouping them up then excluding any jobs that have a status of 1. ``` SELECT COALESCE(j.OriginalJobId, j.JobId) JobId, COUNT(*)-1 RetryCount FROM Jobs j WHERE j.[Status] = 2 AND NOT EXISTS (SELECT 1 ...
Retrieving failed jobs from a table with retry details (id and retry count)
[ "", "sql", "sql-server", "" ]
I have two tables, created with the following SQL queries: ``` CREATE TABLE user ( user_email varchar(255) not null primary key, --other unimportant columns subscription_start date not null, subscription_end date, CONSTRAINT chk_end_start CHECK (subscription_start != subscription_end) ) CREAT...
This is not possible to do using check constraints, since check constraints can only refer to columns inside the same table. Furthermore, foreign key constraints only support equi-joins. If you must perform this check at the database level instead of your application level, you could do it using a trigger on INSERT/UP...
I always try to avoid triggers where possible, so thought I would throw an alternative into the mix. You can use an indexed view to validate data here. First you will need to create a new table, that simply contains two rows: ``` CREATE TABLE dbo.Two (Number INT NOT NULL); INSERT dbo.Two VALUES (1), (2); ``` Now you ...
SQL constraint check with date from table linked with foreign key
[ "", "sql", "sql-server", "sql-server-2012", "" ]
So I have this table (table1): ![enter image description here](https://i.stack.imgur.com/vYYlb.png) I need to know all the 'num' who dont know HTML I tried - `SELECT num FROM table1 WHERE package <> HTML` The problem is, for example, that NUM 2 knows Excel aswell, so he still shows up in the result... Any ideas?
``` SELECT DISTINCT num FROM table1 WHERE (num NOT IN (SELECT num FROM table1 WHERE package = 'HTML')) ``` I don't have access to a MySQL box at this moment, but that should work.
Try this: ``` SELECT DISTINCT num FROM table1 WHERE num NOT IN (SELECT num FROM table1 WHERE package = 'HTML') ```
SQL - Removing other entries
[ "", "mysql", "sql", "" ]
I've got a few columns that have values either in fractional strings (i.e. 6 11/32) or as decimals (1.5). Is there a `CAST` or `CONVERT` call that can convert these to consistently be decimals? The error: Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar to numeric. Can I avoid doing any kind of...
``` CREATE FUNCTION ufn_ConvertToNumber(@STR VARCHAR(50)) RETURNS decimal(18,10) AS BEGIN DECLARE @L VARCHAR(50) = '' DECLARE @A DECIMAL(18,10) = 0 SET @STR = LTRIM(RTRIM(@STR)); -- Remove extra spaces IF ISNUMERIC(@STR) > 0 SET @A = CONVERT(DECIMAL(18,10), @STR) -- Check to see if alrea...
You'll need to parse. As Niels says, it's not really a good idea; but it can be done fairly simply with a T-SQL scalar function. ``` CREATE FUNCTION dbo.FracToDec ( @frac VARCHAR(100) ) RETURNS DECIMAL(14, 6) AS BEGIN RETURN CASE WHEN @frac LIKE '% %/%' THEN CAST(LEFT(@frac, CH...
Convert fractional string to decimal
[ "", "sql", "sql-server", "casting", "" ]
I'm running this query: ``` SELECT "uname","sip",count(1) as cnt FROM "random_data_date" GROUP BY "uname","sip"; ``` To get something like this: ``` +------------+-----------------+--------------+ | uname | sip | cnt | +------------+-----------------+--------------+ | root | 172.17.16...
Would be something like this: ``` SELECT "uname", count(distinct "sip"), count("sip") as cnt FROM "random_data_date" GROUP BY "uname" ; ```
``` SELECT "uname", Count(distinct "sip") as "sipcnt", count(1) as cnt FROM "random_data_date" GROUP BY "uname"; ```
Count records of a column after group by in SQL
[ "", "sql", "select", "apache-phoenix", "" ]
I have a table named conductor. I want to select latest records that `date` less than `my_value`. ``` +----+-----------+------+ | id | program | date | +----+-----------+------+ | 1 | program 1 | 1 | | 2 | program 1 | 3 | | 3 | program 2 | 3 | | 4 | program 1 | 5 | | 5 | program 1 | 7 | +----+---...
``` SELECT * FROM Conductor WHERE `date` = (SELECT max(`date`) FROM Conductor WHERE `date` < myvalue ) ```
``` SELECT * FROM Conductor WHERE date IN (SELECT max(date) FROM Conductor WHERE date < myvalue ) ```
How to select latest records less than value
[ "", "mysql", "sql", "" ]
Given a table such as the following called form\_letters: ``` +---------------+----+ | respondent_id | id | +---------------+----+ | 3 | 1 | | 7 | 2 | | 7 | 3 | +---------------+----+ ``` How can I select each of these rows except the ones that do not have the maximum id value f...
Something like this should work; ``` SELECT respondent_id, MAX(id) as id FROM form_letters group by respondent_id ``` MySQL fiddle: <http://sqlfiddle.com/#!2/5c4dc0/2>
There are many ways of doing it. `group by` using `max()`, or using `not exits` and using `left join` Here is using left join which is better in terms of performance on indexed columns ``` select f1.* from form_letters f1 left join form_letters f2 on f1.respondent_id = f2.respondent_id and f1.id < f2.id where f2.res...
Select each row of table except where the id is not the maximum value for a given foreign key
[ "", "mysql", "sql", "" ]
If i have the following query > select sum(8.9177 + 7.1950 + 5.1246) as total > from table1 Gives me `21.2373` how do i round that figure to only be `21.2`. I must always only have one decimal place, nothing more
``` SELECT ROUND(SUM(8.9177 + 7.1950 + 5.1246),1) AS total FROM table1 ```
here are two solutions : 1. it will cast it it in decimal with 1 decimal point : select cast((sum(8.9177 + 7.1950 + 5.1246)) AS decimal(19,1)) from yourtable 2. it will round it upto 1 decimal point but output will remail in 4 decimal place select round(sum(8.9177 + 7.1950 + 5.1246),1) from yourtable use 2nd ...
how to remove certain amount of decimals in sql server
[ "", "sql", "sql-server-2008", "" ]
I am trying to get duplicate counts but without actually removing duplicates. I tried using `GROUP BY id` and then `COUNT(id)` but it removes all duplicate entries. Is there any way to not remove duplicates? The table looks like this: ``` ID1 ID2 Value 1 2 someval 1 3 someval 1 4 somev...
One of way doing this is to have a separate query for the count and join on it: ``` SELECT t.id1, t.id2, t.value, cnt FROM my_table t JOIN (SELECT id1, count(*) AS cnt FROM my_table GROUP BY id1) c ON t.id1 = c.id1 ```
You can do this with a correlated subquery in MySQL; ``` select id1, id2, value, (select count(*) from table t2 where t2.id1 = t.id1) as count from table t; ```
Get Duplicated Count Without Removing
[ "", "mysql", "sql", "group-by", "" ]
i have a 4 columns in my table.. ``` digit1 digit2 digit3 amount 1 2 3 1 2 2 2 1 2 1 3 1 3 2 1 1 ``` and i want to group them if the row has the same digit value..and the output would be like this : ``` digit1 digit2 digit3 amount ...
here a solution if all digits has the same set of numbers ( 2,1,3) ,(3,2,1),...etc, this means they have same factorial example: 2\*1\*3=3\*2\*1 ... etc **NOTE**: this solution works for any digits different than zero (Factorial rule) steps of solution 1. make multiplication and summation for each row 2. make part...
``` please try this one i did it in oracle but its simple sql so it will too work on your DBMS select digit1,digit2,digit3,(select sum(amount) from expdha where digit2<>digit1+1 and digit3<>digit2+1) amount from expdha where digit2=digit1+1 and digit3=digit2+1 group by ...
how to match values in sql ?
[ "", "sql", "vb.net", "" ]
I am using SQL Server 2008 and need to create a query that shows rows that fall within a date range. My table is as follows: ``` ADM_ID WH_PID WH_IN_DATETIME WH_OUT_DATETIME ``` My rules are: * If the WH\_OUT\_DATETIME is on or within 24 hours of the WH\_IN\_DATETIME of another ADM\_ID with the same WH\_P...
Since the question does not specify that the solution be a "single" query ;-), here is another approach: using the "quirky update" feature dealy, which is updating a variable at the same time you update a column. Breaking down the complexity of this operation, I create a scratch table to hold the piece that is the hard...
I would do this using `exists` in a correlated subquery: ``` select t.*, (case when exists (select 1 from table t2 where t2.WH_P_ID = t.WH_P_ID and t2.ADM_ID = t.ADM_ID and t.WH_OUT_DATETIME betwe...
Grouping rows with a date range
[ "", "sql", "sql-server", "sql-server-2008", "" ]
**I want to replace the space with Special characters while searching in OBIEE** *Example:* When I search for "T MOBILE", I find "T-MOBILE" and "T\_MOBILE", etc. **Here's my Select statement:** ``` SELECT "- Customer Install At"."Cust Number" saw_0, "- Customer Install At"."Cust Name" saw_1, "- Custo...
If you wanted to do something more complex than koriander's answer then the following should work. You can't use database functions (such regexp\_like) directly, only OBI functions. So you need to use the OBI function EVALUATE to pass the regexp\_like function back to the database. (There is plenty of documentation o...
I'm not sure how general you need this to be. For your example, you would use the LIKE operator. ``` WHERE FIELDNAME LIKE 'T_MOBILE' ``` The wildcard underscore "\_" will look for any character matching in that position. The other wildcard you can use is "%" which will match a set of characters of any length.
Replace a Space with Special characters in a SELECT
[ "", "sql", "oracle", "obiee", "" ]
I want to convert 12/8/2006 12:30:00 to 12/8/2006 I tried - ``` 1. trunc(TO_DATE (effective_date_time,'DD/MM/YYYY HH24:Mi:SS')) 2. TO_DATE (effective_date_time,'DD/MM/YYYY') ``` But all these are returning values as 12/8/0006. Why Oracle is returning year 0006 instead of 200![enter image description here](https://i...
Try this: ``` trunc(effective_date_time) ``` It's a date, you don't need TO\_DATE When you're using TO\_DATE(effective\_date\_time, 'format') on a DATE column, effective\_date\_time is converted to a char using NLS params. I suppose your NLS settings is something like 'dd/mm/yy'. That's why you get a wrong year. A ...
If `effective_date_time` is a `date` column using `to_date()` is totally useless. It will first (implicitely!) convert the `date` to a `varchar` (based on the NLS settings, just to convert it back to a `date` again. If you want a specific format for your date column use `to_char()` ``` to_char(effective_date_time,'D...
Issue in removing time stamp in PL/SQL
[ "", "sql", "oracle", "date", "plsql", "timestamp", "" ]
I'm working to update a stored procedure that current selects up to n rows, if the rows returned = n, does a select count without the limit, and then returns the original select and the total impacted rows. Kinda like: ``` SELECT TOP (@rowsToReturn) A.data1, A.data2 FROM mytable A SET @maxRows = @@ROWCOU...
As @MartinSmith mentioned in a comment on this question, there is no direct (i.e. pure T-SQL) way of getting the total numbers of rows that would be returned while at the same time limiting it. In the past I have done the method of: * dump the query to a temp table to grab `@@ROWCOUNT` (the total set) * use `ROW_NUBME...
How about this.... ``` DECLARE @N INT = 10 ;WITH CTE AS ( SELECT A.data1, A.data2 FROM mytable A ) SELECT TOP (@N) * , (SELECT COUNT(*) FROM CTE) Total_Rows FROM CTE ``` The last column will be populated with the total number of rows it would have returned without the TOP Clause. The issue with you...
TSQL: Is there a way to limit the rows returned and count the total that would have been returned without the limit (without adding it to every row)?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sqlclr", "" ]
For a table such as this: ``` tblA A,B,C 1,2,t3a 1,3,d4g 1,2,b5e 1,3,s6u ``` I want to produce a table that selects distinct on both A and B simultaneously, and still keep one value of C, like so: ``` tblB A,B,C 1,2,t3a 1,3,d4g ``` Seems like this would be simple, but not finding it for the life o...
This should do the trick ``` CREATE TABLE tblB AS ( SELECT A, B, max(C) AS max_of_C FROM tblA GROUP BY A, B ) ```
When you use `DISTINCT ON` you should have `ORDER BY`: ``` SELECT DISTINCT ON (A,B), C INTO tblB FROM tblA ORDER BY A, B; ```
Select distinct on multiple columns simultaneously, and keep one column in PostgreSQL
[ "", "sql", "postgresql", "" ]
I have two tables. **Invoices** ``` ID | Amount ----------- 1 | 123.54 2 | 553.46 3 | 431.34 4 | 321.31 5 | 983.12 ``` **Credit Memos** ``` ID | invoice_ID | Amount ------------------------ 1 | 3 | 25.50 2 | 95 | 65.69 3 | 51 | 42.50 ``` I want to get a result set like this out of ...
Your query would work fine. Just add `Credit_memo.Amount` with an alias: ``` SELECT Inv.ID,Inv.Amount,IFNULL(C.Amount,'') AS Cr_memo FROM Invoices Inv LEFT JOIN Credit_Memos C ON Inv.ID=C.invoice_ID ``` Result: ``` ID AMOUNT CR_MEMO 1 124 2 553 3 431 25.50 4 321 5 983 ``` See result in [**SQL...
You almost got the answer `Left Outer Join` is what you need but you missed to select `Cr_memo` from `Credit_Memos` table. Since you don't want to show Null values when there is no `Invoices_ID` in `Credit Memos` table use `IFNULL` to make `NULL's` as Empty string ``` SELECT A.ID, A.Amount, IFNULL(B.Cr_memo,'') AS Cr_...
Select data from another table if exists, if not display null
[ "", "mysql", "sql", "" ]
Given two Tables that are Linked together ``` tbl_Gasoline -------------- ID | Type ------------- 1 | Diesel 2 | Kerosene ``` and ``` tbl_Expense ----------------------------- ID | Price | GasolineType (tbl_Gasoline foreign key) ----------------------------- 1 | 5000 | 1 2 | 4000 | 2 3 | 3000 | 1 ``` I...
Try this one ``` SELECT e.id, SUM(price) AS 'price', g.NAME FROM tbl_expense e INNER JOIN tbl_gasoline g ON e.GasolineType = g.id GROUP BY e.id, g.NAME ```
**Please Try this.** ``` SELECT e.id, SUM(price) AS 'price', g. NAME FROM tbl_expense e INNER JOIN tbl_gasoline g ON e.GasolineType = g.id GROUP BY g.id,g. NAME ```
SELECT DISTINCT TWO COLUMNS and SUM another COLUMN's VALUES
[ "", "sql", "sql-server-2008", "sum", "distinct", "" ]
When I try to execute this query ``` INSERT INTO StateRegion ( FullName , Abbreviation , RegionType , Admitted , Capital ) VALUES ( 'Alabama' , 'AL' , 1 , '1819-Dec-14' , 'Montgomery' ); ``` it gives me error sql...
The month name part of that date format is interpreted according to the language of the login. You can change the default language of the login to US English or British English if you must work with that format or issue a ``` Set language english ``` To set the format at run time before the problematic query then ...
Use a parameterized query. Parameterization will send the date to the server in binary, avoiding any string conversions which depend upon the client locale. Example in C#: ``` SqlCommand sqc = new SqlCommand("INSERT INTO MyTable (DateColumn) VALUES (@date)", con); sqc.Parameters.AddWithValue("@date", new DateTime(181...
Inserting date in sql server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I created two tables Category and Products for my shopping cart database. Should I build a third table CategoryProduct and save both the ID's of category and Products in it or have a column in the product table to save the category to it. I ask because I need to display the products, category wise. Please guide or sho...
If the product belongs to only one category, then you don't need a third table. Just create a column `CategoryId` as a foreign key and references the `CategoryId` from the categories table. However, if the product belongs to many categories, then you need a third table, something like `CategoryProducts` with columns: ...
It depends on if a Product can have more than one Category, if this is the case then you will need the 3rd table to hold id's of both. If it is one Category per product you can add a Foreign Key to the Product table to hold the category id.
How to add category to product in mysql
[ "", "mysql", "sql", "shopping-cart", "" ]
I've two tables structure is below ``` person (id, fname, lname, ph, mob, dob, email) address (id, address1, address2, address3, town, county, postcode) person_address (id, person_id, address_id) ``` I've have a issue here, if one person have more than one address how would i work out which is active or current addre...
Presumably, a person can have only one current address. If so, you should add a column into the `person` table, called something like `CurrentAddress`. If you *require* a current address, you can even declare `CurrentAddress` to be `NOT NULL`. If a person could have more than one current address, then use a flag in `...
You should add a bit in the person\_address table to indicate if it is the current address or not. Make sure there are not more than one current addresses via sql or code checks: ``` person_address (id, person_id, address_id, current) ```
MySQL relationship issue
[ "", "mysql", "sql", "database", "foreign-keys", "" ]
I materialize the result of a view in a table. I want to know if their is a way to know when the result of this view change to refresh it. Materialized view and result cache can do that but I don't want to use both techniques. Is their another way to answer to this question? In fact we have a generic system who materi...
You could have a flag table that looks something like this: ``` CREATE TABLE FlagTable SourceTable varchar(30), UpdateDate DATETIME, Handled CHAR(1) DEFAULT 'N' ``` Create a trigger on your base tables, where on INSERT, UPDATE, or DELETE of the table, you insert a record into FlagTable with the name of the base...
You can do all this in an easier way, by setting the mat\_view with refresh on commit option and if possible, also to make it refresh *fast* on commit. This will guarantee you that each time a change occurs the view will refresh only the new lines (compared to complete refresh, where the query behind the view is execut...
When refreshing the result of a view?
[ "", "sql", "oracle", "view", "materialized-views", "" ]
Is it possible to use unique on multiple columns? like: ``` user_vote user_id ------------------ 1 1 1 2 2 1 ``` both unique This must be possible But: ``` user_vote user_id 1 2 1 2 ``` This must not be possible
You can add a unique constraint on the column's combination: ``` ALTER TABLE my_table ADD CONSTRAINT my_table_uq UNIQUE (user_vote, user_id) ```
# MySQL / SQL Server / Oracle / MS Access: ``` CREATE TABLE uservotetable ( user_vote int NOT NULL, user_id int NOT NULL, CONSTRAINT uservote UNIQUE (user_vote ,user_id) ); ``` and if you created your table before ..then you can use *ALTER* ``` ALTER TABLE uservotetable ADD CONSTRAINT uservote UNIQUE ...
SQL multiple unique columns
[ "", "sql", "constraints", "unique", "" ]
For example I have this statement: ``` my name is Joseph and my father's name is Brian ``` This statement is split by word, like this table: | ID | word | | --- | --- | | 1 | my | | 2 | name | | 3 | is | | 4 | Joseph | | 5 | and | | 6 | my | | 7 | father's | | 8 | name | | 9 | is | | 10 | Brian | I want to get prev...
you didn't specify your DBMS, so the following is ANSI SQL: ``` select prev_word, word, next_word from ( select id, lag(word) over (order by id) as prev_word, word, lead(word) over (order by id) as next_word from words ) as t where word = 'name'; ``` SQLFiddle: <http://sqlfid...
Why did no-body give the simple answer? ``` SELECT LAG(word) OVER ( ORDER BY ID ) AS PreviousWord , word , LEAD(word) OVER ( ORDER BY ID ) AS NextWord FROM words; ```
Get previous and next row from rows selected with (WHERE) conditions
[ "", "sql", "sql-server", "sql-server-2012", "row", "" ]
I have a table of data that looks like follows: ``` +--------+----------+------------+ | Client | Item No. | Serial No. | +--------+----------+------------+ | A | 1 | 1 | | A | 1 | 2 | | B | 1 | 2 | | B | 2 | 1 | | C | 2 | ...
Maybe this helps: ``` SELECT t.client, t.item, MAX(t.serial) AS serial FROM(SELECT client, MAX(item) AS item FROM your_table GROUP BY client ) a JOIN your_table t ON a.client = t.client AND a.item = t.item GROUP BY t.client, t.item ``` If your...
Postgres has the awesome shortcut ``` SELECT DISTINCT ON (Client) Client, Item, SerialNumber FROM some_table ORDER BY Item DESC, SerialNumber DESC -- DESC gets highest ``` Because of the DISTINCT this grabs only one record per Client, and the ORDER BY makes sure it is the ones you want. I have no idea if any other D...
Finding the Max of another Max query
[ "", "sql", "max", "" ]
I'm building my application in 3-tier architecture. In my `DataAccess` class i got a function for inserting a `Person` into the database. `Person` table has up to 81 columns in the database. The user may not insert all the data in these columns initially, so he might only fill 10 or 20 fields. Is there a way i can ma...
A very good option when writing sprocs that insert rows into a single table is to use [Table-Valued Parameters](http://msdn.microsoft.com/en-us/library/bb675163%28v=vs.110%29.aspx). First, you need to create a `table type` that reflects the table into which you want to insert new records, e.g. ``` CREATE TYPE dbo.Per...
A quick and dirty solution would be to pass in a dictionary of which has the name and value of the items you want to change: ``` public void Upsert(Dictionary<string, object> KeyValues, Dictionary<string, object> Changes) { // insert logic here } ``` PS: Take note that many ORM's solve this problem for you, go an...
Creating a dynamic number of parameters for Insert based on User's input
[ "", "sql", "asp.net", "sql-server", "" ]
I have a hierarchy in SQL Server, with multiple parents, but can't seem to get the result set I need. This is what i have so far. ``` DECLARE @Table TABLE (ChildId varchar(max), ParentId varchar(max)) INSERT INTO @Table (ChildId,ParentId) VALUES ('England',NULL), ('Cities',NULL), ('Towns',NU...
What you are trying to do resembles, at least to some extent, the Ranganathan's classification. In this case you have to go up in hierarchy, not down: ``` with cte as ( select t.ChildId, t.ParentId, 0 as [Lvl] from @Table t where t.ParentId is not null union all select c.ChildId, t.ParentId, c.Lvl ...
What about using a recursive table-valued function instead of a CTE: ``` CREATE FUNCTION tvf_GetParents ( @childID VARCHAR(MAX), @level INT ) RETURNS @output TABLE ( ancestor VARCHAR(MAX), level INT ) AS BEGIN DECLARE @parentIDs TABLE (pID VARCHAR(MAX)) -- Get parent of child and add it...
Show all Children and Grandchildren in SQL Hierarchy CTE
[ "", "sql", "sql-server", "t-sql", "hierarchy", "common-table-expression", "" ]
My SQL table called `categories` has the following structure: ``` CREATE TABLE categories( id int NOT NULL AUTO_INCREMENT, parent_id int, name varchar(50), PRIMARY KEY(id) ); ``` I would like to know if it's possible to JOIN the same table and present the `parent_id` name. I can do this by PHP code, but I...
Use `INNER JOIN` instead of `LEFT JOIN` and you have to join on the `id` equal to the `parent_id` of the other table like this: ``` SELECT c.id, c.name, parents.name AS `Parent Category Name` FROM categories AS c INNER JOIN categories AS parents ON parents.id = c.parent_id ORDER BY c.name ASC; ``` * [**S...
Of course you can do a self join. For the syntax to work you need to use aliases: ``` select c.id, c.name, cp.name as parent_category_name from categories c left join categories cp on c.parent_id = cp.id; ``` In your query, you just have the join in the wrong direction. I would suggest that you use more mea...
MySQL category with parent_id - SELF Join
[ "", "mysql", "sql", "self-join", "" ]
I am having a table with following structure: ``` ID TIME_UNIX STATUS TIME_DDMMYY_HHMMSS 1 1416234308 1 (dateadd(second,[time],'19700101')) 1 1416234313 0 (dateadd(second,[time],'19700101')) 1 1416234319 1 (dateadd(second,[time],'19700101')) 1 ...
``` SELECT ID, MIN(CASE WHEN STATUS = 1 THEN TIME_UNIX ELSE NULL END) AS FIRST_ENABLE_TIME, MAX(CASE WHEN STATUS = 0 THEN TIME_UNIX ELSE NULL END) AS LAST_DISABLE_TIME, TIME_DDMMYY_HHMMSS AS DDMMYYY FROM MyTable GROUP BY ID, TIME_DDMMYY_HHMMSS ```
``` SELECT ID, MIN(CASE WHEN STATUS = 1 THEN TIME_UNIX ELSE NULL END) AS FIRST_ENABLE_TIME, MAX(CASE WHEN STATUS = 0 THEN TIME_UNIX ELSE NULL END) AS LAST_DISABLE_TIME, convert(varchar(10),TIME_DDMMYY_HHMMSS,103) AS DDMMYYY FROM FROM MyTable GROUP BY ID, convert(varchar(10),TIME_DDMMYY_HHMMSS,103) ```
Get min and max value from a multiple rows events
[ "", "sql", "" ]
what does the line (rowid,0) mean in the following query ``` select * from emp WHERE (ROWID,0) in ( select rowid, mod(rownum,2) from emp ); ``` i dont get the line `WHERE (ROWID,0)`. what is it? thanx in advance
`IN` clause in Oracle SQL can support column groups. You can do things like this: ``` select ... from tab1 where (tab1.col1, tab1.col2) in ( select tab2.refcol1, tab2.refcol2 from tab2 ) ``` That can be useful in many cases. In your particular case, the subquery use for the second expression `mod(rownu...
Not sure what dialect of sql you're using, but it appears that since the subquery in the IN clause has two columns in the select list, then the (ROWID,0) indicates which columns align with the subquery. I have never seen multiple columns in an IN statment's select list before.
Confused syntax in Where clause
[ "", "sql", "oracle", "oracle11g", "" ]
Have table like : ``` col1 col2 col3 col4 col5 test1 1 13 15 1 test2 1 13 15 4 test3 2 7 3 5 test4 3 11 14 18 test5 3 11 14 8 test6 3 11 14 11 ``` Want select `col1,col2,col3,col4` data where `col2,col3,col4` are duplicates for example it ...
Presuming SQL-Server >= 2005 you can use [`COUNT(*) OVER`](http://msdn.microsoft.com/en-us/library/ms189461.aspx): ``` WITH CTE AS ( SELECT col1, col2, col3, col4, cnt = COUNT(*) OVER (PARTITION BY col2, col3, col4) FROM dbo.TableName t ) SELECT col1, col2, col3, col4 FROM CTE WHERE cnt > 1 ``` `Demo`
If I understand correctly: ``` select col1, col2, col3, col4 from table t where exists (select 1 from table t2 where t2.col1 = t.col1 and t2.col1 <> t.col1) and exists (select 1 from table t2 where t2.col2 = t.col2 and t2.col1 <> t.col1) and exists (select 1 from table t2 where t2.col3 = t.col3 and t2.col1...
How to select duplicate columns data from table
[ "", "sql", "sql-server", "t-sql", "" ]
Consider three parameters: ``` @Y=2014 @M=11 @D=24 ``` I want to have a function in SQL Server which gets three numbers and return one date as result.
You can use SQL Server 2012 [DATEFROMPARTS](http://msdn.microsoft.com/en-us/library/hh213228.aspx) function. ``` SELECT DATEFROMPARTS(@year, @month, @day) ``` For versions below 2012, I'd use: ``` SELECT CONVERT(DATETIME, STR(@year * 10000 + @month * 100 + @day)) ```
You could do: ``` select cast(cast( (@y * 10000 + @m * 100 + @d) as varchar(255)) as date) ``` But `datefromparts()` is best if you are using SQL Server 2012+.
Converting three int parameter to one date
[ "", "sql", "sql-server", "sql-server-2008", "function", "" ]
I need to check if a partial name matches full name. For example: ``` Partial_Name | Full_Name -------------------------------------- John,Smith | Smith William John Eglid,Timothy | Timothy M Eglid ``` I have no clue how to approach this type of matching. Another thing is that name and last name may come i...
This is what I ended up doing... Not sure if this is the best approach. I split partials by comma and check if first name present in full name and last name present in full name. If both are present then match. ``` CASE WHEN instr(trim(lower(Full_Name)), trim(lower(REGEXP_SUBSTR(Partial_Name, '[^,]+',...
you could use this pattern on the text provided - works for most engines ``` ([^ ,]+),([^ ,]+)(?=.*\b\1\b)(?=.*\b\2\b) ``` [Demo](http://regex101.com/r/yW4aZ3/125)
Check if string variations exists in another string
[ "", "sql", "regex", "oracle", "" ]
I have 2 tables in my database one tblNews and another tblNewsComments I want to select 10 records from tblNewsComments than have must Comments of news I used this query but it give an error ``` SELECT tblNews.id, tblNews.newsTitle, tblNews.createdate, tblNews.viewcount, COUNT(tblNewsCo...
Try to replace ``` GROUP BY tblNews.id ``` With ``` GROUP BY tblNews.id, tblNews.newsTitle, tblNews.createdate, tblNews.viewcount ``` All the expressions in the SELECT list should be in the GROUP BY or inside an aggregate function.
I've always found this to be an annoyance in SQL. There's nothing logically wrong with your query; you're grouping by news item and selecting various attributes of the news item, and then selecting the count of comments linked to the news item. That makes sense. The error arises because the SQL engine isn't smart enou...
How To Get Count of the records in sql
[ "", "sql", "" ]
I have a table CLIENT(id, name, date). in mssql. how can i return all the id's per day. say for instance I have a poller and i want to insert script into a poller that polls once a day. what script will return all the id's created today?
Assuming that `date` is a date with no time component, the simplest way to get the records on the current date is: ``` select id from client where date = cast(getdate() as date); ``` If there is a time component, then use: ``` where date >= cast(getdate() as date) and date < cast(getdate() + 1 as date) ``` Notice t...
use DATEDIFF function to get the difference between datetime in db vs current date ``` SELECT ID FROM Client WHERE DATEDIFF(day, Date, GETDATE()) = 0; ```
How to return all id's per day in mssql
[ "", "sql", "sql-server", "" ]
How to add an offset in a "select" query in Oracle 11g. I only know how to add the limit by e.g `rownum <= 5` this question is not a duplicate, I already checked the other questions and are not related to mine. So, how to add the offset in Oracle 11g ?
You can do it easily on `12c` by specifying `OFFSET`. In `12c`, ``` SELECT val FROM table ORDER BY val OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY; ``` To do the same on `11g` and prior, you need to use `ROWNUM` twice, `inner query` and `outer query` respectively. The same query in `11g`, ``` SELECT val FROM (SELECT ...
You can use ROW\_NUMBER function for that. Maybe this helps: ``` SELECT * FROM(SELECT t.*, ROW_NUMBER() OVER (ORDER BY ...) rn -- whatever ordering you want FROM your_table t ) WHERE rn >= ... -- your offset ``` Hope that helps
How to add offset in a "select" query in Oracle 11g?
[ "", "sql", "oracle", "oracle11g", "pagination", "rownum", "" ]
I'm looking for a text editor, or maybe a complement for Notepad++ to help me when building SQL insert statements. ``` INSERT INTO table_name (column1,column2,column3) VALUES (value1,value2,value3); ``` I would like that when I click on `column2`, `value2` is highlighted, and vice versa. Do you know something that c...
Several good options: <http://www.phpmyadmin.net/home_page/index.php> (PHP + APACHE + MySQL) MySQL Workbech: <http://www.mysql.com/products/workbench/> (MySQL, PgSQL, others) <https://www.jetbrains.com/dbe/> (More general solution)
Maybe you can do this with SublimeText Cheers.
SQL insert statement text editor
[ "", "sql", "insert", "editor", "" ]
I really need to know if i can somehow count 4 different values in a column and store it in 4 different variables. Those variables will be used later in that procedure. This is the code I have but i don't want to use the select statement 4 times but prefferably 1 time. Is there any way to solve it? ``` create or repl...
``` SELECT sum(case FCountGuessed(dData, LiczbyMniejsze, LiczbyWieksze) when 6 then 1 else 0 end), sum(case FCountGuessed(dData, LiczbyMniejsze, LiczbyWieksze) when 5 then 1 else 0 end), sum(case FCountGuessed(dData, LiczbyMniejsze, LiczbyWieksze) when 4 then 1 else 0 end), sum(case FCountGu...
``` create or replace PROCEDURE FCountPrizes (dData IN DATE) IS SELECT COUNT(DECODE(CountGuessed(dData, LiczbyMniejsze, LiczbyWieksze),6,1)) , COUNT(DECODE(CountGuessed(dData, LiczbyMniejsze, LiczbyWieksze),5,1)) , COUNT(DECODE(CountGuessed(dData, LiczbyMniejsze, LiczbyWieksze),4,1)) , COUNT(DECOD...
Oracle / SQL Counting Different values from one Column and storing it in a variable
[ "", "sql", "oracle", "plsql", "" ]
I would like to get the latest record for each server. Here is some example data: ``` TimeGenerated SourceName ComputerName Message 2014-11-22 21:48:30 Windows Update Agent Server1 Update Failed 2014-11-22 21:42:30 Windows Update Agent Server2 Update Failed 2014-11-22 21:45:30 Wind...
``` SELECT * FROM yourtable INNER JOIN ( SELECT MAX(timeGenerated) as maxtime, ComputerName FROM yourtable GROUP BY ComputerName ) AS latest_record ON (yourtable.timeGenerated = maxtime) AND (latest_record.ComputerName = yourtable.ComputerName) ``` Inner query gets the latest timestamp for every computer n...
I you only use a GROUP function, you can only display the columns which are part of that SELECT statement. If you need more data displayed, you need to work with a subquery. For example, if you want to "select \*", you can't just use only a GROUP BY and no subquery. So, it depends what you want to display.
get latest record for each ID
[ "", "mysql", "sql", "groupwise-maximum", "" ]
I have made some SQL code to (what I thought) would update 1 field for only some records. The code I made was: ``` UPDATE Name SET name.STATUS = 'a' WHERE EXISTS (SELECT Name.ID, Name.MEMBER_TYPE, Name.CATEGORY, Name.STATUS, Name.COMPANY_SORT, Name.FULL_N...
Try something like this: ``` UPDATE Name SET name.STATUS = 'a' WHERE EXISTS (SELECT * FROM Activity WHERE Name.ID = Activity.ID AND ACTIVITY_TYPE = 'ELECTIONS' AND PRODUCT_CODE LIKE '%new%' AND TRANSACTION_DATE LIKE '%2014%' AND name.MEMBER_TYPE IN ('mcm', 'MCNM') ) ``` S...
The issue is that your reference to `Name` in the update line and your reference to `Name` under the sub-query are treated as two separate instances, so there is no relation between the update statement and the sub-query. To get around it, you can actually alias your tables within the sub-query itself, and then explic...
Why did this UPDATE change all rows instead of just one row?
[ "", "sql", "" ]
Given the following data: ``` EMPID NAME SALARY DID 1 kevin 32000 2 2 joan 42000 1 3 brian 37000 3 4 larry 82000 5 5 harry 92000 4 6 peter 45000 2 7 peter 68000 3 8 smith 39000 4 9 chen 71000 1 10 kim 46000 5 1...
No need for joining: ``` SELECT name FROM employee GROUP BY name HAVING COUNT(name) = 1 ``` count how many of each name there are, then return only those where there's only one name. e.g. peter has a count of 2 and won't show up, while kim has a count of 1 and WILL show up.
With an inner join that does a count of the number of records for each emp. you can filter the results where count = 1 ``` SELECT T.EMPID, T.NAME, T.SALARY, T.DID FROM employee AS T INNER JOIN (SELECT COUNT(*) AS CNT , NAME FROM employee GROUP BY NAME) AS A ON T.NAME = A.NAME WHERE C...
Query: employees who do not have the same name
[ "", "sql", "" ]
During the creation of a new Tablespace in Oracle Database, the user has to enter the DBF file name that he (or she) want to use. The DBF file is then created in a specific location. The user may also specify a path in which the DBF file should be created. I need to find a way to get the default location of the DBF f...
`DB_CREATE_FILE_DEST` specifies the default location for Oracle-managed datafiles (see [its entry](https://docs.oracle.com/cd/E11882_01/server.112/e40402/initparams053.htm#REFRN10034) in the Database Reference). You can retrieve its value with the following SQL query: ``` select value from v$parameter where name = 'd...
Use this sentence with system user: ``` Select * from dba_data_files ; ``` [![enter image description here](https://i.stack.imgur.com/ms2R0.png)](https://i.stack.imgur.com/ms2R0.png)
How to find the default location in which Oracle DBF files are created?
[ "", "sql", "oracle", "dbf", "" ]
Table - BASECASE(CaseNumber, PatientID) ``` CaseNumber------PatientID S100---------------P201 S101---------------P201 S102---------------P200 S103---------------P199 S104---------------P201 ``` 2nd table ``` Table - CHECKUP(CheckupNumber, CaseNumber) CheckupNumber------CaseNumber C301-------------------S100 C302----...
you need to use `left join` and `group by` ``` select B.caseNumber, ISNULL(count(C.checkupNumber) ,0) from BaseTable B left join Checkup C on B.caseNumber = C.caseNumber where B.patientId ='P201' group by B.caseNumber ```
**Join with Group BY** ``` select BC.Casenumber,isnull(COUNT(BC.Casenumber),0) CNT from BaseCase BC left join CheckUp Ch on BC.CasetNumber=Ch.CaseNumber group by BC.Casenumber ```
SQL Server : Select from two tables with default value 0
[ "", "sql", "sql-server", "select", "default-value", "" ]
I've got a problem with some query. What I need to do is write out all the orders from the customer with the highest number of orders (from one table). So I got this (it works and tell me which customer have the highest number of orders): ``` SELECT custid, COUNT(*) as "Number of orders" FROM sales.orders GROUP BY cu...
try ``` SELECT custid, orderid FROM sales.orders WHERE custid = (SELECT TOP 1 custid FROM sales.orders GROUP BY custid ORDER BY Count(*) DESC) ```
``` SELECT custid, orderid FROM sales.orders WHERE custid IN( SELECT TOP 1 custid FROM sales.orders GROUP BY custid ORDER BY COUNT(*) DESC) ``` This should work (for MySQL), here a SQL fiddle: <http://sqlfiddle.com/#!2/d580a6/1>
using subqueries on example (find all orders from the customer with condition)
[ "", "sql", "sql-server", "sql-server-2008", "subquery", "" ]
I have a table with currency exchange rates: ``` CREATE TABLE ExchangeRates ( ID int IDENTITY, SellingCurrency nvarchar(20), BuyingCurrency nvarchar(20), Rate float, CONSTRAINT PK__ExchangeRates__ID PRIMARY KEY (ID) ) ``` For example, table contains this data: ``` INSERT INTO ExchangeRates VAL...
This problem is an excellent fit for solutions from the [graph theory](https://en.wikipedia.org/wiki/Graph_theory) field (and graph databases like [Neo4j](http://neo4j.com/) for example), but modelling a graph in a relational database isn't that hard and implementing an path finding algorithm like BFS/DFS or Dijkstra (...
When you are sure you can fix it in 2 levels, you could use someting like this: --- ``` select Rate from ExchangeRates where SellingCurrency = 'SEK' and BuyingCurrency = 'EUR' UNION select er1.Rate*er2.Rate as Rate from ExchangeRates er1 left join ExchangeRates er2 on er2.SellingCurrency = er1.BuyingCurrency whe...
Joining multiple tables in SQL Server
[ "", "sql", "sql-server", "" ]
Basically I have a LoginHistory table in SQL . I want to execute a command that will return the count of logins on a certain date. But if a user has logged in multiple times I only want to record it as one log in. So I can see how many logged in on one day and not how many times they logged in on that day. So far I h...
You want to count *distinct* users: ``` select count(distinct username) as TotalUserCountOnTheDay from dbo.LoginHistory where datediff(day,LoginDate, '2014-11-19') = 0; ```
Maybe the *distinct* keyword could help you in this case.
How to get count of number of rows in table that have multiple matching row values?
[ "", "mysql", "sql", "" ]
I have two tables, `Students` and `Course_Registrations` where each student registers several courses. In my `students` table I have his/her degree(MS/BS) but it's missing in the `course_Registrations` table. I've tried the below code to get each student degree program in `course_registrations` but I get this error: ...
You have a problem because some students have multiple rows in `ISB_STUDENTS`. You need to figure out what to do to combine them. In the meantime, I would suggest this: ``` Update ROOT.ISB_COURSE_REGISTRATIONS set degree = (Select MAX(s.degree) from ROOT.ISB_STUDENTS s where IS...
as i understood from your question, you have the following 1. student table that contains degree field 2. course\_registration table that also contains degree field and you want to update it from student table for each student if so, you can try this ``` Update r set r.degree=s.degree from ROOT.ISB_COURSE_REGISTRATI...
Inputing column values in one table from another related table
[ "", "sql", "" ]
I just try to write MS SQL statement to get LAST DATA from database, unfortunately when i add there DESC LIMIT 1 it says wrong syntax despite the fact it looks OK to me. Can somebody with more skill look at it? ``` Select sum(spareparts), month(calculationdate) from cz_axnmrs_calculations where CASE_ID in (sel...
SQL server uses `TOP` instead of `LIMIT` to restrict number of records. Your query becomes: ``` Select top 1 sum(spareparts), month(calculationdate) from cz_axnmrs_calculations where CASE_ID in (select case_id from cz_axnmrs_cases where insurer_memberid = 'MM-O-5B57274F')...
In SQL Server 2012+, Microsoft supports the ANSI standard OFFSET clause. You can write this as: ``` Select sum(spareparts), month(calculationdate) from cz_axnmrs_calculations where CASE_ID in (select case_id from cz_axnmrs_cases where insurer_memberid = 'MM-O-5B57274F') and YEAR(calculationdate)='2014' group by ...
MS SQL last record
[ "", "sql", "sql-server", "" ]
I have two tables `restaurants` and `meals`. Restaurants has ``` `id` `name` `menu` `image` `text` `address` ``` Meals has ``` `meal_id` `meal_name` `meal_image` `meal_weight` `meal_price` `meal_menu` ``` What I think to connect them `meal.restaurant.id`. Is this good approach or is better to make another (third) t...
Create a pivot table e.g. ``` CREATE TABLE meal_restaurant ( meal_id int not null, restaurant_id int not null, primary key (meal_id, restaurant_id), foreign key (meal_id) references meals (meal_id), foreign key (restaurant_id) references restaurants (id) ); ``` Now to select all meals for a specific restau...
**if you think one restaurant has a many meal and one meal has only one restaurant** then you should try restaurants table ``` `id` `name` `menu` `image` `text` `address` ``` Meals table ``` `meal_id` `meal_name` `meal_image` `meal_weight` `meal_price` `meal_menu `restaurant_id` ``` **Or If you...
MySQL relations and query
[ "", "mysql", "sql", "" ]
I have asked a question with the same query earlier but this time the question is different so I am posting another question. Below is the sql stored procedure query. ``` SELECT ROW_NUMBER() OVER (ORDER BY [PostedDate] Desc)AS RowNumber,[Products].[Id], [Name], [Description], [PostedDate], ISNULL(AVG([Rating]....
Using a case can solve this. ``` SELECT ROW_NUMBER() OVER (ORDER BY [PostedDate] Desc)AS RowNumber,[Products].[Id], [Name], [Description], [PostedDate], ISNULL(AVG([Rating].[RatingValue]), 0) AverageRating, SUM(case when (Rating.RatingValue) is null then 0 else 1 END) RatingCount INTO #DealResults1 FRO...
COUNT(expression) evaluates expression for each row in a group and returns the **number of nonnull values**. You may look into using the OVER clause : `COUNT(EmployeeID) OVER (PARTITION BY DepartmentID) AS EmployeesPerDept` See [COUNT (Transact SLQ)](http://msdn.microsoft.com/en-us/library/ms175997.aspx) for more inf...
Don't want to use columns in the COUNT which are NULL
[ "", "sql", "sql-server", "" ]
I want to return 1 if some number already exists in table and 0 otherwise. I tried something but it doesn't work: ``` select case when 100 in (select distinct id from test) then '1' else '0' from test ``` I want something similar to exists function that already exists in PostgreSQL, but instead of `true` and `false`...
**[`EXISTS`](https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS)** yields a `boolean` result. The simple way to achieve what you are asking for is to cast the result to `integer`: ``` SELECT (EXISTS (SELECT FROM test WHERE id = 100))::int; ``` `TRUE` becomes `1`. `FALSE` bec...
If the field you are testing is the Primary Key (or some other unique constraint), then you can simply return the count (which will always be 0 or 1): ``` SELECT count(*) FROM test WHERE id = 100; ```
Return 1 if number exists in table and 0 otherwise
[ "", "sql", "postgresql", "boolean", "exists", "" ]
I want to find new, modified and deleted records in one table (tableA) by comparing it to another table (tableB). Both tables are of the same schema and has a unique ID field. In my situation, tableA is originally the same as tableB but it has been edited by some external organisation and once they have done their edi...
How about: ``` -- DELETED SELECT B.*, 'DELETED' AS 'CHANGE_TYPE' FROM TableB B LEFT JOIN TableA A ON B.PK_ID = A.PK_ID WHERE A.PK_ID IS NULL UNION -- NEW SELECT A.*, 'NEW' AS 'CHANGE_TYPE' FROM TableA A LEFT JOIN TableB B ON B.PK_ID = A.PK_ID WHERE B.PK_ID IS NULL UNION -- MODIFIED SELECT B.*, 'MODIFIED' AS 'CHAN...
Based on what i understood i came up with the following solution. ``` DECLARE @tableA TABLE (ID INT, Number INT) DECLARE @tableB TABLE (ID INT, Number INT) INSERT INTO @tableA VALUES (1,10), (2,20), (3,30), (4,40) INSERT INTO @tableB VALUES (1,11), (2,20), (4,40), (5,50) SELECT *,'...
Find Modified/New/Deleted Records Between Two Tables
[ "", "sql", "sql-server", "t-sql", "" ]
``` SELECT state, business, a.report FROM base WHERE state IN (SELECT a.state FROM heart a join (SELECT CAST(MAX(percent_adults) AS DOUBLE) max1 FROM heart)b on (a.percent_adults=b.max1)); ``` In the above subquery, only one value can be returned i.e a.state from table 'heart'. that value is used in the main query a...
You don't need the subquery to return two values. All you need the subquery for is to provided the unique join value (relying on the odds that two calculated double values will ever be exactly the same). So just do a join and choose the report from that: ``` select b.state, b.business, a.report from base b join ...
Use `exists` instead of `in`: ``` SELECT state, business, a.report FROM base b WHERE EXISTS (SELECT 1 FROM heart h JOIN (SELECT MAX(percent_adults) as max1 FROM heart h2 ) sb ON h.percent_adults = h2.max1 WHERE h.s...
How to return multiple values from a subquery
[ "", "sql", "hive", "" ]
I have a record which has value with leading and space in a column. eg: column value is `' D0019 '` I want to pass this particular column in where clause. ``` select * from my_table where my_column='D0019'; ``` Since the value has space, it doesn't detect from the where clause. How can I select the record even it ...
it's not the normal space you have to remove. It's `Horizontal Tab character` . (Ascii 9). The below `regexp` would strip all the charcters from ASCII range `0-32` , which are associated with the white space symbols. ``` select * from my_table WHERE REGEXP_REPLACE(my_column,'['||chr(1)||'-'||chr(32)||']' ) = 'D...
Seems as simple as (if I get it): ``` select * from TAB where REGEXP_LIKE (COL,'\s*D0019') ``` returns values such ' D0019', 'D0019', ' D0019', ' D0019' ...etc.
Find value having leading and trailing space in DB table column - Oracle
[ "", "sql", "oracle", "" ]
I generated a .sql file by mysqldump command: ``` system "mysqldump -u#{USERNAME} --password=#{PASSPORT} --extended-insert #{DATABASE} #{table_name} > init_#{table_name}.sql" ``` the .sql file looks like this: ``` ..... ..... LOCK TABLES `config_products` WRITE; /*!40000 ALTER TABLE `config_products` DISABLE KEYS */...
You can use `gsub`, and replace opening bracket using a `newline`, a `tab` and the bracket itself. You should either do this before writing or on reading ``` text = "INSERT INTO `config_products` VALUES (1,1000,30,54),(2,2000,30,56),(3,3000,30,51),(4,1000,30,54)...." newtext = text.gsub(/\(/,"\n\t(") #INSERT INTO ...
Check out this gem once, may be helpful to you: `anbt-sql-formatter`
how to modify .sql file with ruby?
[ "", "mysql", "sql", "ruby-on-rails", "ruby", "" ]
I have a set of data as below ``` number quantity 1 4 2 6 3 7 4 9 2 1 1 2 5 4 ``` I need to find the unique value in the column "number" The output should look like this: ``` number quantity 3 7 4 9 5 4 ``` Any help would be appreciat...
One way to go could be to have an aggregate query that counts the number of occurrences for each number use it in a subquery: ``` SELECT number, quantity FROM my_table WHERE number IN (SELECT number FROM my_table GROUP BY number HAVING COUNT(*) = 1) ```
In the inner query get all the distinct numbers, then join with again with the main table to get your expected results. ``` select o.* from mytable o , (select number from mytable group by number) dist where o.number = dist.number ```
Find the unique value in column MS SQL database
[ "", "sql", "sql-server", "" ]
When I use a `DateDiff` in a `SELECT` statement in SQL Server, I get an `int` value back: ``` select DATEDIFF(day,'01/01/2011','15/05/2011') from Table1 ``` Result is : `134` ``` select DATEDIFF(day,'01/01/2011','15/05/2011')/15 from Table1 ``` Result is : `8` ``` select cast(DATEDIFF(day,'01/01/2011','15/05/201...
The problem is that you're using `CAST` after dividing. If you perform the division after the `CAST`, you'll get the answer you want: ``` select cast(DATEDIFF(day,'01/01/2011','15/05/2011') as Decimal(9,2))/15 from Table1 ```
You need to cast your inputs into the division as decimal first: ``` select cast(DATEDIFF(day,'2011-01-01','2011-05-15') as Decimal(9,2))/15.0 ``` Otherwise you are dividing an integer by an integer - you'll get an integer out. If you then cast this to a decimal after the division, you are going to get 8.0.
Issue with DateDiff / Nb in SQL Server
[ "", "sql", "sql-server", "casting", "datediff", "" ]
Please check the tables below for a simplified version of my problem: **Table Boys** ``` BoyId BoyName ... ``` **Table Girls** ``` GirlId GirlName ``` **Table Toys** ``` ToyId ToyName ToyOwnerBoyOrGirl ( The toy could be owned by a boy or a girl) ToyOwnerId ``` I created two constraints: 1) `ToyOwnerId` is a fo...
It looks like a bad design. Why don't have one table for all children and some mark - is it boy or girl? Also I really doubt you need `ToyOwnerBoyOrGirl` field - as it can be easily obtained by join from toys to owners. Consider following scheme: ``` Table Children ID Name Is_Boy Table Toys ID Name Owner_ID ``` In ...
I think you should combine the boys and girls table to one table called children. It would have sex column that would have an M or F. That will simplify things.
A field referencing two tables - Foreign Key Conflict
[ "", "sql", "sql-server", "database-design", "" ]
I'm trying to get the total minutes but it's not working correctly with my left joins. Is there a way to add a column that has the DISTINCT total of minutes for a given MachineDescription? Here is the sqlfiddle: <http://sqlfiddle.com/#!2/7fd99/1> ``` SELECT Work.WorkID , Work.Description , Ma...
Use `Correlated Sub-query` to get the result. Try this. ``` SELECT Work.WorkID, Work.Description, Machine.MachineDescription, NAME.NAME, Work2.RegMin, Work.MINUTES, (SELECT Sum(DISTINCT MINUTES) FROM Work w WHERE w.MachineID = Machine.MachineID) Total_minute...
``` SELECT Work.WorkID , Work.Description , Machine.MachineDescription , Name.NAME , Work2.RegMin , Work.MINUTES , (SELECT (SUM(work2.RegMin) ) FROM work2 left join work on work2.workid = work.workid) - work.minutes AS TotalMinutes FROM Work Work ...
Get DISTINCT Sum of Total by WorkID with LEFT JOINs
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm in coldfusion working with data from an sql table, and using a query of queries to join the sql data to some data from an oracle database. Unfortunately, I need to order them by date, and the oracle table has two columns - DRWR\_DATE which is of type DATE and TIME which is of type VARCHAR2. The two columns put into...
Try this: ``` SELECT to_timestamp( to_char( drwr_date,'dd-mon-yy') ||' '|| time , 'dd-mon-yy hh24:mi:ss' ) FROM your_table ```
Try using `TO_TIMESTAMP` function: ``` SELECT TO_TIMESTAMP('17-JUN-03 16:35:18', 'DD-MON-RR HH24:MI:SS') FROM DUAL; ```
Return an oracle column as timestamp
[ "", "sql", "oracle", "coldfusion", "" ]
How could I get the first business day of the current month? Without create a function, only select. something like that: ``` SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GETDATE())-1), GETDATE()), 101) ``` somebody knows please? Thanks.
A Simple case statement could do it ``` SELECT CASE WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, getdate()), 0)) = 'Saturday' THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2 WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, getdate()), 0)) = 'Sunday' THEN dateadd(mm,...
This will literally give you what you're asking for -- the first business day in a month if we define a business day as "any day that's not a Saturday or a Sunday". But this is is a very narrow definition of "business day" that is not appropriate when taking into account holidays and cultural differences, so it general...
First business day of the current month - SQL Server
[ "", "sql", "sql-server", "" ]
I am running an SQL Query and i want to use `min()` and `DATE()` i tried: ``` and min(DATE(datetime)) = '".date("Y-m-d")."' ``` but that does not work, what should i be using? the full query i have tried is: ``` select min(datetime) as d, ticketnumber from ticket_updates where type = 'update' and min(DATE...
If you want the *earliest* date time, then use a `having` clause: ``` select min(datetime) as d, ticketnumber from ticket_updates where type = 'update' group by ticketnumber having min(DATE(datetime)) = '".date("Y-m-d")."' ``` These seems rather strange as a construct, because the min is going to get the date you ...
There is no need to use the `min` function in your where clause. I've also changed the where to use `between` for readability. ``` select min(datetime) as d, ticketnumber from ticket_updates where type = 'update' and datetime between'".date("Y-m-d 00:00:00")."' and '".date("Y-m-d 23:59:59")....
using min and DATE() in SQL
[ "", "mysql", "sql", "" ]
I have an ETL process which takes values from an input table which is a key value table with each row having a field ID and turning it into a more denormalized table where each row has all the values. Specifically, this is the input table: ``` StudentFieldValues ( FieldId INT NOT NULL, StudentId INT NOT NULL, ...
Think about doing this using conditional aggregation: ``` SELECT s.StudentId, d.Day, max(case when sfv.FieldId = 1 then sfv.Value end) as NumberOfClasses, max(case when sfv.FieldId = 2 then sfv.Value end) as MinutesLateToSchool, ... INTO StudentDays FROM Students s CROSS JOIN Days d LEFT OU...
Yes, this is going to blow up. You have your definitions of "normalized" and "denormalized" backwards. The Field/Value table design is *not* a relational design. It's a variation of the [entity-attribute-value](/questions/tagged/entity-attribute-value "show questions tagged 'entity-attribute-value'") design, which has ...
Creating a denormalized table from a normalized key-value table using 100s of joins
[ "", "sql", "sql-server", "join", "etl", "olap", "" ]
I have a table (ClassEnrolments) which contains student data: ``` StudentId Student Module Status EndDate Credits 12345678 J Bloggs Introduction Pass 2014/09/01 10 12345678 J Bloggs Advanced Pass 2014/06/01 15 23456789 ...
Use `Group By` and Aggregate Function `count` to count the `Module` and filter the data by using `Between operator` to filter the data between particular date range ``` SELECT StudentId, Student, Count(Module) Module, Sum(Credits) Credits FROM tablename WHERE EndDate BETWEEN '2014-01-01' AND '2...
Try this: ``` Set dateformat DMY; Select StudentId, Student, Count(Modules) as ModuleCount from ClassEnrolments Where EndDate >= convert(Datetime, '01-01-2014', 105) and EndDate <= convert(Datetime, '24-11-2014', 105) Group By StudentId, Student ```
SQL to COUNT items associated with individuals
[ "", "sql", "sql-server", "sql-server-2008", "aggregate-functions", "" ]
In my table I want to see a list of unoccupied id numbers in a certain range. For example there are 10 records in my table with id's: "2,3,4,5,10,12,16,18,21,22" and say that I want to see available ones between 1 and 25. So I want to see a list like: 1,6,7,89,11,13,14,15,17,19,20,23,24,25 How should I write my sql ...
Select the numbers form 1 to 25 and show only those that are not in your table ``` select n from ( select rownum n from dual connect by level <= 25) where n not in (select id from table); ```
Let's say you a #numbers table with three numbers - ``` CREATE TABLE #numbers (num INT) INSERT INTO #numbers (num) SELECT 1 UNION SELECT 3 UNION SELECT 6 ``` Now, you can use CTE to generate numbers recursively from 1-25 and deselect those which are in your #numbers table in the WHERE clause - ``` ;WITH n(n) AS ( ...
How can I find unoccupied id numbers in a table?
[ "", "sql", "oracle11g", "" ]
I am trying to implement a function with dates as parameters in PostgreSQL 9.3.5. It should cover all the below conditions and return the results accordingly. ``` select * from tablename where sid is not null and dob >= '11-14-2014' order by dob; -- Only Start Date select * from tablename where sid is not null and ...
This can be ***much simpler still***: You can simplify the expression from @Clodoaldo's currently accepted answer to: ``` SELECT * FROM sampletest WHERE eid IS NOT NULL AND (_sd IS NULL AND _ed IS NULL OR _sd IS NULL AND dob <= _ed OR _ed IS NULL AND dob >= _sd OR dob BETWEEN _sd AND _ed);...
You have to define the function as returning a `set of` sampletest and then [return different query restults](http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html#AEN58217) based on the arguments passed. ``` CREATE FUNCTION test_dob_dates(_sd date, _ed date) RETURNS SETOF sampletest AS $BODY...
Function with dates as params that can be NULL
[ "", "sql", "postgresql", "null", "date-range", "postgresql-9.3", "" ]
I have a table with student ids (sID) and the classes (cCODE) that they're taking. I'm trying to retrieve the student ids of the student(s) who are taking the highest number of classes, so the query needs to allow for the fact that there might be a tie. I know the highest number of occurrences of the same sID will in...
Have you tried combining the two approaches using a subquery? ``` select sID, count(sID) as NumberOfClasses from STUDENT_CLASSES group by sID having count(sID) = (select count(sID) N from STUDENT_CLASSES group by sID order by N desc limit 1) ```
This is a bit of a pain in MySQL with an aggregation query. I would suggest just using variables ``` select sID, NumberOfClasses from (select sID, count(sID) as NumberOfClasses, @max := if(count(sID) > @max, count(sID), @max) as unused from STUDENT_CLASSES cross join (select @max := -1) v...
MySQL; Return most frequent occurrence(s) where there may be more than one
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I need to get the minimum count of data. my current sql is ``` select min(count(*)) from table group by id ; ``` where i expect to get minimum count of variable count(\*). Seems like above query is not allowed. Error ``` aggregate function calls cannot be nested ``` is thrown. Is there a way achieve this using any ...
Many solutions exist as attested by the number of answers here. Interestingly, @ahorse\_with\_no\_name questions the performance of each of them. ### The subquery approach ``` SELECT MIN(count) FROM (SELECT COUNT(*) FROM table GROUP BY id) t; ``` It typically yields the following plan: ``` Aggregate -> HashAggr...
You need to wrap that in a sub-select: ``` select min(cnt) from ( select id, count(*) as cnt from the_table group by id ) t ; ```
PostgreSQL get minimum of count(*)?
[ "", "sql", "postgresql", "" ]
so I've got a question that shouldn't be too hard to answer, but for whatever the reason, I'm just not able to get it. I need to sum the costs of two different tables. I've tried doing one long join, but the numbers themselves come out wrong. The only way I can get the correct numbers is making two queries and summing ...
Try this: ``` SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(p.cost) FROM store s INNER JOIN video v ON s.storeId=v.storeId INNER JOIN (SELECT p.videoid, SUM(p.cost) cost FROM previousrental p GROUP BY p.videoid UNION SELECT r.videoid, SUM(...
One option would be to put the results in a subquery: ``` SELECT storeId, street, city, state, zipcode, SUM(cost) FROM (SELECT s.storeId, s.street, s.city, s.state, s.zipcode, SUM(p.cost) cost FROM store s JOIN video v ON s.storeId = v.storeId JOIN previousrental p ON v.videoid = p.videoid G...
Having Trouble Summing Two Parts of Union in MySQL
[ "", "mysql", "sql", "select", "join", "union", "" ]
I have following tables which are BankDetails and Transactiondetails. Using these two tables, I want to get the current balance of the account name. Tables: ``` Create table Bankdetails ( AccName varchar(50), AccNo int, OpBal numeric(18,2) ) Create table Trandetails ( AccNo int, Amount numeric(18,2), Trantype varcha...
The idea is to generate first the sum for each transaction type, `Debit` and `Credit`. With that, join it to the `Bankdetails` to compute for the current balance. ``` ;with cte as( select AccNo, Credit = sum(case when TranType = 'Credit' then Amount else 0 end), Debit = sum(case when TranTy...
For those that care about performance,here goes; ``` Select B.AccName ,B.AccNo ,(B.OpBal + SUM( Case When TranType = 'Credit' Then Amount Else Amount* -1 End)) CurrBal From Bankdetails B Left Join Trandetails T On B.AccNo = T.AccNo Group By B.AccName, B.AccNo, B.OpBal; ``` **[SQL Fiddle](http://sqlf...
Optimizing the SQL Query for Calculating account balance
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Just thought of learning SQL on my own and started with **[THIS](http://sqlzoo.net/wiki/SELECT_from_Nobel_Tutorial)** I was practicing some tutorial and got stuck in one basic query. After **trying a lot** I could not get it running. Question is: in which years was the Physics prize awarded but no Chemistry prize. ...
So close! You just needed `yr` and `IN`: ``` SELECT yr FROM nobel WHERE subject ='Physics' AND yr NOT IN (Select yr from nobel where subject = 'Chemistry') ``` You could also do this with an exclusion join: ``` SELECT yr FROM nobel n1 LEFT JOIN nobel n2 ON n1.yr = n2.yr AND n2.subject = 'Chemistry' WHERE n1.sub...
``` SELECT yr FROM nobel WHERE subject ='Physics' AND yr NOT IN (Select yr from nobel where subject = 'Chemistry') ```
Simple SELECT SQL query not working
[ "", "sql", "sql-server", "" ]
I am trying to declare local variable like: ``` DECLARE @thresholdDate DATETIME = '2014-11-30' ``` And I am getting error: > Cannot assign a default value to a local variable. As per [documentation](http://msdn.microsoft.com/en-us/library/ms188927.aspx): ``` DECLARE @find varchar(30); /* Also allowed: DECLARE @f...
Prior to SQL Server 2008, assigning a default value (or initial value) to a local variable is not allowed; otherwise this error message will be encountered. **Solution 1:** (Use `SET`) ``` DECLARE @thresholdDate DATETIME set @thresholdDate = '2014-11-30' ``` For more details about the error : <http://www.sql-server...
You will hit this error > Cannot assign a default value to a local variable in case you are running SQL Server 2005 or earlier, and you try to declare a variable and assign it a value in one statement. Something like - ``` DECLARE @Var Varchar(15) = 'Test' ``` > Message 139, Level 15, State 1, Line 0 > Cannot as...
Cannot assign a default value to a local variable in SQL
[ "", "sql", "sql-server", "sql-server-2005", "default-value", "declare", "" ]
I'm using mysql and I've got a table similar to this one: ``` id | user | task | time | checkout ----+-------+------+-----------------------+--------- 1 | 1 | 1 | 2014-11-25 17:00:00 | 0 2 | 2 | 2 | 2014-11-25 17:00:00 | 0 3 | 1 | 1 | 2014-11-25 18:00:00 | 1 4 | 1 ...
As all comments tell you, your current table structure is not ideal. However it's still prossible to pair checkins with checkouts. This is a SQL server implementation but i am sure you can translate it to MySql: ``` SELECT id , user_id , task , minutes_per_each_task_instance = DATEDIFF(minute, time, ( ...
You can determine with a ranking method what are the matching check in/ check out records, and calculate time differences between them In my example new\_table is the name of your table ``` SELECT n.user, n.task,n.time, n.checkout , CASE WHEN @prev_user = n.user AND @prev_task = n.ta...
How can I make an SQL query that returns time differences between checkins and checkouts?
[ "", "mysql", "sql", "" ]
I have a MySQL table data that looks like below ``` +--------------------------+ | period | +--------------------------+ | 2014-11-27 to 2014-11-28 | | 2014-11-09 to 2014-11-09 | | 2014-11-07 to 2014-11-07 | | 2014-11-06 to 2014-11-06 | | 2014-11-04 to 2014-11-04 | | 2014-11-02 to 2014-11-02 | | 2014...
i think below is right one, ``` select period from mysql_common.leave_details where (period like '%-11-%' or period like '%-10-%' or period like '%-09-%') order by period desc; ```
FIrst thing you should really normalize your table and store the dates with mysql native date data-types and make sure you store them in two columns `start_date` and `end_date`. This will make your life easy. Now coming back to the current situation there is a way you can do it, first extract the start and end date fr...
MySQL, split column data and get result by splitted data
[ "", "mysql", "sql", "date", "select", "between", "" ]
In MySQL, I have a two tables as below : ``` ClientTable clientID clientName 1 Client A 2 Client B 3 Client C 4 Client D 5 Client E 6 ...
Why all the subqueries? ``` select ct.clientID, ct.clientName,max(nt.noteDate) latestNoteDate from ClientTable ct left outer join NotesTable nt on ct.clientID = nt.clientID group by ct.clientID, ct.clientName ```
You can use an `outer join` with a subquery: ``` select c.clientid, c.clientname, n.latestnotedate from client c left join ( select clientId, max(noteDate) latestnotedate from notes group by clientId ) n on c.clientId = n.clientId ``` This assumes the `max(noteDate)` is the **latest** note ...
SQL SELECT statement MAX date and table joins
[ "", "mysql", "sql", "select", "left-join", "" ]
I want to get the missing protocol Numbers from this list for each section I have my list ``` ProtocolNumber Section -------------------------------- 14A1000014 | A1 14A1000015 | A1 14A1000018 | A1 14A1000019 | A1 14A2000014 | A2 14A2000015 | A2 14A2000019...
With the assumption that you are trying to generate a list of missing protocol numbers between the minimum and maximum range currently existing for that section, I'd suggest the following: ``` /*Sample Data*/ CREATE TABLE #tmp (ProtocolNumber VARCHAR(20), Section VARCHAR(2)) INSERT INTO #tmp (ProtocolNumber, Section) ...
Does it have to be a one line select statment? How about writing a stored procedure or Table-Valued function that using cursor iterates through your table and creates missing records, which the function returns Implemenation would also need to check for max protocol number for each give section so that you only creat...
Get the missing numbers for each section
[ "", "sql", "sql-server", "t-sql", "" ]
I want to repeat first row first column value in every row in a particular column like a group. Please let me know how i will do it? ``` Table Id - Title 1 - ABC1 2 - ABC2 3 - ABC3 4 - ABC4 5 - ABC5 ``` I want result like this in a simple select query, Please dont use variable for it me...
This query will be helpful to get expected result. ``` SELECT Id, Title, (SELECT TOP 1 Id FROm Table ORDER BY ID) AS [Group] FROM Table ```
USE THE QUERY: (ORDER BY ID ASC will make sure that the first ID will selected always even if there is a change of order in ID.) ``` SELECT Id, Title, (SELECT TOP 1 ID FROM Table ORDER BY ID ASC) AS [Group] FROM Table ```
How to make a group with multiple column
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "sql-server-2012", "" ]
I'm trying to select persons who have an account at all branches of the city. (With a SQL query) ``` SELECT A.customId FROM accountholder as A WHERE NOT EXISTS ( (SELECT name FROM branch WHERE city='LA') EXCEPT (SELECT C.branch FROM accountholde...
As others have stated, MySQL does not support the `EXCEPT` operation. You will have to rewrite your query. You appear to be querying accountholders if there is no other branch in LA besides those branches at which the accountholder's accounts are held. Here's a rough guess: ``` SELECT A.customId FROM accountholder A...
MySQL does not use `EXCEPT`. Use [`NOT IN`](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in). ``` SELECT A.customId FROM accountholder as A WHERE branch NOT IN ( (SELECT name FROM branch WHERE city='LA') AND branch NOT IN (SELECT C.branch FROM accountholder AS B, account AS C WHERE...
SQL Error in Syntax near except
[ "", "mysql", "sql", "database", "mysql-error-1064", "" ]
I am trying to calculate an average number from three columns but only include the column in the calculation if column is not null and is bigger than 0; for example the average usually is ``` (column1 + column2 + column3) / 3 ``` but if column3 is null or 0 then it will be ``` (column1 + column2 + column3) / 2 or (...
I'm fixing the rest of the query to use table aliases and proper `join` syntax. But the `case` statements are what you really need: ``` SELECT m.title, m.imdbrating, m.metacritic, t.rating, ((case when imdbrating > 0 then imdbrating else 0 end) + (case when metacritic > 0 then metacritic else 0 e...
Try this: ``` SELECT (IF Column3 IS NULL OR Column3=0, AVG(Column1+Column2), Avg(Column1+Column2+ Column3)) as Result FROM Table ``` **EDIT:** If any of the tree columns can be nullm, try this: ``` SELECT AVG(IF(Column1 IS NULL,0,Column1)+IF(Column2 IS NULL,0,Column2)+IF(Column3 IS NULL,0,Column3)) as Result FROM T...
Calculating an average number from three columns
[ "", "mysql", "sql", "" ]
A table Jobs which have 2 column JobId, City when we save job a job location may be multiple city like below ``` ----------------------------- JobId City ------------------------------- 1 New York 2 New York , Ohio , Virginia 3 New York , Virginia ```...
``` SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(all_city, ',', num), ',', -1) AS one_city, COUNT(*) AS cnt FROM ( SELECT GROUP_CONCAT(city separator ',') AS all_city, LENGTH(GROUP_CONCAT(citySEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(citySEPARATOR ','), ',', '')) + 1 AS count_city FROM table_name ) t JOI...
Your database is poorly designed and you are going to have a lot of trouble down the line. Using the current structure you can get the count using the `find_in_set` function but that you should avoid . Your table is as ``` create table test (jobid int ,city varchar(100)); insert into test values (1,'New York'), (2,...
Get Count of different values in comma separated row in mysql
[ "", "mysql", "sql", "string-aggregation", "" ]
I've tried this query, but got the wrong result... I looked at many references but I could not find the answer. ``` SELECT a.id, SUM(b1.amount) as section1, SUM(ABS(b2.amount)) as section2 FROM parent_table as a INNER JOIN child_table as b1 ON a.id=b1.parent_id INNER JOIN child_table as b2 ON a.id=b2.parent_id WHERE b...
You have to use `CASE`, like this: ``` SELECT a.id, a.customer_namem, SUM(CASE WHEN ch_key = "deposit" THEN ch_value ELSE 0 END) as deposit, SUM(CASE WHEN ch_key = "withdraw" THEN ch_value ELSE 0 END) as withdraw, a.date_register FROM parent_table as a INNER JOIN child_table as b ON a.id=b.parent_id GROUP BY...
## Query ``` SELECT a.id, a.customer_name, COALESCE(SUM(CASE WHEN b.ch_key='deposit' THEN b.ch_value END),0) AS deposit, COALESCE(SUM(CASE WHEN b.ch_key='withdraw' THEN b.ch_value END),0) AS withdraw, a.date_register FROM parent_table a JOIN child_table b ON a.id=b.parent_id GROUP BY a.id; ``` **Output** ``` +----+-...
How do I sum the child table?
[ "", "mysql", "sql", "select", "group-by", "sum", "" ]
I wrote a sql query and my sample query like below: ``` select value1, value2, value3, ( select CAST(amount1 as decimal(17,2)) from table1 where something...) - select CAST(amount2 as decimal(17,2)) from table1 where something...) ) as 'Total Purchase' from t...
There are lot of things wrong in your sql. try this ``` SELECT value1, value2, value3, (SELECT Cast(amount1 AS DECIMAL(17, 2)) FROM table1 where something...) - (SELECT Cast(amount2 AS DECIMAL(17, 2)) FROM table1 where something...) AS 'Total Purchase' FROM ...
Just a syntax error, i believe it should be like this : ``` ( (select CAST(amount1 as decimal(17,2)) from table1 where something...) - (select CAST(amount2 as decimal(17,2)) from table1 where something...) ) as total purchase ```
Using Extraction in SQL Server
[ "", "sql", "sql-server", "" ]
I am trying to create an SQL query for an ASP NET drop down list using two tables and a session variable. I want to retrieve the all values from table 1 which correspond to a matching ids in table 2, where table 2 is filtered by an external variable. As it is clear I do not know how to word this question, here is a s...
I think this should do the trick if I understand the question above ``` select * from Cars c inner join Colours cl on c.colourID = cl.ID where cl.Name = @ExternalVar ```
``` SELECT Cars.* FROM Colours INNER JOIN Cars ON Colours.ID = Cars.ColourID WHERE Colours.Name = @Variable ```
SQL Query - SELECT WHERE Table1.ID = Table2.ID AND Table2.Var = @Var
[ "", "sql", "asp.net", "webforms", "" ]
I have the following query: ``` SELECT u.user_id, u.username, u.email hp.homepage_id FROM table_u u LEFT JOIN table_hp hp ON (u.user_id = hp.user_id) WHERE u.blocked = 'N' AND u.email LIKE 'someemailaddress' ``` I am joining on...
The point was how some data was stored in the database... Seems that in an old (buggy) version of the application data was stored without decent trimming etc. The issue was the field was stored in with a whitespace... Stupid... should/must had checked the actual data that was stored...
Put the '%' before and after in the LIKE clause - see below ``` SELECT u.user_id, u.username, u.email hp.homepage_id FROM table_u u LEFT JOIN table_hp hp ON (u.user_id = hp.user_id) WHERE u.blocked = 'N' AND u.email LIKE '%somee...
SQL Query shows no result with left join
[ "", "mysql", "sql", "left-join", "resultset", "" ]
``` with cte as ( select '2014-03-10 08:00:00' as Dates union all select '2014-05-11 14:00:00' ) select * from cte join someTable on 1=1 OPTION (MAXRECURSION 0) ``` The here above SQL is outputing like a charm all hours between two dates and a field retrieved from a join with another table: ``` 2014-03-...
You cannot specify the `MAXRECURSION` option inside a view. From <http://benchmarkitconsulting.com/colin-stasiuk/2010/04/12/maxrecursion-with-a-cte-in-a-view/>: In order to make use of the MAXRECURSION option you need to first create your view without using the MAXRECURSION option: ``` USE AdventureWorks; GO CREATE ...
If you have more than 100 expected results, and want to avoid having to add the OPTION statement to your VIEW calls, try executing the CTE query - including the OPTION clause - in an OPENQUERY statement within your VIEW. In your example, it would probably look something like this: ``` USE AdventureWorks; GO CREATE V...
MS SQL Server - How to create a view from a CTE?
[ "", "sql", "sql-server", "t-sql", "" ]
select max(case when field\_number = 7 then value end) value from wp\_rg\_lead\_detail group by lead\_id having max(case when field\_number = 21 then value end) > curdate()I already tried my best reading documentation and searching on Google but i can't figure it out.. ![](https://i.stack.imgur.com/gAxg5.png) I need ...
You could use `group by` with `max` and `case`. I'm assuming the unique group is `lead_id` and `form_id`: ``` select max(case when field_number = 7 then value end) value from wp_rg_lead_detail group by lead_id, form_id having max(case when field_number = 19 then value end) = 1 and max(case when field_number = 21 ...
This should do the trick ``` SELECT o.value FROM wp_rg_lead_detail o JOIN wp_rg_lead_detail t1 ON t1.lead_id = o.lead_id AND t1.form_id = o.form_id AND t1.field_number = 19 AND t1.value = 1 JOIN wp_rg_lead_detail t2 ON t2.lead_id = o.lead_id AND t2.form_id = o.form_Id AND t2.field_number = ...
Need help building sql query
[ "", "sql", "" ]