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 table which contains information about reports being accessed along with the Date.I need to group reports being accessed according to a date range and count them.
I'm using T-SQL
Table
```
EventId ReportId Date
60 4 11/24/2015
59 11 11/23/2015
58 6 11/22... | Assuming you have values for all the dates, then you can calculate the difference in days between each date and the maximum (or minimum) date. Then divide this by three and use that for aggregation:
```
select min(date), max(date), count(*) as ReportsAccessed
from (select t.*, max(date) over () as maxd
from tabl... | Those 2 blocks are simply for added clarity on what parameters you'd have to change
```
DECLARE @t as TABLE(
id int identity(1,1),
reportId int,
dateAccess date)
DECLARE @NumberOfDays int=3;
```
And here comes the actual select
```
Select StartDate, EndDate, COUNT(reportId) from
(
select *,
DATEADD(da... | Group by contiguous dates and Count | [
"",
"sql",
"t-sql",
""
] |
I'm working on AdventureWorks2014 Database and need to retrieve client's ID's for those clients who placed orders in BOTH years 2011 and 2014. So far I have this query:
```
SELECT CustomerID, SalesOrderID, YEAR(OrderDate) AS 'Year'
FROM Sales.SalesOrderHeader
WHERE YEAR(OrderDate) IN (2011,2014)
HAVING COUNT(YEAR(Ord... | Try this, it will only return matching Customer ID's if they have purchased in both 2011 and 2014
```
SELECT S.CustomerID, S.SalesOrderID, YEAR(S.OrderDate) AS 'Year'
FROM Sales.SalesOrderHeader S
WHERE S.CustomerId IN (
SELECT DISTINCT S1.CustomerId FROM Sales.SalesOrderHeader S1
INNER JOIN Sales.S... | You have to use GROUP BY CustomerID and DISTINCT keywords in the COUNT to count only one for 2014 and one for 2011 (in case if there were many orders in each year):
```
SELECT CustomerID
FROM Sales.SalesOrderHeader
WHERE YEAR(OrderDate) IN (2011,2014)
GROUP BY CustomerID
HAVING COUNT(DISTINCT YEAR(OrderDate))=2;
```... | How to write SQL query for matching two conditions in the same column? | [
"",
"sql",
"sql-server",
""
] |
I have a MySql query, which is given below:
```
UPDATE signup SET lastname='Lastname', password='123'
WHERE firstname='Firstname';
```
I am using MySql Workbench to execute the query.
But it's not updating the row and shows this error:
> You are using safe update mode and you tried to update a table without
> a WHE... | In mysql workbench the safe mode is enabled by default, so if your `WHERE` clause doesn't have a key it will prevent running the query. Try disabling that using these steps -
`Edit` > `Preferences` > `Sql Editor` > `uncheck the "Safe Updates"`
**Note** - try reconnecting the server (`Query` > `Reconnect to Server`) a... | `MySQL` helps you particularly avoid updating/deleting multiple rows in one shot. To achieve that, it doesn't allow you to run `UPDATE` queries without passing the ID parameter. This is called as the `SAFE UPDATES` mode.
As said by @ManojSalvi, you can set it permanently from the settings.
In case you want to tempora... | Update query not working in mysql workbench | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
Is there a way to select rpd.name using a different WHERE clause if the previous one returns an empty string?
I've looked into CASE, but I'm not sure how would I go about using it.
## table replacement\_part
**part\_id** **href**
1 url\_1
2 url\_2
3 url\_3
## table replacement\_part\_description
**part\_i... | One way is to join the rpd table twice, moving the where clause on the ON condition, and then use COALESCE:
```
SELECT
...,
COALESCE(rpd1.name, rpd2.name) AS name
FROM
replacement_part rp LEFT JOIN replacement_part_description rpd1
ON rp.part_id = rpd1.part_id AND rpd1.language=a
LEFT JOIN replacement_part_d... | This ?
```
SELECT *
FROM replacement_part AS rp
LEFT JOIN replacement_part_description AS rpd
ON (rp.part_id = rpd.part_id)
WHERE
(
language_id = :id
AND (rpd.name = '' OR rpd.name IS NULL)
)
OR language_id = b
``` | If the column is empty, select the same column using different where clause | [
"",
"mysql",
"sql",
""
] |
I want a query that will display rows of those **COMPANIES** who are giving **theft cover** and **key loss** Having status is **yes**
See the Sample Data below :
```
addon status amt1 amt2 company
theft cover yes 7 7 comp1
key loss yes 2 2 comp1
theft co... | Use Group BY clause to group your records by company and addon and sum all your amounts (only if you have multiple records which is not in your sample data) like:
```
SELECT addon, status, SUM(amt1), SUM(amt2), company
FROM test
WHERE (addon = 'theft cover' OR
addon = 'key loss') AND ... | SELECT addon, status, amt1, amt2, company
FROM test
WHERE addon in('theft cover', 'key loss') AND (status = 'yes')
GROUP BY company, addon, amt1, amt2, company
if you find any duplicates it can be achieve using above query. | SQL Query to find Records companywise | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I can get nearly what I require, from a sql query but not quite and I would appreciate some help.
I have the following three tables:
```
people
+----+-------------------------+
| id | email |
+----+-------------------------+
| 1 | joe_soap@hotmail.com |
| 2 | john_doe@hotmail.com |
| 3 | f... | Use `HAVING` clause instead:
```
SELECT people.id, people.email,
GROUP_CONCAT(DISTINCT jobs.description
ORDER By jobs.description DESC SEPARATOR ', ')
FROM jobs
INNER JOIN people_jobs On people_jobs.job_id = jobs.id
INNER JOIN people On people.id = people_jobs.person_id
GROUP BY people.id
HAVING COUNT(... | You can wrap your first query with subquery and use `FIND_IN_SET`:
```
SELECT *
FROM (
SELECT people.id, people.email,
GROUP_CONCAT(DISTINCT jobs.description
ORDER By jobs.description DESC SEPARATOR ', ') AS jobs
FROM jobs
JOIN people_jobs On people_jobs.job_id = jobs.id
JOIN people On people.i... | mySQL GROUP_CONCAT - Query | [
"",
"mysql",
"sql",
"database",
""
] |
I have two tables (`delta` and `aa`) of flight data, and I am trying to create a new table that would be a subset of `delta`. This subset would only contain the rows in delta that share the same `origin_airport_id` and `dest_airport_id` as in `aa`.
`aa` has 89,940 rows and `delta` has 245,052.
I used:
```
CREATE TABL... | You should use `WHERE EXISTS` rather than `JOIN`:
```
SELECT *
FROM delta d
WHERE EXISTS (
SELECT 1
FROM aa
WHERE aa.origin_airport_id = d.origin_airport_id
AND aa.dest_airport_id = d.dest_airport_id);
``` | What about something like this?
```
SELECT delta.*
FROM delta
inner join aa on aa.origin_airport_id = delta.origin_airport_id
and aa.dest_airport_id = delta.dest_airport_id
``` | How to create a subset of a table | [
"",
"sql",
"postgresql",
"postgresql-9.3",
""
] |
I want to replace all the `dots` **before** `@` in an email with `empty string` in oracle query
like:
```
anurag.mart@hotmail.com >> anuragmart@hotmail.com
``` | * Instr - To identify the position(`@`)
* Substr - To extract data between start(`1`) and end(`@`) position
* Replace - To replace `.` with `''`
* || - To concatenate two strings
Try this
```
SELECT Replace(Substr('anurag.mart@hotmail.com', 1,
Instr('anurag.mart@hotmail.com', '@', 1)), '.', '')... | The easiest way is to use **REGEXP\_REPLACE** to identify the pattern and replace it with required pattern.
```
regexp_replace('anurag.mart@hotmail.com', '(\w+)\.(\w+)(@+)', '\1\2\3')
```
For example,
```
SQL> SELECT 'anurag.mart@hotmail.com' email_id,
2 regexp_replace('anurag.mart@hotmail.com', '(\w+)\.(\w+)(@+)... | How to replace all the dots before @ in an email with empty string in Oracle SQL? | [
"",
"sql",
"oracle",
""
] |
I am using SQL Server 2008. And I am trying to insert a string into a table but only part of the string is inserted. I have checked whether it is a SQL injection risk. How to solve or avoid this problem?
```
insert into tble (col1, col2, col3)
values (23, 34, "out of 8 works, 5 works are completed");
```
Only `Out o... | The double quotes will only work if QUOTED\_IDENTIFIERS is turned off, if you are worried about SQL injection then don't pass a string on the INSERT - parameterise it from the application. The string could be truncated because the col3 is not defined long enough - check that also. | Try this..
```
insert into table(col1,col2,col3) values (23,34,'out of 8 works, 5 works are completed');
``` | Unable to insert this string into a column. Only part of the string Is inserted | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-injection",
"code-injection",
""
] |
The logic is pretty simple, I have first, last name columns and I wish to concatenate them and make a search based on the concatenated column fullName.
My query does not work since I cannot do where on a alias:
```
SELECT CONCAT(profile_firstname, ' ', profile_lastname) AS fullName FROM Profiles WHERE fullName = '%a%... | You can use a `having` clause, for example (*in your specific case*):
```
having fullName = '%a%';
``` | This may be more what you're looking for......
```
SELECT Sub_Query.*
FROM
(
SELECT CONCAT(profile_firstname, ' ', profile_lastname) AS fullName FROM Profiles
) Sub_Query
WHERE
Sub_Query.fullName = '%a%';
```
But you might want to consider a View which would have fullName and run your queries against that........ | Alternative to WHERE on alias | [
"",
"mysql",
"sql",
""
] |
In Oracle, just using the `ORDER BY` does not sort version numbers.
My `Version_Number` field is declared as a `VARCHAR` and I cannot change it.
For Example: The following versions :
```
1.20
1.9
1.18
1.13
1.5
1.11
2.0
1.8
1.3
1.2
1.1
1.0
1.10
```
**should be sorted as**
```
2.0
1.2... | This is one way to do it. First order by the number before `.` and then by the numbers after `.`
```
select version_number
from mytable
order by substr(version_number, 1, instr(version_number,'.')-1) desc
,length(substr(version_number, instr(version_number,'.')+1)) desc
,substr(version_number, instr(... | This SQL supports your input data plus any included Revision or Build digits.
```
with
inputs as (select '1.20' as version_number from dual union all
select '1.9' as version_number from dual union all
select '1.18' as version_number from dual union all
... | Oracle SQL to Sort Version Numbers | [
"",
"sql",
"oracle",
"sorting",
"rdbms",
"version-sort",
""
] |
```
SQL SERVER:
Select tblActivity.RoomID, tblActivity.Time , tblRoom.RoomType
from tblActivity
Inner Join tblRoom
On tblRoom.ID = tblActivity.RoomID
Where tblActivity.Time Between 10 And 11
And tblActivity.RoomID is NULL
GROUP BY tblActivity.RoomID , tblRoom.RoomType
```
Sorry the questions title is pretty vague. ... | For your logic, you would seem to want `not exists`:
```
Select r.*
from tblRoom r
where not exists (select 1
from tblActivity a
where r.ID = a.RoomID and
a.Time >= 10 and
a.Time <= 11
);
```
When using date/times, it... | `Where tblActivity.Time Between 10 And 11` is identical to writing :
```
Where tblActivity.Time >= 10 And tblActivity.Time <= 11
```
Note that the between in SQL Server is `inclusive`, meaning the end (11) is included in the answer... which is overall considered a bad practice for many good reasons. So be aware it mi... | How to properly use the Between statement | [
"",
"sql",
"sql-server",
""
] |
I need to create a view in `Oracle 11g` that would take these tables:
**employees**
```
FirstName | LastName | EmployeeID
-----------------------------------
joe | shmo | 1
bob | moll | 2
```
**salesData**
```
Employee ID | commission on sale
----------------------------------
1... | This should get you what you need
Create someviewname as view
```
Select EmployeeID, sum (commision)
from employees
left outer join salesData on salesData.EmployeeID = employees.EmployeeID
Group by EmployeeID, commision
order by commission desc
``` | ```
SELECT employeeID
FROM
(SELECT employeeID,
SUM(commission)
FROM sales
GROUP BY employeeID
ORDER BY SUM(commission)
)
WHERE rownum = 1
```
Not sure why you want a view of that, but hopefully, you can figure that out. | How to create a oracle view of the max sum of a sum of values of a column based on the values of another | [
"",
"sql",
"oracle",
"view",
"sum",
""
] |
I tried these queries in our application. Each returned different result sets for me.
Query Set 1
```
SELECT *
FROM TABLE1 T1
LEFT OUTER JOIN TABLE2 T2 ON (T1.ID = T2.ID
AND T1.STATUS = 'A'
AND T2.STATUS = 'A')
INNER JOIN TABLE3 T3 ON (T2.ID = T3.ID)
WHERE ... | On the first
```
SELECT *
FROM TABLE1 T1
LEFT OUTER JOIN TABLE2 T2 ON (T1.ID = T2.ID
AND T1.STATUS = 'A'
AND T2.STATUS = 'A')
INNER JOIN TABLE3 T3 ON (T2.ID = T3.ID)
WHERE T3.STATUS = 'A'
```
AND T1.STATUS = 'A' has zero effect
It is a left join - you are... | You are putting a filter on the right table of a left join, creating an inner join. Your first query will return less results, whilst your second will have NULLS against non matching rows on the right table. This link helped me to understand joins much better, as I really struggled for a long time to grasp the concept.... | Data Difference Between Where Clause and AND Clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
How can i select only distinct user id's ONLY having ACCESS\_COLUMN\_ID value 1 even though they may also have ACCESS\_COLUMN\_ID value 2 as well.
Here is my query which returns 1 and 2:
```
SELECT DISTINCT(USER_ID) FROM USER_ACCESS WHERE ACCESS_COLUMN_ID = 1
```
The result returned contains userid who have `ACCESS_... | You could use `HAVING`:
```
SELECT USER_ID
FROM USER_ACCESS
GROUP BY USER_ID
HAVING MIN(ACCESS_COLUMN_ID) = 1
AND MAX(ACCESS_COLUMN_ID) = 1
```
This query will get all `user_id`, but only unique ones because of the `group by` clause. Then it will take the minimum and maximum `access_column_id` it f... | You can use `NOT IN` to filter out the ones with `ACCESS_COLUMN_ID = 2`
```
SELECT DISTINCT(USER_ID) FROM USER_ACCESS WHERE ACCESS_COLUMN_ID = 1 and
USER_ID NOT IN (
SELECT DISCTINCT (USER_ID) FROM USER_ACCESS WHERE ACCESS_COLUMN_ID = 2
)
``` | Only select unique record for a condition in sql | [
"",
"sql",
"sql-server",
"distinct",
""
] |
I am trying to disable a table's constraint with an ALTER statement using BCP commands. My code is as follows:
```
SET @disableConstraints = 'SQLCMD -E -S server-Name -d '+@databaseName+' -Q "EXEC sp_MSforeachtable @command1 = ALTER TABLE '+@schemaName+'.'+@tableName+' NOCHECK CONSTRAINT ALL;" >> Z:\Log\ErrorLog.txt'
... | Needed two single quotes at the start of ALTER and the end of ALL
```
SET @disableConstraints = 'SQLCMD -E -S server-Name -d '+@databaseName+' -Q "EXEC sp_MSforeachtable @command1 = ''ALTER TABLE '+@schemaName+'.'+@tableName+' NOCHECK CONSTRAINT ALL'';" >> Z:\Log\ErrorLog.txt'
``` | You miss the double quote before alter
```
SET @disableConstraints = 'SQLCMD -E -S server-Name -d ' + @databaseName + ' -Q EXEC sp_MSforeachtable @command1 = "ALTER TABLE ' + @schemaName + '.' + @tableName + ' NOCHECK CONSTRAINT ALL;" >> Z:\Log\ErrorLog.txt'
``` | Incorrect syntax near ALTER NOCHECK CONSTRAINT - SQL Server 2008 | [
"",
"sql",
"sql-server-2008",
"bcp",
"alter",
""
] |
I'm trying to write one of my first SQL queries, but it seems like the syntax is wrong. I've gone over it for the past two hours trying to change things back and forth, but it still seems to be wrong somewhere on line 3. Could someone help me?
```
SELECT prodotti.ID_Prodotto, prodotti.ID_Ditta,
prodotti.Nome, p... | You need to back-tick the table name with a space in it, if that is a table name with a space in it.
Otherwise, yet another table, and you need a comma ?
```
SELECT prodotti.ID_Prodotto, prodotti.ID_Ditta, prodotti.Nome, prodotti.Descrizione,
prodotti.ID_Tipologia, prodotti.Immagine, cp.Nome, valori.Valore
FROM prod... | Your SQL have a typpo at:
```
campi tipologia AS cp,
```
remove spaces between 2 tables; | Wrong syntax in SQL? | [
"",
"mysql",
"sql",
""
] |
I'm trying to extract some data were the Event column is distinct but I specifically want only rows that contain the highest number from the Value column, I'm thinking it's some mis-mash of using DISTINCT and GROUP BY but my sql knowledge is limited at the moment, any help would be great
[![enter image description her... | Try this out:
```
SELECT [EVENT]
,MAX([Value])
FROM [MyTable]
GROUP BY [EVENT]
``` | The easiest way to do this is using either a subquery or `row_number()`:
```
select event, value
from (select t.*, row_number() over (partition by event order by value desc) as seqnum
from mytable t
) t
where seqnum = 1;
```
or:
```
select t.*
from mytable t
where t.value = (select max(t2.value) from myta... | SQL selecting specific DISTINCT rows | [
"",
"sql",
""
] |
I have two tables and i need to compare data and update one table records. Please let me know how this can be done, i am trying to not use merge. This is the scenario
**Proj1 Table**
This is the first table where data needs to be synchronized
```
ID Text
1 R1
2 R2
3 R3
```
**Proj2 Table**
This is the table wh... | If you really can't use `MERGE`, you can simply split it into an update and an insert query :
```
INSERT INTO @Proj2(Text, Active)
SELECT Text,1 FROM @Proj1 p1
WHERE NOT EXISTS(
SELECT *
FROM @Proj2 p2
WHERE p2.Text = p1.Text
);
UPDATE
p2
SET
p2.Active = CASE WHEN p1.id is null THEN 0 ELSE 1 END
... | ```
merge [Proj2Table] target
using ( select [id], [text] from [Proj1Table] ) source ([id], [text] )
on target.[id] = source.[id]
when not matched by source
then update
set target.[Active] = 0
when not matched by target
then insert
([id], [text] )
values( source.[id], source.[text] )
``` | Compare data between two tables and update one table data | [
"",
"sql",
"sql-server",
""
] |
I have two different tables: one called XY and the other called XZ
In each table I have a column named "id" and I want to compare those columns and to see which one of the "id" values in table XY is also available in XZ and which isn't available | To get the id's that are in XY and not in XZ (The inner query gives the id's present in both XY and XZ)
```
SELECT XY.`id`
FROM XY
WHERE `id` NOT IN(
SELECT XY.`id`
FROM XY
JOIN XZ ON XY.`id`=XZ.`id`);
``` | Is a simplle inner join
```
select * from table XY
inner join XZ on (XY.id = XZ.id);
``` | mysql compare columns | [
"",
"mysql",
"sql",
"database",
""
] |
Please help me to debug the error for below stored Procedure.
Whenevere i tried to execute the sp i am getting error as
(142 row(s) affected)
Msg 2714, Level 16, State 6, Line 16
There is already an object named 'AOP\_Monthly\_GrowthRate\_Acquisition' in the database.
```
if exists (select * from INFORMATION_SCHEMA.T... | ```
USE BudgetWorld_temp
GO
IF OBJECT_ID('dbo.AOP_Monthly_GrowthRate_Acquisition', 'U') IS NOT NULL
DROP TABLE dbo.AOP_Monthly_GrowthRate_Acquisition
GO
IF OBJECT_ID('tempdb.dbo.#TEMP3') IS NOT NULL
DROP TABLE #TEMP3
GO
SELECT
a.[Year],
a.[Month],
a.SALES_MANAGER_CODE,
a.SALES_GROUP,
... | SELECT
FROM
INTO
Creates a table, which it cannot do if it already exits (perhaps from a previous execution).
You could swap to a temp table (prefix table name with #). Or you could use INSERT INTO instead. With the second method you may need to clear the table before populating. | Error In Stored Procedure with error message as There is already an object named | [
"",
"sql",
"sql-server",
""
] |
I have table like this:
```
product_id model date computers
----------------------------------------------------------------
12204 Asus 'random_date' :::aass:::ddff:::ddfd:::dfwr:::
12205 Acer 'random_date' :::ersz:::dfwqq:::bbs:::
122... | Using a combination of `SUM`, `ROUND`, `LENGTH`, `REPLACE` & `COUNT` for the count field, and then group by the product\_id and model.
```
SELECT product_id, model,
SUM(ROUND ((LENGTH(computers) - LENGTH(REPLACE(computers, ":::", ""))) / LENGTH(":::"))) - count(product_id) AS count
FROM yourtable
GROUP BY product_id,... | Try the following query:
```
SELECT product_id, model,
SUM(1 + ((LENGTH(computers) - LENGTH(REPLACE(computers, ':::', ''))) / 3)) AS count
FROM products
GROUP BY product_id, model
```
Click the link below for a running demo:
[**SQLFiddle**](http://sqlfiddle.com/#!9/eba29/4) | Mysql query explode and count | [
"",
"mysql",
"sql",
"split",
"explode",
""
] |
I was able to join 2 SQL tables use the following query:
```
SELECT *
FROM Table1, Table2 with (nolock)
WHERE Table1.field1 = Table2.field2
```
Then I tried to join 3 SQL tables like below:
```
SELECT *
FROM Table1, Table2, Table3 with (nolock)
WHERE Table1.field1 = Table2.field2, Table1.field2 = Table3.field3
```... | If you use the **proper** ANSI JOIN syntax, you won't have any of those issues:
```
SELECT *
FROM
Table1
INNER JOIN
Table2 ON Table1.field1 = Table2.field2
INNER JOIN
Table3 ON Table1.field2 = Table3.field3
``` | You are joining table in old style and for multiple condition you have to use `and` instead of `,`
Try to use inner join
Like this
```
SELECT *
FROM Table1
inner join Table2 on Table1.field1 = Table2.field2
inner join Table3 on Table1.field2 = Table3.field3
``` | SQL Server: join three tables | [
"",
"sql",
"sql-server",
"join",
""
] |
I have 2 Tables A & B
**A**
```
select TranType, DocType, Document FROM
db1.dbo.A
TRANTYPE | DOCTYPE | DOCUMENT
Coup | Stat | 1
Coup | Stat | 2
Coup | Stat | 3
Coup | Stat | ...
Coup | Stat | 100
Swp | Corr | 1
Swp | Corr | 2
Swp | Corr | ...
Swp ... | **[SQL Fiddle Demo](http://sqlfiddle.com/#!6/1c80d/3)**
`UNION` is easy. Just need matching column name
Or `UNION ALL` to keep duplicated
```
SELECT TranType, DocType, SUM (Docs)
FROM (
SELECT TranType, DocType, COUNT (*) AS Docs
FROM TableA
GROUP BY TranType, DocType
UNION ALL
SELECT... | I would suggest using subqueries and then aggregating:
```
select TranType, DocType, sum(docs) as docs
from ((select TranType, DocType, count(*) as docs
from db1.dbo.A a
group by TranType, DocType
) union all
(select RecType, SubType, count(*) as docs
from db1.dbo.B
group by Rec... | Join two Tables and add Count result | [
"",
"sql",
"select",
"join",
""
] |
I am doing an Sql assignment in which I need to create a few tables. The assignment requires:
> Make sure that you define NOT NULL constraints for the PK of each table
I don't get this. When we are defining a key as Primary Key, why should we write `NOT NULL` separately with it? Doesn't defining a key as `PRIMARY KEY... | <http://www.techonthenet.com/oracle/primary_keys.php>
> In Oracle, a primary key is a single field or combination of fields
> that uniquely defines a record. None of the fields that are part of
> the primary key can contain a null value. A table can have only one
> primary key.
when you set `PK` for a table the colum... | I imagine the reason your instructor asks for this is to make sure you write DDL that shows your intent clearly. Trusting auto conversion of null to not null does not help readability of DDL so I'd request all DDL to be written such that the create table statement shows the intended nullability of all columns. | Primary key not null | [
"",
"sql",
"oracle",
""
] |
I did not know how to insert column with max.
```
Select id,MAX(salary),Min(Salary)
from C
GROUP BY id;
```
it is give me the all id with it is maximum
and I want just the id with maximum and minimum of salary!! | ```
Select id,
salary
from C
where salary = (select MAX(salary)
from C)
``` | Several options for you that only require a single scan of the table:
[SQL Fiddle](http://sqlfiddle.com/#!4/f8541/9)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE C ( ID, SALARY ) AS
SELECT 1, 100 FROM DUAL
UNION ALL SELECT 2, 110 FROM DUAL
UNION ALL SELECT 3, 100 FROM DUAL
UNION ALL SELECT 4, 110 FROM ... | Insert column with Max in sql | [
"",
"sql",
"oracle",
"greatest-n-per-group",
""
] |
I have a form with two subforms in it in the following format:
[](https://i.stack.imgur.com/9ZIBM.png)
on Subform1, Element1 has Data1. Value of Data1 points to Data1 on Subform2 which has a value of Value1
Right now both subforms are showing all data in each ... | ## Results and explanation using methods in other answers
Okay, so I ended up coming to a solution for my specific problem, and hopefully by sharing here, it will help others in the future.
The other solutions to this question assume that your form hierarchy is as follows:
```
MainForm->Subform1->Subform2
```
As in... | You can do that by changing the recordsource of Subform2 on the OnCurrent event of subform1. The steps to do that are as follows:-
* Open the form in design view
* Go to the properties of subform1
* Go to the event tab
* Select eventprocedure from the oncurrent combo
* double click on the button next to the event to g... | Filter data in datasheet based on second datasheet | [
"",
"sql",
"ms-access",
"vba",
""
] |
My data is like so
```
item date country sales
----------------------------------------
motorola 2015-01-01 US 10
motorola 2015-01-01 UK 20
motorola 2015-01-02 US 40
motorola 2015-01-02 UK 80
motorola 2015-01-03 US 120
motorola 20... | This is it, the query logic is as simple as it gets, the performance better than inner joins:
```
select date, sum(sales) - coalesce(lag(sum(sales), 1) over (order by date), 0)
from my_sales
group by date
order by date
```
Use window function `lag`. Play with it: <http://sqlfiddle.com/#!6/bebab/8> and read about it: ... | use a self join
```
declare @t table (item varchar(10), [date] date,country char(2), sales int)
insert into @t (item, [date],country, sales) values
('motorola','2015-01-01','US',10),
('motorola','2015-01-01','UK',20),
('motorola','2015-01-02','US',40),
('motorola','2015-01-02','UK',80),
('motorola','2015-01-03','US... | Syntax to get sum(sales) group by brand but different date | [
"",
"sql",
"sql-server",
"database",
"aggregate-functions",
""
] |
I have two tables in a database. One called Users and one called Days.
The Users table has a column called ID which contains some numbers and an ActiveUser column which contains either a 0(not active) or 1(active). The Days table has a column called UserID which contains the same numbers the ID column from the Users ta... | This is classic example where `APPLY` can be applied:
```
select * from users u
outer apply(select top 1 day from days where userid = u.id order by day desc)a
where u.ActiveUser = 1
```
If you want only the `day` column(I think it makes no sense):
```
select max(d) as day
from users u
join days d on d.userid = u.id
... | ```
Select a.User_ID, max(a.day) as LatestDay from Days a
Inner Join Users b
on a.User_ID = b.ID and b.ActiveUser = 1
group by a.User_ID
```
The `inner join` limits it to active users only. You can remove `a.User_ID` from the `select` if you only want a list of days. | SQL query to find most recent date using two tables | [
"",
"sql",
"sql-server",
""
] |
I need a resultset of weeknumers, year and startdate of all weeks between two dates. I need it to match other search results to the weeks. Since the report will span just over a year, I need it to match the calendars.
We're in Europe, so weeks start on MONDAY.
I use SQL Server via a JDBC connection. I cannot use the c... | Use `iso_week` in [`DATEPART`](https://msdn.microsoft.com/en-us/library/ms174420.aspx):
> ISO 8601 includes the ISO week-date system, a numbering system for
> weeks. Each week is associated with the year in which Thursday occurs.
> For example, week 1 of 2004 (2004W01) ran from Monday 29 December 2003
> to Sunday, 4 J... | The reason you're seeing 53 weeks in 2010 is simply because, there *are* 53 weeks in 2010.
Let's take a closer look at how the weeks break down in that year:
```
Declare @FromDate Date = '2010-01-01',
@ToDate Date = '2011-01-03'
;With Date (Date) As
(
Select @FromDate Union All
Select DateAdd... | Need list of weeknumbers between two dates | [
"",
"sql",
"sql-server",
"date",
""
] |
I have very large data set as below (example) :
```
#ID #report_name #report_count
1 ReportA1 3
2 ReportA1(PDF) 4
3 ReportA2 2
4 ReportA2(PDF) 6
5 ReportA3 7
6 ReportA3(PDF) 2
7 ReportA4 9
8 Repor... | In mySQL you can probably do this:
```
SELECT ReportName, SUM(ReportCount) as ReportsCount
FROM (
SELECT REPLACE(ReportName,'(PDF)','') as ReportName, ReportCount
FROM Reports ) T
GROUP BY ReportName
```
See `Demo` | This should help you
```
select substr(report_name,8),sum(report_count) from yourtablename
groupb by (substr(report_name,8))
```
This is Oracle Syntax, but every SQL dialekt have a "substr" methode. | Combine rows in same column and table with similar values and sum values | [
"",
"sql",
""
] |
I have a table with data like:
```
==============
item | tagid
--------------
1111 | 101
1111 | 102
2222 | 101
2222 | 103
3333 | 104
4444 | 105
4444 | 106
5555 | 101
5555 | 103
==============
```
I want all items with tagids `101` and `103`. In the sample above, that would be items `2222` ... | Assuming tagid is unique for each item (ie the combination of item and tagid is unqiue):
```
select item
from mytable
where tagid in (101, 103)
group by item
having count(*) = 2
```
or if not unique (unlikely), use `having count(distinct tagid) = 2` | Something like this should work:
```
select item from table
where tagid in(101, 103)
group by item
having count(distinct tagid) = 2
``` | MySQL query to get value of coumn 1 having set of values in column 2 | [
"",
"mysql",
"sql",
""
] |
I would like to create a constraint that verifies if a value (from the 'nominal\_value' column) classified as "minimum" in the 'stats\_type' column is equal or smaller than a value classified as "average", when all values in the other columns are equal. In other words, given corresponding tuples, except for columns 'oi... | This cannot be done using a check constraint because of necessity of querying the table. You can use a trigger:
```
create or replace function price_trigger()
returns trigger language plpgsql as $$
begin
if exists (
select 1
from price p
where (p.product, p.territory, p.year, p.data_source)... | Since your scenario has the complexity that the insertions can be made in any order, I suggest that you perform the insertions in a secondary table beforehand, such as price\_check.
Then you could put a trigger to perform a SQL such as:
```
SELECT pmin.*
FROM price_check AS pmin
JOIN price_check AS pavg
ON (pmin... | Constraint for values with different labels when all other columns are equal | [
"",
"sql",
"postgresql",
"triggers",
"constraints",
"multiple-columns",
""
] |
I have a `table` with Sum of Amounts for Each Weekday (Sunday to Saturday) . Table structure is as below.
[](https://i.stack.imgur.com/sFQCz.png)
I need to assign these table values into parameters. For E.g : I need to assign sum of rdate `'2015-11-1... | Ok - let's do it this way: the `else` case is set to return itself, so each variable essentially aggregates as a coalesce. Note: I don't have any way to test this right now. :)
```
SELECT
@sundayval = case when DATEPART(weekday, rdate) = 1 then sum else @sundayval end
, @mondayval = case when DATEPART(weekday,... | This does the job. It doesn't depend on any particulat [`DATEFIRST`](https://msdn.microsoft.com/en-GB/library/ms181598.aspx) settings - it instead uses an arbitrarily chosen sunday (I picked 17th May this year) (what I usually refer to as a "known good" date because it has the property we're looking for, in this case t... | Update multiple variables in a single query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table that look like this:
```
ID | DATE | NAME | VALUE_1 | VALUE_2
1 | 27.11.2015 | Homer | A | B
2 | 27.11.2015 | Bart | C | B
3 | 28.11.2015 | Homer | A | C
4 | 28.11.2015 | Maggie | C | B
5 | 28.11.2015 | Bart | C | B
```
I currently delete duplicate rows ... | You need to add one more `CTE` where you will index all islands and then apply your duplicate logic in second `CTE`:
```
DECLARE @t TABLE
(
ID INT ,
DATE DATE ,
VALUE_1 CHAR(1) ,
VALUE_2 CHAR(1)
)
INSERT INTO @t
VALUES ( 1, '20151127', 'A', 'B' ),
( 2, '20151128', 'C', 'B' ),... | You could use this query:
```
WITH cte AS
(
SELECT RN = ROW_NUMBER() OVER (ORDER BY ID)
, *
FROM @data
)
DELETE FROM c1
--SELECT *
FROM CTE c1
INNER JOIN CTE c2 ON c1.RN +1 = c2.RN AND c1.VALUE_1 = c2.VALUE_1 AND c1.VALUE_2 = c2.VALUE_2
```
Here I order them by ID. If the next one (RN+1) has similar V1 ... | SQL: Deleting row which values already exist | [
"",
"sql",
"sql-server",
"t-sql",
"delete-row",
""
] |
I need to match one column data to another column data, if the first column exists anywhere in the second then the result should be '0.5' (1/2) else if doesn't match or crossing both columns result should be '0'(zero).
I have table which contain following data:
```
Job_Id link_Id
2 3
3 2
4 ... | Why not just a standard outer join?
```
select a.job_id, b.link_id, case when b.link is not null then 0.5 else 0 end cycle
from tb a left outer join tb b
on a.job_id = b.link_id;
```
Written free hand as no create table and data is provided. Adopt as needed. | Your table looks like it might be hierarchical, in which case a [recursive CTE/sub-query factoring clause](http://docs.oracle.com/database/121/SQLRF/statements_10002.htm#BCEJGIBG) may help you in the future.
To obtain your current result though, you just need to do a self-join:
```
select coalesce(l.job_id, j.job_id)... | Find if a value exists anywhere in a second column and return a result | [
"",
"sql",
"oracle",
"birt",
""
] |
Can you please have a look at the code and notice that I cannot use the "MYDELTOT" in the main Select Statement Query, either side of the "Union"
Code:
```
select
'POID' = DYN_PORDERS.ID, 'PSID' = SYS_SUPPLIERS.ID,
(select sum(DYN_PORDERDELS.DelQty) as MMTD
from DYN_PORDERDELS
where DYN_PORDERDE... | The aliases are applied after the `WHERE` condition, that mean that there is nothing that is called `MYDELTOT` when the condition is applied.
One way to address it is to create the alias in a subquery, with that the alias will be associated to the value at the subquery level
```
select 'POID' = DYN_PORDERS.ID
, ... | You can try to use `CTE` in following:
```
;with cte as (
select 'POID' = DYN_PORDERS.ID, 'PSID' = SYS_SUPPLIERS.ID,
(select sum(DYN_PORDERDELS.DelQty) as MMTD from DYN_PORDERDELS where
DYN_PORDERDELS.DelPOID = DYN_PORDERS.ID) as MYDELTOT,
* from DYN_PORDERSRS
inner joi... | SQL - Use a Column from a Sub Select Statement as a Query in Main Select Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an issue regarding date calculations.
I have a datetime column called `CreatedLocalTime` date with this format: **`2015-11-15 19:48:50.000`**
I need to retrieve a new column called `Prod_Date` with:
```
if “CreatedLocalTime” between
(CreatedLocalTime 7 AM)
& (CreatedLocalTime+1 7 AM)
return Created... | For `day 7AM` to `day+1 7AM`, you can try:
```
SELECT CAST(CreatedLocalTime as date)
...
FROM ...
WHERE ...
CreatedLocalTime >= DATEADD(hour, 7, CAST(CAST(CreatedLocalTime as date) as datetime))
AND
CreatedLocalTime < DATEADD(hour, 31, CAST(CAST(CreatedLocalTime as date) as datetime))
...
```
For `previo... | It looks like you want somthing along the lines of
```
DECLARE @StartDateTime Datetime
DECLARE @EndDateTime Datetime
SET @EndDateTime = DATEADD(hour, 7,convert(datetime,convert(date,getdate())) )
SET @StartDateTime = DATEADD(day, -1, @EndDateTime )
--Print out the variables for demonstration purposes
PRINT '@Sta... | Today Production - SQL Date Calculation case when | [
"",
"sql",
"sql-server",
"case",
"dynamics-ax-2012",
"production",
""
] |
I have a table:
table1
```
start end
1/jan/2012 15/jan/2012
1/feb/2013 5/april/2013
```
I need to find all the possible monthly, quarterly and yearly timeframes. For ex.
1)
1/jan/2012 15/jan/2012
will fall between:
```
1/jan/2012 31/jan/2012
1/jan/2012 31/march/2012
1/jan/2012 31/dec/2012
```
2)... | ```
WITH date_range AS (
SELECT TO_DATE('2012-01-01', 'YYYY-MM-DD') AS start_date, TO_DATE('2012-01-15', 'YYYY-MM-DD') AS end_date FROM DUAL
UNION
SELECT TO_DATE('2012-02-01', 'YYYY-MM-DD') AS start_date, TO_DATE('2012-04-05', 'YYYY-MM-DD') AS end_date FROM DUAL
), monthly_range AS (
SELECT dr.start_dat... | Hope it helps:
```
-- test data
with table1 as
(select 1 as id,
to_date('20120101', 'YYYYMMDD') as start_dt,
to_date('20120115', 'YYYYMMDD') as end_dt
from dual
union all
select 2 as id,
to_date('20130201', 'YYYYMMDD') as start_dt,
to_date('20130405', 'YYYYMMDD') as end_d... | Oracle - Find monthly, quarterly and yearly dates | [
"",
"sql",
"oracle",
"date",
""
] |
I am trying to select the latest row from a LEFT JOIN not on the main query. This is my SQL:
```
SELECT *
FROM messages
LEFT JOIN users
ON messages.message_to = users.user_id
OR messages.message_user = users.user_id
LEFT JOIN message_replies
ON messag... | If i understood the question, i'll do it this simple way:
```
SELECT *
FROM messages
LEFT JOIN users
ON messages.message_to = users.user_id OR messages.message_user = users.user_id
LEFT JOIN message_replies
ON messages.message_id = message_replies.message_reply_main
... | There is a "left join" method for getting the most recent message (as well as several others). But in keeping with the preferred join method of the question:
```
SELECT *
FROM messages m LEFT JOIN
users u
ON m.message_to = u.user_id OR m.message_user = u.user_id LEFT JOIN
message_replies mr
ON m.m... | LEFT JOIN latest row using a date column | [
"",
"mysql",
"sql",
""
] |
I have the following format
```
Name someString theValue
abc bla bla 3
abc bla bla 3
abd bla bla 5
abd bla bla 5
xfz ffs ds ds 50
xfz ffs ds ds 50
```
expected result:
```
Name someString theValue
abc bla bla 3
abd bla bla ... | I would suggest a simple aggregation as the simplest approach:
```
select name, someString, min(theValue) as theValue
from t
group by name, someString;
``` | Surely what you want to do is
```
SELECT DISTINCT Name, someString, theValue FROM myTable
```
Or if you need to know how many occurances then
```
SELECT Name, someString, theValue, Count(*) as ct FROM myTable GROUP BY Name, someString, theValue
``` | SQL Server - select distinct rows by two columns | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Let's say I've got a list of Clients and I want to allocate them to a bus. I've got John, Ringo, Paul..... and they can travel on the Pink or green bus. The idea is that the allocation would be
```
John: Pink
Ringo: Green
Paul: Pink
```
Does anyone know how to do this without resorting to a loop statement?
```
--DRO... | The following code demonstrates the basic technique. Hopefully the real tables have some unique field that can be used to provide an order in place of the `( order by ( select NULL ) )` hacks.
Note that the code generates numbers for each row independent of any other data. It will not get tripped up by gaps in identit... | It is confusing to most of us here why you are not using Id columns. But, if it is as simple as you are saying, this would be the minimum code to achieve what you want.
```
DECLARE @RowIndex int = 0
UPDATE BusAllocation
SET BusAllocation = CASE WHEN @RowIndex % 2 = 0 THEN 'Pink' ELSE 'Green' END,
@RowIndex = @RowInd... | Update a table with records in a sequential order | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have the following query --
```
select * from main_iteminstance where master_id=33568
or tv_series_id in
(select id from main_iteminstance where master_id=33568)
```
How would this best be simplified?
Basically, what I am trying to get is:
```
ids = select id from main_iteminstance where master_id=33568
child... | Upon looking at this further, the subquery is performing the lookup where the master\_id is the same value of the parent query. This means the condition with the `tv_series_id` is superfluous as it will only return results that have already been found in the parent.
Your most simple resultset would be:
```
SELECT *
... | Another way to do it is to join the table on itself:
```
SELECT Master.*
FROM main_iteminstance Master
INNER JOIN main_iteminstance Child
ON Child.master_id = 33568 AND ((Master.id = Child.id) OR (Master.tv_series_id = Child.id))
``` | How to simplify sql statement | [
"",
"mysql",
"sql",
""
] |
I've been trying to find some way to simplify editing/adding a value to the corresponding column inside Insert-clauses when coding inside SQL inside Managagement Studio 2008 R2.
Assume the following code:
```
INSERT INTO [Schema].[Table]
( [Col1],
[Col2],
[Col3],
... | I'm not aware of any facility to do this, but when I've run into this issue, I usually just add comments to the code, something like:
```
VALUES
(
232, --Col1
0, --Col2
NULL, --Col3
NULL, --Col4
--etc.
... | I haven't seen an option like this.
Although it requires more typing, I prefer SELECT over VALUES because I can alias the inputs, saving time later. Also SELECT statements can be previewed (by highlighting just that section and pressing F5 - very handy).
Alternative you can turn on line numbers in SSMS and calculate ... | How to find column in value list easily in Management Studio? | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I have a procedure and anonymous block, where I enter in two dates and it searches the tickets table for the tickets that have been resolved during those two dates and outputs em. But I can't seem to figure out how to output multiple rows in pl/sql.
```
ORA-01422: exact fetch returns more than requested number of rows... | Based on new information: your query returns multiple records. With this type of select you can only fetch one row. Try using a cursor. e.g. structure like this:
```
declare
cursor c1 is <select your thing from table>;
begin
for r1 in c1
loop
dbms_output.put_line (r1.firstcolumn|| r2.anothercolumn );
end loop;
en... | ```
Try this. Returning refcursor is the best way for this kind of resultset.
CREATE OR REPLACE PROCEDURE jobs_done(
month_start IN tickets.DATE_REPORTED%TYPE,
month_end IN tickets.DATE_RESOLVED%TYPE,
cur_out OUT sys_refcursor
)
AS
OPEN cur_out FOR
select user_id, support_staff_i... | PL/SQl sqldeveloper want to output multiple rows in plsql | [
"",
"sql",
"oracle",
"plsql",
"select-into",
"ora-01422",
""
] |
I am trying to use nested sql in postgresql tPostgresqlRow\_1.
But I receive an error.
The following sql runs okay if I run it in PgAdmin.
But in Talend I receive an error.
I am getting the max date from one table and updating the column in another table.
```
update "STG_magento_de"."configuration_table"
set created_a... | The tPostgresqlRow component expects a Java string containing the SQL statement.
The most likely problem is that you have unescaped quotes in the statement. That works fine in pgAdmin because it is valid. To pass the same statement from Talend, you'll have to escape all the quotes in the statement itself. Alternativel... | Following sql with escape quotes worked.
```
"update \"STG_magento_de\".\"configuration_table\"
set created_at=(select MAX(created_at) from \"STG_magento_de\".\"sales_flat_order_test\")
where table_name='sales_flat_order_test'"
``` | Nested sql statement in talend (updated) | [
"",
"sql",
"talend",
""
] |
Consider this setup. Please understand that our setup is much more detailed but this is a simple example.
`competition` which has `name`. This is an annual competition.
`competition_instances` which has `location`, `starts_at`.
Each competition has `sports` which has `name`.
Example:
`competition`.`name`: "Supe... | I'm just thinking of the case where there are standard sports which are always in the Olympics and some which are added on, such as those proposed by the host country.
I would use [Polymorphic Associations](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations), in a ["reverse manner"](https:/... | Based on what I understand from the question I cannot see where STI will be helpful in this situation. However a join table will get you where you want.
I suggest creating a new table `sports`, this model will have all the specific details of each sport. The `competition_instance.rb` will have one/many `sport.rb`. `co... | Rails: Is this a use case for Single Table Inheritance (STI)? | [
"",
"sql",
"ruby-on-rails",
"database-design",
"database-normalization",
"sti",
""
] |
I seem to be stuck on this and can't find a solution having had a look around.
I have an SQL table who's first row looks something like this:
```
Name Val1 Val2 Val3
John 1000 2000 3000
```
What I need to do is Select the largest value within this row i.e. `3000`
Obviously if these values were in a colu... | You can build a reference table for columns by `APPLY` and use native `MAX()`
```
-- Sample Data
declare @data table (Name varchar(10), Val1 int, Val2 int, Val3 int, Val4 int, Val5 int, Val6 int)
insert @data values
('John', 1000, 2000, 3000, 4000, 5000, 6000),
('Mary', 1, 2, 3, 4, 5, 6)
select Name, MaxVal... | ```
select MAX(case when c1 > c2 and c1 > c3 then c1
when c2 > c3 then c2
else c3
end)
from tablename
```
**Edit:** Modern SQL Server versions have the `GREATEST()` function:
```
select GREATEST(c1, c2, c3)
from tablename
```
<https://learn.microsoft.com/en-us/sql/t-sql/fun... | SQL - Select the largest value within a row | [
"",
"sql",
"max",
"ssms",
""
] |
In our application, we have some tables storing staff data. I need to find out whether the same office is allocated to a staff member multiple times. How can I figure this out in SQL Server?
I have tried below query but it didn't give me the correct solution.
```
SELECT DISTINCT STAFFID, officeid
FROM [stafftable]
WH... | ```
SELECT *
FROM (
SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY STAFFID, officeid ORDER BY STAFFID)
FROM dbo.stafftable
WHERE rowstatus = 'A'
) t
WHERE t.RowNum > 1
``` | You can use `COUNT(*)` to count all rows in each group:
```
SELECT STAFFID, officeid
FROM [stafftable]
WHERE rowstatus = 'A'
GROUP BY STAFFID, officeid
HAVING COUNT(*) > 1
ORDER BY STAFFID, officeid
``` | Find out the Duplicate Records in Sql-server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In my query, when I use:
```
CONCAT(GROUP_CONCAT(wu_paqueteproducto.extra1),' ',GROUP_CONCAT(wu_paqueteproducto.producto)) as elproducto
```
I get something like this
```
+--------+---------+----+---------------------------------------------+
| poliza | cct | // | elproducto |
+-... | Put `CONCAT` inside `GROUP_CONCAT` instead of the other way around:
```
GROUP_CONCAT(CONCAT(wu_paqueteproducto.extra1, ' ', wu_paqueteproducto.producto)) AS elproducto
``` | I have wrote on [SQL Fiddle](http://sqlfiddle.com/#!9/0426f/2) a solution than you can translate easily to your query:
**MySQL 5.6 Schema Setup**:
```
create table t ( a char(1), b char(1), i int);
insert into t values
( '1', 'a', 1 ),
( '2', 'b', 1 ),
('8', 'x', 2),
('9', 'y', 2);
```
**Query**:
```
select GROU... | How do I group columns into a field containing the data? | [
"",
"mysql",
"sql",
""
] |
Table @t1 is the master table that should have the summed values of table @t2 after an import.
```
DECLARE @t1 TABLE (
typ int,
total float
);
insert into @t1 (typ,total) values(1,30.0)
insert into @t1 (typ,total) values(2,70.0)
insert into @t1 (typ,total) values(3,99.9)
DECLARE @t2 TABLE (
... | This would normally be done with a `left join`:
```
select t1.typ, t1.total, t2.typ, t2.sumvalue,
(case when t1.total = t2.sumvalue then 'TRUE' else 'FALSE' end) as Result
from @t1 t1 left join
(select typ, sum(t2.value) as sumvalue
from @t2 t2
group by typ
) t2
on t2.typ = t1.typ;
``... | You can use `OUTER APPLY` for this:
```
SELECT t1.typ, t1.total, x.Summed,
CASE
WHEN x.Summed = t1.total THEN 'TRUE'
ELSE 'FALSE'
END
FROM @t1 AS t1
OUTER APPLY (
SELECT SUM(value) AS Summed
FROM @t2 AS t2
WHERE t1.typ = t2.typ ) AS x
``` | Comparing summed values against the master table | [
"",
"sql",
"sql-server-2008",
""
] |
I have a database query question.
My USER table set up is like this..
```
Id | PIN | biz_id | active_ind
--- | ---------------------------
1 | 123 | NULL | Y
2 | 456 | 1 | Y
3 | 789 | NULL | N
4 | 012 | 2 | Y
```
and my USER\_PURCHASE table is like this
```
id user_id ... | ```
SELECT
u.id,
u.pin,
max(up.date) mdate
FROM
User u
LEFT JOIN User_Purchase up ON u.Id = up.user_id
WHERE
u.active_ind = 'Y'
and u.biz_id IS NULL
GROUP BY
u.id,
u.pin
HAVING
mdate IS NULL or
mdate < DATE_SUB( CURDATE( ) , INTERVAL 13 MONTH )
```
you can leave off the `m... | It's not correct because inner join users\_purchases will automatically filter out users who have never made any purchase.
```
select distinct a.id, a.pin
from users a
left join users_purchases b on a.id = b.user_id and b.mdate >= curdate() - interval 13 month
where a.active_ind = 'Y' and a.biz_id is null and b.id is ... | MYSQL getting a user with latest purchase | [
"",
"mysql",
"sql",
"select",
"join",
"greatest-n-per-group",
""
] |
I have two tables:
Table 1:
```
Id
1232
1344
1313
4242
3242
555
```
Table 2:
```
Id sym mnth code
1232 9 1 32
1344 15 1 14
1313 10 1 32
4242 11 1 32
3242 9 1 32
1232 9 2 32
1344 13 2 14
1313 9 2 32
4242 10 2 ... | * Here I create a cte to find out what are the month missing.
* Has to create a derivated table `months` to include all the months.
* Then perform a left join, so either didnt exist one item in table 2 to match or the item was the wrong one
* Once I have all the wrong link create the string using `XML PATH`
+ [Conca... | You have a lot of conditions in your request that don't compliment each other so well, so the query is likely going to look a bit messy, and probably perform slow. You'll need a way to combine results into your comma-delimited list. SQL Server doesn't have a built-in string concatenation aggregate function, so you'll n... | Check if all ID's in a Column have a specific value in another column, different tables | [
"",
"sql",
"sql-server",
"select",
"exists",
""
] |
I am quite new in sql server. I am trying to run this following query:
```
SELECT AVG( jl.[Stock Weight] )
FROM [Settlement Line] jl
WHERE jl.[Vendor No_] = 8516
AND ( jl.[Slaughter Date] BETWEEN '2015-11-01' AND '2015-11-30' )
AND ( CAST( jl.[Item No_] AS INT ) BETWEEN 17000 AND 17099 )
```
As a ... | It is unclear from the error whether the error is for `[Vendor No_]` or `[Item No_]` or `jl.[Stock Weight]`. SQL is strongly typed, but does type conversions. You should try to do the comparisons using the same type and not to store numbers as strings.
If the problem is the average, then you can use a `case`. Somethin... | Try this one:
```
SELECT AVG(jl.[Stock Weight])
FROM dbo.[Settlement Line] jl
WHERE jl.[Vendor No_] = 8516
AND jl.[Slaughter Date] BETWEEN '20151101' AND '20151130'
AND jl.[Item No_] BETWEEN '17000' AND '17099'
``` | SQL Server error "Conversion failed" while using CAST or CONVERT | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Guy's I'm having issues with this query of mine. I have done what i can and now it's coming towards the end. If i run the 2 separate it works perfectly but once i select the whole thing to run as on piece it give me an error about the temp table already existing even though I check if the Temp table exists and drop it ... | `ELSE` is not a batch separator, and any temporary tables you use and don't drop will throw this error.
Unless you've specifically changed the batch separator, you should use `GO` in-between your batches. That way any temporary tables will be dropped between batch separation. | T-SQL is declarative, when you execute the SQL the first thing the optimiser does is look at your batch of SQL and then create an execution plan (that is before anything actually executes), so, to the optimiser you do indeed have two CREATE TABLE #TEMP which is invalid. You can't even use dynamic SQL here because the s... | Can not run the whole T-SQL query but in parts I can | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have two tables and i need to compare data and update/insert one table records. What iam trying to do is I need to take each record from Table1,
use a split function then for each text in split, compare dataelement field between both these tables. We are syncing data in Table2 to similar to Table1.
Please let me know... | You can try using a MERGE statement with a few other tricks.
[Merge Guide](https://www.simple-talk.com/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/)
```
-- Create a CTE that will split out the combined column and join to DataTable
-- to get the dataId
;WITH cteTable1Split AS
(
SELECT reqId, dt.* ... | You've not mentioned whether you have control over the structure of these tables, so I'm going to go ahead and suggest you **redesign Table1 to normalise the dataelementValues column**.
That is, instead of this:
```
Table1:
Id reqId dataelementValues
1 52 Check
2 52 City;State;System
... | Loop through table data and compare using split | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Here is my Store Procedure for printing purpose. I am facing issue as i get records twice as they exist due to commented join. I want to get output as mentioned below in question. I am a novice to DB. Help in this regard will be appreciated.
```
DECLARE @path AS VARCHAR(100)
SET @path = N'~/BillAttachments/166/'
DECLA... | Use [`DISTINCT`](https://msdn.microsoft.com/en-us/library/ms176104.aspx):
> Specifies that only unique rows can appear in the result set
```
SELECT DISTINCT bh.billID,bh.statusID,bh.modifiedOn,bs.statusName
FROM dbo.eInvoice_tbl_billHistory AS bh
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON bh.billID = ba.b... | A different approach if your rule is getting more complex which row you want to keep using a CTE and the [`ROW_NUMBER`](https://msdn.microsoft.com/en-us/library/ms186734.aspx) ranking function:
```
WITH CTE AS
(
SELECT bh.billID,
bh.statusID,
bh.modifiedOn,
bs.statusName,
... | How to avoid duplicate records while retrieving using Inner Join in SQL Server | [
"",
"sql",
"sql-server",
"database",
"stored-procedures",
"inner-join",
""
] |
Need help figuring out how to determine if the date is the same 'day' as today in teradata. IE, today `12/1/15 Tuesday`, same day last year was actually `12/2/2014 Tuesday`.
I tried using `current_date - INTERVAL'1'Year` but it returns `12/1/2014`. | You can do this with a bit of math if you can convert your current date's "Day of the week" to a number, and the previous year's "Day of the week" to a number.
In order to do this in Teradata your best bet is to utilize the `sys_calendar.calendar` table. Specifically the `day_of_week` column. Although there are [other... | Why don't you simply subtract 52 weeks?
```
current_date - 364
``` | Teradata SQL Same Day Prior Year in same Week | [
"",
"sql",
"teradata",
""
] |
If I have the following example table, is there any way that I only keep rows where the "Closed Date" column is empty? In this example, only the second row has an empty "Closed Date" column, the third and fourth are not. [](https://i.stack.imgur.com/gq... | ```
SELECT *
FROM your_table
WHERE [Closed Date] IS NULL OR LTRIM(RTRIM([Closed Date])) = ''
``` | You can use `IS NULL` to filter out records that contains `NULL` value:
```
SELECT *
FROM your_table
WHERE "Closed Date" IS NULL
```
Keep in mind that column identifier with space is bad practice. You should use something like `Closed_Date` to avoid quoting. | SELECT only the whole row where the column is empty in SQL | [
"",
"sql",
"sql-server-2014",
""
] |
I have a sql problem that I just cannot seem to solve.
Please imagine a table of software releases. In said table we have a release id, a product id, a version number and a status flag field.
*Please note I have heavily simplified this. In the real world this is a BIG table hence we introduced the status to avoid exp... | How about using window functions?
```
with toupdate as (
select sr.*, row_number() over (partition by ProductId order by version desc) as seqnum
from SoftwareRelease sr
)
update toupdate
set status = (case when seqnum = 1 then 1 else 0 end)
where seqnum = 1 and status = 0 or seqnum > 1 and sta... | You can do this with a `Row_Number()` function over the ProductId partition, and then updating the `Status` column based on whether it is the latest version or not:
```
;With Cte As
(
Select *,
Row_Number() Over (Partition By ProductId Order By Version Desc) Row_Number
From SoftwareRelease
... | Update a record where a "newer" version exists | [
"",
"sql",
"sql-server",
"sql-update",
""
] |
I'm new to SQL and database design.
I have a task where I need to create a table with users (student or teacher), each user can be in a group or more, and each group can get one or more tasks to solve.
I created the design, but I think is a problem with the entity `group`, because when I what to add data there, I can... | Is this a possible way to do it?
```
insert into [group] (group_id) values((SELECT ISNULL(MAX([group_id])+1,1) FROM [group] WITH(SERIALIZABLE, UPDLOCK)))
insert into [Entity3] values(1,1) //values(x,y) x - user_id, y - group_id where I want to add the user
insert into [Entity3] values(2,1)
insert into [Entity3] ... | Something like this should work:
```
USERS
-----
user_id (pk)
name
surname
email
GROUPS
------
group_id (pk)
groupName
TASKS
-----
task_id (pk)
taskName
USERSGROUPSM2M (Many-to-Many table)
-------------
id (pk)
user_id (fk)
group_id (fk)
```
You could have user\_id #1 with group\_id #1 and #42, or any combination
... | Designing SQL Server database | [
"",
"sql",
""
] |
I'm trying to make a report to find rows in a table, which have a mistake, a missing item order. I.e.
```
ID Item Order
----------------
1 A 1
2 A 2
3 A 3
4 B 1
5 B 2
6 C 2
7 C 3
8 D 1
```
Note, that Item "C" is missing row wit... | You can find the missing orders using a [HAVING](https://msdn.microsoft.com/en-GB/library/ms180199.aspx) clause. HAVING allows you to filter on aggregated records. In this case we are filtering for Items with a min Order in excess of 1.
The benefit of this approach over a sub query in the WHERE clause is SQL Server do... | The idea is sound, but there is one tiny detail with NOT IN that may be problematic. That is, if the subquery after NOT IN results in any NULLs, the NOT IN is evaluated as if it were false. This may be the reason why you get no results. You can try NOT EXISTS, like in the other answer, or just
`SELECT DISTINCT Item FR... | Select rows with missing value for each item | [
"",
"sql",
"sql-server",
"distinct",
""
] |
Is there any ways to SELECT the first and last 2 characters and REPLACE all the other characters with \* as shown below?
```
WA***RT
EX*** ***IL
CH***ON
BE******* *****AY
AP*LE
```
Thanks in advance! | Spaces skipped:
```
SELECT
name,
[hidden] = CASE WHEN LEN(name) <= 4 THEN name
ELSE CONCAT(LEFT(name, 2),REPLICATE('*', LEN(name)- 2),RIGHT(name,2))
END
FROM #tab;
```
If you need spaces and there is **only one** you can use:
```
SELECT name,
[hidden] = CASE
WHEN LE... | ```
select left(col, 2) + REPLICATE('*',len(col)-4) + right(col,2) from table;
``` | SQL-Server: Replace except first and last characters | [
"",
"sql",
"sql-server",
""
] |
Noob question - I have the following tables;
ID is Unique as well as date & time.
How can I write an SQL query that will return a table with;
```
COLUMNS: id, man
```
Pretty sure I'm being extra stupid but losing patience rapidly with what appears to be so simple. | ```
SELECT t2.*, t1.price
FROM film t1
JOIN movie t2 ON t1.id = t2.id
``` | ```
select film.id, date, time, price
from film
join movie on (film.id = movie.id)
``` | SQL - joining tables together for a single table | [
"",
"sql",
""
] |
I have the following code:
```
declare @testValue nvarchar(50) = 'TEST';
select @testValue = 'NOTUSED' where 1 > 2;
select @testValue; -- Outputs 'TEST'
select @testValue = 'USED' where 2 > 1;
select @testValue; -- Outputs 'USED'
```
With the above, the first assignment is never used because the where clause fails. ... | This is the expected behavior:
"If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL."
<https://msdn.microsoft.com/en-us/library/ms187330.aspx>
You can get around this in your example by using a subquery... | This is the default behavior of `SELECT`.
When assigning a value to a variable using `SELECT`, if there is no value returned, `SELECT` will not make the assignment at all so the variable's value will not be changed.
On the other hand, `SET` will assign `NULL` to the variable if there is no value returned.
[For more ... | Why doesn't the Select statement assigns an empty string or null value if it doesn't return a result? | [
"",
"sql",
"sql-server",
""
] |
im a bit new to sql server, so hopefully this isnt something too convoluted. if i have a table with a bunch of data that shows different records that have been complete or not...
TABLE 1
```
ID CATEGORY COMPLETE
1 reports yes
2 reports no
3 processes no
4 processes yes
5 reports ... | `group by` category column and use conditional sum to get only `complete = 'yes'` cases in the numerator.
```
select category,
100 * 1.0 * sum(case when complete = 'yes' then 1 else 0 end)/count(*) as pct
from tablename
group by category
``` | You can use windowed functions and `PARTITION BY Category`:
```
SELECT DISTINCT Category,
[percentage] = ROUND(100 * SUM(CASE complete WHEN 'yes' THEN 1.0 ELSE 0.0 END)
OVER (PARTITION BY Category)/
COUNT(*) OVER (PARTITION BY Category),0)
FROM #tab;
```
`LiveDem... | SQL Server Completion Percentage Category | [
"",
"sql",
"sql-server",
"percentage",
""
] |
I have this:
```
SELECT
invoice_number, invoice_year, invoice_month, invoice_amount,
payment_year, payment_month, payment_amount
FROM payments_table
```
**Result:**

So I have 4 invoices. The invoice amount of two invoices from 2015/01 add up to 900 and the 2 invoi... | I've found the solution myself. Thanks all for thinking with me:
```
select b.invoice_year
, b.invoice_month
, b.invoice_amount
, c.payment_year
, c.payment_month
, c.payment_amount
from (
select a.invoice_year
, a.invoice_month
, sum(a.invoice_amount) as invoice_amount
from (
select distinct... | The query you need is this one:
```
select a.invoice_year, a.invoice_month, a.payment_year, a.payment_month,
SUM(payment_amount), b.sumup
from payments_table a
inner join
(select invoice_year, invoice_month, sum(payment_amount) sumup
from payments_table
group by invoice... | Two different grouping levels in one select | [
"",
"sql",
"sql-server",
""
] |
I have a database query:
```
DECLARE @Pager_PageNumber AS INT, @Pager_PageSize AS INT;
SET @Pager_PageNumber = 1;
SET @Pager_PageSize = 12;
SELECT
[Name], [Description], [Table1ID], [VersionNo], [Status]
FROM
(SELECT
CAST(Table1.name AS VARCHAR(MAX)) As [Name],
CAST(Table1.description... | You apply `with (nolock)` to *tables*, not to subqueries. So, instead of:
```
(SELECT Table1_id, MAX(version_no) as version_no
FROM Table1
where Table1.status='00002'
GROUP BY Table1_id
) as BR WITH (NOLOCK)
```
You would write:
```
(SELECT Table1_id, MAX(version_no) as version_no
FROM Table1 WITH (NOLOCK)
wher... | Just put
```
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
```
before your query. NOLOCK behavior will be used for all your tables in the query. Using hint NOLOCK just means using READ UNCOMMITTED transaction isolation level for a particular table. | SQL Server Inner Join using WITH(NOLOCK) | [
"",
"sql",
"sql-server",
"join",
"inner-join",
"self-join",
""
] |
I have a table on my DB that record every call made by employees all over the day.
Every record is a call made by branch lines.
If a branch made 50 calls a day we will have 50 records on DB:
```
branch | date
-------+----------------------------
72489 | 2015-12-03 08:03:58
34002 | 2015-12-03... | The cast using `::date` implies you are using Postgres. In this case getting the "*the first call of the day of every branch line*" is quite easy by using the `distinct on()` operator:
```
SELECT DISTINCT ON (branch) branch, date
FROM table
WHERE date::date = '2015-12-03'::date
ORDER BY branch, date;
```
Another po... | Possible solution:
```
SELECT
branch,
(
select
date
from
table tb
where
tb.branch = table.branch
) as date
FROM
table
GROUP BY
branch
WHERE
date::date='2015-12-03'::date;
``` | SELECT DISTINCT or GROUP BY on field | [
"",
"sql",
"postgresql",
"group-by",
"distinct",
"greatest-n-per-group",
""
] |
I have the following query which counts the number of items created on a particular date in the last 10 days
```
SELECT
CONVERT (DATE, CreatedDate_6258638D_B885_AB3C_E316_D00782B8F688) AS 'Logged Date',
Count (*) AS 'Total'
FROM
MTV_System$WorkItem$Incident
WHERE
CreatedDate_6258638D_B885_AB3C... | You can write a recursive cte to get the date for the last 10 days into a table as follows:
```
WITH TableA (StartDate) AS (SELECT DATEADD(DAY, DATEDIFF(DAY, 0, Getdate()) - 10, 0)),
q as (
SELECT StartDate
, Number = 0
FROM TableA
UNION ALL
SELECT DATEADD(d,1,StartDate)
... | Similar to BeanFrog's answer but a little shorter
```
-- sample data for testing
declare @MTV_System$WorkItemIncident table (
[CreatedDate_6258638D_B885_AB3C_E316_D00782B8F688] DATE,
[Total] INT
);
INSERT INTO @MTV_System$WorkItemIncident VALUES ('2015-11-23', 23);
INSERT INTO @MTV_System$WorkItemIncident VALU... | Show Dates that have no values for selected column | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
Suppose I have the following table
```
ClassID StudentID
1 10
1 11
2 12
2 10
3 13
```
I want to have table like this
```
ClassID StudentID1 StudenID2 ... StudentID32
1 10 11 null
2 12 10 null
3 3 ... | I hope I understood you clearly..I still used PIVOT though and here, I assume I don't know the student ID's as well.
```
create table Student (
ClassID INT
, StudentID INT
)
INSERT INTO Student (ClassID, StudentID) VALUES
(1,10)
, (1,11)
, (2,12)
, (2,10)
, (3,13)
select
'Student' + CONVERT(NVARCHAR... | With a known limit that is relatively small (e.g. 10), a self join would work. | T-sql putting values of column into one row | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Hey so I have one set of data with the structure:
```
id product_number product_type
1 1001 car
2 1002 house
```
But the data has some duplicates where:
```
id product_number product_type
1 1001 car
2 1001 house
```
I ... | In MySQL, you can do what you want with a `join`:
```
delete t
from table t join
(select product, count(*) as cnt
from table
group by product
) tt
on tt.product = t.product
where tt.cnt > 1 and t.product_type = 'house';
``` | ```
DELETE *
FROM table
WHERE id not in
(select max(id) from table
group by product_number)
```
AND product\_type = house | Deleting duplicates with a where clause | [
"",
"mysql",
"sql",
""
] |
I am trying to get the total sum of a column and the sum of the same column between 2 dates in one query. is this possible?
My table looks like this:
```
uid|amount|date
```
The two queries i am trying to make one of:
```
SELECT sum(amount) as `keys` FROM tbl_keys WHERE uid = 1
SELECT sum(amount) as `keys` FROM tb... | You could use a UNION query:
```
SELECT 'All' AS cnt, sum(amount) as `keys` FROM tbl_keys WHERE uid = 1
UNION ALL
SELECT 'Current_month' AS cnt, sum(amount) as `keys`
FROM tbl_keys
WHERE
uid = 1
AND `date`<= last_day(current_date)
`date`>= current_date - interval (day(current_date)-1) day
```
(I prefer to use `... | Something like this:
```
SELECT sum(amount) as `keys`,
(
SELECT sum(t.amount)
FROM tbl_keys as t
WHERE t.uid = tbl_keys.uid AND YEAR(t.`date`) = YEAR(CURRENT_DATE)
AND MONTH(t.`date`) = MONTH(CURRENT_DATE)
) as `keys2`
FROM tbl_keys
WHERE uid = 1
``` | MYSQL get total sum and sum between 2 date in 1 query | [
"",
"mysql",
"sql",
""
] |
Assuming we got two below tables:
**TravelTimes**
```
OriginId DestinationId TotalJourneyTime
1 1 10
1 2 20
2 2 30
2 3 40
1 3 50
```
**Destinations**
```
... | Use a [`RANK`](https://msdn.microsoft.com/en-GB/library/ms176102.aspx) to rank each journey partitioned by the origin and destination and ordered by the travel time
```
WITH RankedTravelTimes
AS
(
select originid,
destinationId,
totaljourneytime,
rank() over (partition by originid,destinatio... | Not sure I see the problem here with just joining and grouping the data with a `MIN` on the journey time:
```
CREATE TABLE #Traveltimes
(
[OriginId] INT ,
[DestinationId] INT ,
[TotalJourneyTime] INT
);
INSERT INTO #Traveltimes
( [OriginId], [DestinationId], [TotalJourneyTime] )
VAL... | SQL: first row of group by after join and order | [
"",
"sql",
"sql-server",
""
] |
table is like this, say it represents various types of events in a log file
```
<type> <date>
```
I want to select the top 5 most common types
```
select type,count(type) as c from log order by c desc limit 5
```
this works fine, but I only want the type column so I can use this is a `where in` subquery. How do I d... | Pretty straightforward:
```
SELECT type FROM log GROUP BY type ORDER BY COUNT(type) DESC LIMIT 5
``` | You didn't specify the RDBMS and this is highly dependent on which one you're using. Here are some options.
```
-- works in postgres and mysql
select type from log group by type order by count(*) desc limit 5;
-- this variant works in mssql but probably no where else (maybe sybase)
select top(5) type from log group b... | selecting a column sorted by count but without the count | [
"",
"sql",
"sqlite",
""
] |
I'm trying to do a select statement to order the result set by force of connections between them.
```
CREATE CLASS Entity EXTENDS V;
CREATE CLASS isConnectedTo EXTENDS E;
CREATE PROPERTY isConnectedTo.strength INTEGER;
```
**'isConnectedTo'** edges relate **Entities** to another **Entities**
The tricky part is I ha... | I'd like to propose a small change on your domain. Don't create 2 edges in case both people are connected, but use the same edge with 2 properties.
```
CREATE CLASS Entity EXTENDS V;
CREATE CLASS isConnectedTo EXTENDS E;
CREATE PROPERTY isConnectedTo.strengthOut INTEGER;
CREATE PROPERTY isConnectedTo.strengthIn INTEGE... | Try this query:
```
select expand($a.rid) from (select from Entity where name="Mike")
let $a=(select @rid,sum(bothE().strength) as sum from Entity where both('isConnectedTo').name contains $parent.current.name group by name order by sum desc)
``` | Summing edges properties for order by in select statement | [
"",
"sql",
"graph",
"properties",
"graph-theory",
"orientdb",
""
] |
my assignment is to create table-valued function, which will have one DATETIME parameter and which returns every date from first to last day of the month, for example I gave the function date 04/12/2015 from that parameter and it will print all 31 days date of December.
I've already created 2 scalar functions (this wa... | We're not here to do your homework for you, or it defeats the purpose of the homework.
That said, some tips to get you going -
* Don't build your FirstDay using a CAST to string like that - it's not reliable across different servers with different system settings. Run that on a non-US server and it'd fail. Use DATEAD... | Try something like this....
```
Declare @Date DATE = '20151104';
WITH X AS
(
SELECT TOP (31)
YEAR(@Date) AS [Year]
,MONTH(@Date) AS [Month]
,RIGHT('00' + CAST(ROW_NUMBER()
OVER (ORDER BY (SELECT NULL)) AS VARCHAR(2)),2) [Days]
FROM master..spt_values
), Dates AS
(
SELECT TRY_CONVERT... | find out every date from first to last day of the month using table valued function | [
"",
"sql",
"sql-server",
""
] |
I have the following query:
```
SELECT
CASE
WHEN ([DBO].fn_WorkDays(GETDATE(), DATEADD(d, 1, EOMONTH(GETDATE()))) = 2)
THEN 1
END
```
That should return 1 if the condition is true (obviously), but I want it to return nothing (no rows) if false. Instead, it's returning a null row. H... | The way you have this coded it will always return a row. You could rearrange your query to put the scalar function in the where clause.
```
SELECT 1
where [DBO].fn_STRS_WorkDays(GETDATE(), DATEADD(d, 1, EOMONTH(GETDATE()))) = 2
```
Of course, you might consider evaluating that scalar function. They are notoriously po... | How about
```
IF [DBO].fn_STRS_WorkDays(GETDATE(), DATEADD(d, 1, EOMONTH(GETDATE()))) = 2
SELECT 1
``` | Force a SQL Server query to return no rows | [
"",
"sql",
"sql-server",
""
] |
I have a database where I am trying to count the total cancellations and changes. The problem is that their are duplicate rows in the database and I only want to use one row for each id. In the example below, I want my final count to be cancellations:5 , changes:1 . The sum part is working correctly, but the MIN(id) is... | You have to use `DISTINCT`:
```
SELECT
SUM(cancellations), SUM(changes)
FROM (
SELECT DISTINCT * FROM table_1
) AS t
``` | i broke down the parts of your query into smaller ones and made a whole query out of the parts in this sql fiddle, [**Fiddle Here**](http://sqlfiddle.com/#!6/3808d/16) | SQL MIN not working correctly | [
"",
"mysql",
"sql",
"sql-server",
"database",
""
] |
I am trying to make search method in my Rails app, but sadly - my SQL knowledge is rather pathetic. I managed to find guides that have searched text in the description by:
```
@guides = Guide.where(['description LIKE ?', "%#{params[:search]}%"])
```
or in the title:
```
@guides = Guide.where(['title LIKE ?', "%#{pa... | You can use the keyword "or" in your SQL queries:
```
Guide.where('description LIKE :search OR name LIKE :search', search: "%#{params[:search]}%")
```
About the doc, you can try this website which seems to offer interactive courses about SQL in general: <http://www.sqlcourse.com/>
This website is about PostgreSQL: <... | **The shortest answer is tag this method onto your model:**
```
def search_by_fields(q, fields=nil)
sql = fields.map {|field| "#{field} LIKE ?"}.join(' OR ')
parameters = fields.map {"%#{q}%"}
where(sql, *parameters)
end
```
**A longer answer is in a concern!**
Using a concern is a great way to provide search ... | Rails search SQL query | [
"",
"sql",
"ruby-on-rails",
"ruby",
"postgresql",
"search",
""
] |
These are my tables:
`Room` (roomId, roomName, roomTypeId, roomStatus)
`RoomType` (roomTypeId, roomTypeName, roomTypeDesc, roomTypePrice)
`ReservationRoom` (reservationId, roomId,checkInDate, checkOutDate, totalStay)
I receive three parameter from user (check in date, check out date, quantity)to search the availabl... | You could convert from type DATE columns to [DATETIME](https://dev.mysql.com/doc/refman/5.5/en/datetime.html) columns, and then compare specific times of day (i.e., your specific check-out time, such as 11am).
Or, convert all times to [UNIX\_TIMESTAMP](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.ht... | use MySQL `str_to_date` or `cast` because you must need to convert your type as `DATE`
```
cast(str_to_date('1/11/2015','%d/%m/%Y')as date)
```
or
```
cast(str_to_date(checkindate,'%d/%m/%Y')as date)
``` | Search Room Availability | [
"",
"mysql",
"sql",
"database",
""
] |
I'm having a hard time trying to make a query that gets a lot of numbers, a sequence of numbers, and if the difference between two of them is bigger than 30, then the sequence resets from this number. So, I have the following table, which has another column other than the number one, which should be maintained intact:
... | With this test case:
```
declare @data table (id int identity, Number int, Status varchar(20));
insert @data(number, status) values
( 1,'OK')
,( 1,'Failed')
,( 2,'Failed')
,( 3,'OK')
,( 4,'OK')
,( 4,'OK') -- to be deleted, ensures IDs are not sequential
,(36,'Failed') -- to be delete... | I don't deserve answer but I think this is even shorter
```
with gapped as
( select id, number, gap = number - lag(number, 1) over (order by id)
from @data data
),
select Id, status
ReNumber = Number + 1 - isnull( (select top 1 gapped.Number
from gapped
... | If the difference between two sequences is bigger than 30, deduct bigger sequence | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I want list of columns and its table name in a database with columns having all null values.
This table is too large some columns having only null values.
I want a stored procedure which list out columns in a table which do not have any data at all (That is NULL).
So that I can trim number of columns.
```
CREATE TA... | Here's a quick stored procedure that will do a `NULL` check on all columns in a provided table.
```
Create Procedure spGetColumnsWithAllNullValues
(
@Database Varchar (100),
@Schema Varchar (100),
@Table Varchar (100)
)
As Begin
Declare @Column Varchar (100)
Declare @Columns Table
... | Basically, you need to unpivot the values. There are several ways. This is a pretty easy one:
```
select name
from ngkbm_template_data_sets_ t outer apply
(values ('txt_description_1', txt_description_1),
('txt_description_2', txt_description_2),
. . .
) cols(name, val)
group by nam... | I have a large table with 324 columns, I want to get the list of columns which don't have any values at all | [
"",
"sql",
"sql-server",
""
] |
`Text` column is `NVARCHAR(MAX)` type.
```
ID Text
001 have odds and modds
002 odds>=12
003 modds
004 odds < 1
```
How can I search in Text column contains `odds` and not contain `modds`
I try:
```
Select * from MyTable
Where text LIKE '%odds%' AND text NOT LIKE '%modds%'
```
But result not correct... | ```
WHERE (text LIKE '%odds%' AND text NOT LIKE '%modds%')
OR (text LIKE '%odds%odds%')
```
Some questions regarding how this works. First off, SQL works with "sets" of data so we need a selector (WHERE clause) to create our "set" (or it is the entire table "set" if none is included)
SO here we created two portions ... | ```
Select * from MyTable
Where text LIKE 'odds%'
``` | Find exactly text | [
"",
"sql",
"sql-server",
""
] |
I initially had a web service which ran the first query (post details) and within the while loop of its results, I was running the second query to retrieve the number of comments on a post. I need to try and combine the two as now I am having to order the webservice by number of comments.
```
1. SELECT ReportID, Title... | If I understand your question correctly I think what you want is the following:
```
SELECT Posts.*, count(Comments.ReportID) as CommentCount FROM Posts
LEFT JOIN Comments
ON Comments.ReportID = Posts.ReportID
WHERE private = 0
GROUP BY Comments.ReportID
ORDER BY CommentCount, ReportID Desc;
```
Obviously, you will n... | I don't have the data structures, but i think you could use this, using the count in a sub query
```
SELECT
ReportID, Title, Description, posts.Pic, DatePosted, posts.UserID, FName, SName, users.Pic as userPic,
photoWidth, photoHeight, numComments.numComments
FROM posts
... | join two mysql queries to order the first query by the result of the second | [
"",
"mysql",
"sql",
"join",
"inner-join",
""
] |
I have a table TABLE\_A with one column.
```
select VALUE from TABLE_A;
VALUE
---------
1
2
3
4
5
```
I need a second column which will give me sum of all the values of first colum.
Expected:
```
VALUE SUM
--------- ---------
1 15
2 15
3 15
4 15
5 15
```
I... | It could be easily done using **SUM() OVER()** analytic function.
```
SELECT VALUE,
SUM(VALUE) OVER(ORDER BY NULL) as "SUM"
FROM TABLE_A;
```
**Working demo:**
```
SQL> WITH sample_data AS(
2 -- end of sample_data mocking as real table
3 SELECT 1 VALUE FROM dual UNION ALL
4 SELECT 2 VALUE FROM dual... | Just use a sub-select that counts:
```
select value, (select sum(value) from TABLE_A)
from TABLE_A
```
Or `JOIN`:
```
select t1.value, t2.sum_value
from TABLE_A t1
CROSS JOIN (select sum(value) as sum_value from TABLE_A) t2
```
Does Oracle support `CROSS JOIN` syntax? | select to sum the values of one column to other | [
"",
"sql",
"oracle",
"sum",
""
] |
Says I have `TABLE Audit` with `COLUMN ID, STATUS, TIME` and sample data as below:
```
1. {ID = 1, STATUS = 'APPROVE', TIME = '2015-02-01'}
2. {ID = 1, STATUS = 'DECLINE', TIME = '2014-12-01'}
3. {ID = 1, STATUS = 'CLOSED', TIME = '2015-11-01'}
4. {ID = 2, STATUS = 'APPROVE', TIME = '2015-02-01'}
5. {ID = 3, STATUS = ... | You can use windowed functions:
```
WITH cte AS
(
SELECT *
,[dec] = COUNT(CASE WHEN STATUS = 'DECLINE' THEN 1 END) OVER (PARTITION BY ID)
,[app] = COUNT(CASE WHEN STATUS = 'APPROVE' THEN 1 END) OVER (PARTITION BY ID)
FROM #Audit
)
SELECT ID, STATUS, [TIME]
FROM cte
WHERE NOT ([dec] >= 1 AND [app] >= 1 AND [STATUS] =... | THe idea it is to get all the ones that have been approved and for those skip the declined ones.
I couldn't try right now, but it should work:
```
;WITH App (ID, app) AS
(SELECT ID, COUNT(1) FROM #Audit WHERE STATUS = 'APPROVE' GROUP BY ID UNION
SELECT ID, 0 FROM #Audit WHERE ID NOT IN (SELECT ID FROM #Audit W... | How to select data based on special condition? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I just can't find a solution to my problem:
I have a table employees with id's name and the id they report to.
```
Employees:
id name reports_to
2 name2 55
3 name3 2
4 name4 3
5 name5 3
6 name6 2
7 name7 33
8 name8 55
```
now I need to be able to select the person tha... | You have a hierarchy that has been modelled using the adjacency list model. The advantage of this model is that it is fairly intuitive to the modeller and facilitates updates for the user. However, the disadvantage, as you've discovered, it that it is not so easy to query because you need new a join (or equivalent) for... | Here is one method, using a subquery to get the second level:
```
select e.*
from employees e
where e.reports_to = 55 or
e.reports_to in (select e2.id from employees e2 where e2.reports_to = 55);
```
EDIT:
To get this sorted requires using `join` rather than `in`. I think the logic looks like this:
```
select... | join results from the same table | [
"",
"mysql",
"sql",
""
] |
I have a field that is `varchar(8)`, holding date values that I converted from `float` to `varchar`.
Some records have eight characters, and some have seven. I would like to make them all the same length by adding a leading zero to the ones that have 7.
* 8 char example: 12162003
* 7 char example: 5072004 (needs a le... | A function that will work for more situations would be REPLICATE. It concatenates a value X amount of times to a string.
```
SELECT REPLICATE('0', 8-LEN(birthdate_new)) + birthdate_new AS 8_len_birthdate
```
This will take the length of your birthdate, subtract it from 8, then put that many leading 0's on the front t... | You can use `RIGHT`:
```
SELECT RIGHT('00000000' + birthdate_new, 8) AS birthdate_new
FROM table_name;
```
`LiveDemo`
If you want to `UPDATE` field use:
```
UPDATE table_name
SET birthdate_new = RIGHT('00000000' + birthdate_new, 8)
WHERE LEN(birthdate_new) < 8;
``` | Add leading zeros to a varchar field | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have query written below.
```
SELECT T1.[AcctCode],T1.[Segment_0],SUM(T0.[DebLTotal]) AS BUDGET, SUM(T3.[Debit]) AS DEBIT,
AcctName = CASE WHEN T1.[Segment_0] LIKE '6001%%' THEN 'Operating Cost'
WHEN T1.[Segment_0] LIKE '6002%%' THEN 'Operating Cost'
WHEN T1.[Seg... | If `T1.[Segment_0]` are only numeric value you can use this syntax with `between`:
```
case when substring(T1.[Segment_0], 1, 4) between 6001 and 6006 then 'Operating Cost' else T1.[AcctName] end
```
Else you can use `IN` :
```
case when substring(T1.[Segment_0], 1, 4) in ('6001','6002','6003','6004','6005','6006') ... | Perhaps you issue is that you are including `AcctName` in the `group by` rather than the result of the `case`. Perhaps this does what you want:
```
SELECT T1.[AcctCode],T1.[Segment_0],SUM(T0.[DebLTotal]) AS BUDGET, SUM(T3.[Debit]) AS DEBIT,
AcctName = (CASE WHEN T1.[Segment_0] LIKE '6001%%' THEN 'Operating Cost... | multiple Like expression in sql query using case exprssion | [
"",
"sql",
"sql-server",
""
] |
I am writing a script that query's a table and counts all rows that have a status of 10 and separates the total count by month. Something is
not right considering I have two Decembers in my results.
In November, there is only one date in it meaning two rows have a status of 10 and are under the same date (11-04). Dece... | ```
SELECT LEFT(DATENAME(M, datecomplete), 3) AS Month,
Count(*) AS Val
FROM nwds
WHERE status = 10
GROUP BY LEFT(DATENAME(M, datecomplete), 3)
```
If you have ever get data for different years, you can add the year to the `GROUP BY`.
```
SELECT LEFT(DATENAME(M, datecomplete),... | `datecomplete` should be excluded from `group by`, or the results would be grouped by day. Grouping needs to be on `month` and `year` part of datecomplete column.
```
SELECT
CONVERT(CHAR(3), Datename(month, datecomplete)) AS Month,
count(*) AS Val
FROM nwds
WHERE status = 10
GROUP BY CONVERT(CHAR(3), Datenam... | SQL Sum and Count Separated by Month | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm doing an assignment on SQL Server 2012 where I have to
> 7) Create a stored procedure (call it `SQL7`) which will retrieve the
> Charity ID and Charity Name and the total of all the contribution
> amounts that each charity has in the contribution table."
`Charity ID` and `Charity Name` are in one table and the se... | You'll probably need grouping (assuming table1 holds charity information and table2 holds contribution information)
```
create procedure SQL7
as
select a.charityid, a.charityname, sum(b.totalcontributions) as totals
from CharityTbl a
left join ContributionsTbl b on a.charityid = b.charityid
group by a.charityi... | You need to learn about [Join](http://www.w3schools.com/sql/sql_join.asp)
```
CREATE PROC SQL7
AS
SELECT
charity.CharityID
,charity.CharityName
SUM(contrib.TotalContrib)
FROM
dbo.CharityTbl AS charity
INNER JOIN dbo.ContributionsTbl AS contrib
ON contrib.CharityID = charity.C... | SQL Server 2012 add value of rows with matching ids | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
SQL Server
I have a parameter that contains a comma delimited string:
> 'abc,def,ghi'
I want to use that string in a IN statement that would take my parameter like this:
```
select * from tableA where val IN ('abc','def','ghi')
```
Any ideas on how I would do this? | If using dynamic SQL is an option, this can be executed:
```
SELECT 'SELECT * FROM tableA WHERE val IN (' +
'''' + REPLACE('abc,def,ghi', ',', ''',''') + ''')'
```
Basically, the `REPLACE()` function separates each item by **','** instead of just **,**. | The simplest way would be to do something like this:
```
SELECT *
FROM TableName
WHERE ',' + commaDelimitedString + ',' LIKE '%,' + FieldName + ',%'
```
But be careful about SQL injection. You might want to parameterize it. | SQL IN Statement splitting parameter | [
"",
"sql",
"sql-server",
""
] |
I am trying to calculate the standard deviation of multiple columns for each given ID.
I have a table that shows gives me demand over time and I need to calculate volatility of the demand.
```
SELECT id ::Text, n0 ::numeric, n1 ::numeric, n2 ::Numeric, n3 ::numeric, n4 ::numeric, n5 ::numeric, n6 ::numeric, n7 ::nume... | Have you tried [stddev\_samp](http://www.postgresql.org/docs/9.4/static/functions-aggregate.html)? Or do you mean the standard deviation **between** columns? If so, take a look at [this SO question](https://stackoverflow.com/questions/23596515/aggregate-functions-across-multiple-columns-in-postgres). | Hmmm. Probably the easiest way is to unpivot the table and re-aggregate. For instance:
```
select id, stddev(n)
from ((select id, n0 as n from mytable) union all
(select id, n1 as n from mytable) union all
(select id, n2 as n from mytable) union all
(select id, n3 as n from mytable) union all
(... | Postgres Standard deviation of multiple columns | [
"",
"sql",
"postgresql",
""
] |
I am new to SQL and I want to write a query to add multiple rows in a table.
For example:
Table:
```
matchid|player1id|player2id|player1score|player2score
101 |20 |10 |0 |100
101 |20 |10 |0 |100
101 |20 |10 |0 |100
201 |20 |10 ... | Without using `GROUP BY`:
```
SELECT *
FROM (
SELECT DISTINCT matchid, player1id, player2id FROM tbl
) AS t
CROSS APPLY(
SELECT
SUM(player1score), SUM(player2score)
FROM tbl
WHERE
matchid = t.matchid
AND player1id = t.player1id
AND player2id = t.player2id
) AS x(player1s... | ```
SELECT
matchid, player1is, player2id,
SUM(player1score) as player1score,
SUM(player2score) as player2score
FROM
tablename
GROUP BY
matchid, player1id, player2id
``` | add specific multiple rows (SQL) | [
"",
"sql",
"sql-server",
""
] |
I am using SQL Server to create my database.
I want to add a column to my Table which would calculate the number of NULL values in each row, like this:
```
Column1 | Column2 | Column3 | Score
a | B | C | 0
x | NULL | NULL | 2
```
Currently, I have this:
```
Column1 | Column2 | Colu... | You could use a computed column - a virtual column that is always computed with a given expression, and not stored on disk. This way, you avoid problems with data consistency. The syntax is easy:
```
CREATE TABLE myTab
(
column1 datatype
, column2 datatype
...
, Score AS CASE WHEN Column1 IS NULL THEN 1 ELSE 0... | It's generally a bad idea to store calculated values depending on other columns. (Data redundancy, risk of data inconsistency.) Create a view instead:
```
create view MyView as
SELECT column1, column2, column3,
CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END +
CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END +
... | Join the result of a Temp column to a table SQL Server | [
"",
"sql",
"sql-server",
""
] |
My task is to rebuild database structure from queries found in code, these are queries that I have found:
Query 1:
```
Select o.id, n.nazwa, n.nazwa, n.typ, o.kwota, o.pozostala_kwota, o.pozostale_raty
from oplaty o
inner join wlasciciel w on w.id = o.id_wlasciciela
inner join nieruchom... | After table name `oplaty` you have alias `o` and expression `select o.id` means that you want to select `id` from table with `o` alias so it'll be `id`from table `oplaty`.
You can use alias with the key word 'AS' or without.
For more informations see page:
<http://dev.mysql.com/doc/refman/5.7/en/select.html> | The "o" and the "w" are simply aliases for the table name. At this point, I'd say you need to take time on an SQL Tutorial, such as: <http://www.w3schools.com/sql/>. | How to rebuild database from queries | [
"",
"mysql",
"sql",
""
] |
I am facing the following problem.
I have a database with a table which saves Dates (with its time).
Now I would like to know all the tables information where the date is in between two timestamps, but I am getting the following error:
01830. 00000 - "date format picture ends before converting entire input string".
W... | Try this statement (using Oracle syntax)
```
SELECT *
FROM ARBEITSBLOCK
WHERE STARTZEIT BETWEEN TO_DATE ('12/04/2015 09:00:00 AM', 'mm/dd/yyyy hh:mi:ss AM')
AND TO_DATE ('12/04/2015 10:00:00 AM', 'mm/dd/yyyy hh:mi:ss AM');
``` | If STARTZEIT is a DATE column, then why are you trying to compare it to a string?
By doing that, you are relying on Oracle being able to say "aha! This string is really a date, so I will attempt to convert it for you!". That's all well and good, but how will Oracle know how the date-in-the-string is formatted?
Well, ... | Select date from between two timestamps | [
"",
"sql",
"oracle",
"date-arithmetic",
""
] |
This is probably a really basic question but I have spend a lot of time on this.
I have 2 Tables:
**Files**
```
| FileId | Type | FolderId |
----------------------------
| 1 | txt | 11 |
| 2 | xml | 15 |
| 3 | xml | 17 |
| 4 | txt | 19 |
```
**Folders**
```
| FolderI... | You didn't specify a verson of SQL Server.
```
select Files.*
from
Files inner join
(
select f1.FolderId
from Folders f1 inner join
(
select TypeId, Path, max(Version) as MaxVersion
from Folders
group TypeId, Path
) as f2
... | Give this a shot:
```
select f.*
from files f
inner join folders dir on f.folderid = dir.folderid
inner join (
select type, max(version) maxver
from files fi
inner join folders fo on fi.folderid = fo.folderid
group by type
) t on f.type = t.type and dir.version = t.maxver
```
Result:
```
| fileid | type | fo... | SQL: Getting items which have a max value in another tables column, but also match some cross table clauses | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I am creating a file orginization system where you can add content items to multiple folders.
I am storing the data in a table that has a structure similar to the following:
```
ID TypeID ContentID FolderID
1 101 1001 1
2 101 1001 2
3 102 1002 ... | `MIN()` and `MAX()` should return the same amount of rows. Changing the function should *not* change the number of rows returned in the query.
Is this query part of a larger query? From looking at the sample data provided, I would assume that this code is only a snippet from a larger action you are trying to do. Do yo... | Use ROW\_NUMBER
```
WITH CTE AS
(SELECT ID,TypeID,ContentID,FolderID,
ROW_NUMBER() OVER (PARTITION BY TypeID,ContentID ORDER BY ID) as rn FROM t
)
SELECT ID FROM CTE WHERE rn=1
``` | Using GROUP BY, select ID of record in each group that has lowest ID | [
"",
"sql",
"sql-server",
"select",
"group-by",
"min",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.