Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Concepts Banking Example
```
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
loan (loan_number, branch_name, amount)
depositor (customer_name, account_number)
borrower(customer_name, loan_number)
```
Find all customers w... | So you're selecting the `customer-name` from the `depositor` table where:
1. You're getting the `branch-name` for all branches in Brooklyn: `(select branch-name from branch where branch-city = ‘Brooklyn’)`
2. You're getting all of the `branch-name`s in Brooklyn for which that particular customer has an account at: `(s... | Note: it will probably be easier to understand queries if format them so they read more easily.
```
-- get the unique customer names
select distinct S.[customer-name]
--from all all depositors
from depositor as S
--where there the are no brooklyn branches that don't have an account for that customer
where no... | advanced sql query using join | [
"",
"sql",
"database",
""
] |
I have a table which contains sensor data `data1` and the allowed (alarm) limits for that sensor data `data1high` and `data1low`. I wish to create a view where only those data1 values are listed which are the first to move outside the limits (i.e. an alarm condition) or moved back in within "safe" limits (alarm conditi... | You can use a [Recursive CTE](https://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) to iterate over the rows and compare one row to the previous row, applying the logic of what you classify as a transition.
Looking at your desired output though, I don't think `id = 10` should appear in the list as ... | If you're using SQL-Server 2012, you can use the `LAG` function:
If I understood your problem correctly, you want to get all records that changed from being in alarm to not being in alarm. If that is the case, shouldn't be 11 not in the result set? The last change is 8. Records in between ( 9 and 10) is still in alarm... | SQL conditional Where with limits and previous value | [
"",
"sql",
"sql-server",
""
] |
My problem is similar to this one:
[how to maintain order while doing join in sql](https://stackoverflow.com/questions/5743373/how-to-maintain-order-while-doing-join-in-sql)
Basically I have a table parameter in a stored procedure that contains some IDs in a particular order. I want to use those IDs in an inner join a... | I have tried using IDENTITY on a column, but it seems that the DataTable class that I used didn't allow inserting rows with less columns than the number of columns the table had (so that I could not omit the IDENTITY column when inserting data and let it auto-increment).
What I did instead, was providing the rank colu... | 1. Add `identity` seed enabled column to your input table now, column will be automatically populated with physical order they are inserted into.
2. Use this column to sort after join | sql server - inserting rank column in SP table-parameter | [
"",
"sql",
"sql-server",
"sql-order-by",
""
] |
How do I code format the return data in 2 decimals and with percentage format like 100.00% or 67.39% instead of 100.000000 or 67.391304?
```
SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46 as 'C%'
```
I tried `ROUND()` but I got the error stating that the round function requires 2 to 3 arguments?
```... | You can convert to a decimal your original value:
```
CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,2), SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46) ) + '%' as 'C%'
```
The first number in the decimal represents the number of digits in the number including decimal places, and the second number represent... | Using Round and Cast will work. First round to 2 decimal places then convert to a decimal with 2 places to truncate the excess zeros.
```
select cast(Round(yourValue, 2) as decimal(18,2))
```
[Sql Fiddle](http://sqlfiddle.com/#!3/9eecb7db59d16c80417c72d1/624) | How to format % and in 2 decimal points? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
GUYS I KNOW (+) MEANS OUTER JOIN
```
SELECT *
FROM email a,email_types b
WHERE a.user_id (+) =10
AND a.email_id(+)=b.email_enum;
SELECT *
FROM email a,email_types b
WHERE a.user_id =10
AND a.email_id(+)=b.email_enum;
```
What is the meaning of `a.user_id (+) = 10`? Is this equal to `a.user_id =10`, or ... | This is best explained by converting the Oracle syntax to standard SQL:
```
SELECT *
FROM email a,email_types b
WHERE a.user_id (+) =10
AND a.email_id(+)=b.email_enum;
```
is equivalent to:
```
SELECT *
FROM email_types b
LEFT JOIN email a ON a.email_id = b.email_enum AND a.user_id = 10;
```
Which means "d... | The `(+)` syntax is Oracle's old, outdated, syntax for an implicit outer join. The side with the `(+)` is the side that may not have matches, so this query will return all records with `b` with their counterparts in `a` where `a.user_id = 10`, or with `null`s if there's no matching `a` record. | What is the meaning of the query? | [
"",
"sql",
"database",
""
] |
I have a daily schedule process flow which refreshes a bunch of tables within the same library. At the end of the process flow, all tables should have the same up to date records. And I want to double check this via checking the maximum value of `date`.
But problem is, how can I quickly extract all max value of date a... | Create a view that appends all the tables with the date variable and select the max date from the variable. If your tables don't have the same structure you can modify the set statement to keep only the date variable. You may want to anyways to speed up the process.
```
data max_date/view=max_date;
set table: indsn... | In plain SQL it would look like
```
select 'table1' table_name, max(date) max from lib.table1
union all
select 'table2' table_name, max(date) max from lib.table2
union all
select 'table3' table_name, max(date) max from lib.table3
```
Other options are stored procedures, in-line views and probably more. | select maximum value of common column for multiple data set | [
"",
"sql",
"sas",
""
] |
I've got some date/time data in a string, in the format '26/10/2009 09:06:43' (i.e. the date is in UK format). When I try
```
SELECT CAST('26/10/2009 09:06:43' AS DATETIME)
```
I get the following error:
> The conversion of a char data type to a datetime data type resulted in
> an out-of-range datetime value.
I'm s... | Try with `convert` function instead providing style number:
```
SELECT convert(DATETIME, '26/10/2009 09:06:43', 103)
```
You can find out all formats here: <http://www.sqlhub.com/2009/04/list-of-all-available-datetime-format.html> | In oracle it's like that :
```
SELECT to_date('26/10/2009 09:06:43', 'DD/MM/YYYY HH24:MI:SS') from dual;
```
with a following site :
<http://www.sqlines.com/oracle-to-sql-server/to_date>
It's seems to be like this in sql server :
```
SELECT CONVERT(DATETIME, '26/10/2009 09:06:43');
``` | SQL - Converting a non-standard String to DateTime | [
"",
"sql",
"sql-server",
""
] |
I need to get the records of the last 24 hours but not group by hour like this:
```
SELECT HOUR(CompDate) AS hour, COUNT(1) AS action
FROM mytable
WHERE ((CompDate >= DATE_SUB(NOW(), INTERVAL 24 HOUR))
GROUP BY `hour`;
```
The above query will tell me that: hour 22 --> 6 actions, hour 21 --> 9 actions.
What I want t... | You can do It in following:
```
CREATE TABLE Test
(
`Id` INT,
`DateTimes` DATETIME
);
INSERT INTO Test(Id, DateTimes) VALUES (1, '2015-06-09 10:12:12'), (2, '2015-06-09 10:13:12'), (3, '2015-06-09 09:12:12'), (4, '2015-06-09 09:15:12'), (5, '2015-06-09 08:15:10')
SELECT TIMESTAMPDIFF(HOUR,NOW(),DateTimes) * -1 AS... | I guess the only change you need to do is to convert your HOUR to the difference between NOW and the CompDate:
```
SELECT HOUR( timediff( NOW( ) , CompDate) ) AS HOUR , COUNT( 1 ) AS action
FROM mytable
WHERE CompDate > DATE_SUB( NOW( ) , INTERVAL 24 HOUR )
GROUP BY HOUR
ORDER BY HOUR
``` | Get records of last hour, last 2 hours.....last n hours | [
"",
"mysql",
"sql",
"database",
""
] |
There is a column in my Table. In which we are storing string value in format `'HH:MM'`.During fetching records with this table every things works ok with
```
DATEDIFF(MINUTE, '00:00', ColumnName)
```
Problem is when we have Value greater than `23:59`.
Its showing error like
> Conversion failed when converting date ... | So it sounds like your saving the length of a time period. Try storing it in minutes. My query can handle numbers of different lengths since it's based on the colon.
```
DECLARE @yourTable TABLE (ColumnName VARCHAR(10));
INSERT INTO @yourTable
VALUES ('100:00'),
('24:20');
SELECT ColumnName,
(hr * 6... | If you are storing the value as something other than a time, why not just store the number of minutes and convert to whatever format you want on output?
Otherwise, I would suggest that you simply convert the value to minutes:
```
select (cast(left(ColumnName, 2) as int) * 60 +
cast(right(ColumnName, 2) as int... | How to Handle DATEDIFF(MINUTE, '00:00', '24:20') Like scenario? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
```
SELECT cust_email FROM customer AS c WHERE c.cust_email="pankaj@yahoo.com"
SELECT cust_email FROM customer WHERE cust_email="pankaj@yahoo.com"
```
I have these 2 sql queries which perform same operation ,my question is what is the use of giving customer a another name for selecting data ? | It is so called alias. In your case, it is not required.
It is used to make querying easier when current names are inconvenient, ambigious or unknown (for group functions).
1. Example with ambigiousness in JOIN query. Let we have two tables:
**Users**
```
Id int (PK)
Name nvarchar(50)
```
**Books**
... | When querying from a single table, using an alias is really not necessary (but it's good practice to get used to using it.)
When querying multiple tables, joining etc (specially when the same table is referenced multiple times), it is needed.
```
select * from Customer c join Email e on e.cust_id = c.id
```
Also, it... | Diffrence between these select queries | [
"",
"mysql",
"sql",
""
] |
I have query like below:
```
SELECT COUNT(*) AS AppleSupports
FROM VendorItemPricing
WHERE VendorName = 'Apple'
SELECT COUNT(*) AS HpSupports
FROM VendorItemPricing
WHERE VendorName = 'HP'
```
Above queries give me results like below:
```
AppleSupports
63
HpSupports
387
```
How can make my query to get result... | Use sub-queries inside your select statement:
```
SELECT
(select count(*) from VendorItemPricing where VendorName = 'Apple') as AppleSupports,
(select count(*) from VendorItemPricing where VendorName = 'HP') AS HpSupports
``` | ```
Select Sum(Case When vp.VendorName = 'Apple' Then 1 Else 0 End) As AppleSupports
,Sum(Case When vp.VendorName = 'HP' Then 1 Else 0 End) As HpSupports
From VendorItemPricing As vp With (Nolock)
Where vp.VendorName In ('Apple','HP')
``` | Merge two SQL query results into one result | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
In PostgreSQL, I would like to select a row based on some criteria, but if no row matches the criteria, I would like to return the first row. The table actually contains an ordinal column, so the task should be easier (the first row is the one with ordinal 0). For example:
```
SELECT street, zip, city
FROM address
WHE... | > I would like to select a row based on some criteria, but if no row
> matches the criteria, I would like to return the first row
## Shorter (and correct)
You don't actually need a `WHERE` clause *at all*:
```
SELECT street, zip, city
FROM address
ORDER BY street !~~ 'Test%', ord
LIMIT 1;
```
`!~~` is just the ... | You are on the right track. Just add an `order by`:
```
SELECT street, zip, city
FROM address
WHERE street LIKE 'Test%' OR ord = 0
ORDER BY (CASE WHEN street LIKE 'Test%' THEN 1 ELSE 0 END) DESC
LIMIT 1;
```
Or, alternately:
```
ORDER BY ord DESC
```
Either of these will put the `ord = 0` row last.
EDIT:
Erwin br... | Select first record if none match | [
"",
"sql",
"postgresql",
"sql-limit",
""
] |
I have a table containing an identity column as well as a column representing the creation date:
```
CREATE TABLE dbo.OrderStatus
(
OrderStatusId int IDENTITY(1, 1) NOT NULL,
CreationDate datetime NOT NULL default GETDATE(),
CONSTRAINT PK_OrderStatus PRIMARY KEY(OrderStatusId)
)
```
Since the identity col... | You can use your original definition and just use a while loop, for example
```
DECLARE @OrderStatus TABLE
(
OrderStatusId int IDENTITY(1, 1) NOT NULL,
CreationDate datetime NOT NULL DEFAULT GETDATE()
--CONSTRAINT PK_OrderStatus PRIMARY KEY(OrderStatusId) -- this can be uncommented if creating a real tabl... | An easier way is:
```
insert dbo.OrderStatus default values
go 500
```
this will insert 500 rows of default values. | How to insert N rows of default values into a table | [
"",
"sql",
"sql-server",
"t-sql",
"insert",
""
] |
I'm looking for an SQL (MSSQL) tool that will allow me to edit/insert/etc. data without the need to type sql statements. I want to simply enter data into a grid. I can't find this functionality in SSMS. Is there any tool that does that (preferably by MS)? | ## Table Editor
If you right-click on a table in SSMS and click edit, you can edit the data in there directly.

---
## Query Designer
If you select a row or cell in the table editor, you have access to the Query Designer menu on the tool bar. By clicking on the p... | SSMS does let you do it, although it's not a great tool by any stretch. If you right click on a table and go to Edit Top 100 rows, you can get the grid. If you want to be able to edit any number of rows, go to Tools -> Options -> SQL Server Object Explorer -> Commands and change both values in the Table and View option... | Is there an SQL editor for the data itself? | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I want to copy values from a `bit` column called "absent" in table `Person` to a new, empty `datetime` column I just made.
The `bit` type column contains rows with values null, 0 and 1.
Now, I'd like to copy the values of this `bit` column to the new `datetime` column so, that all null AND 0 values in the `bit` colum... | Well, you can do it like this:
```
update Person
set dateTime_Column = case when isnull(absent, 0) = 0 then null else getdate() end
``` | Try this:
```
update someTable
set dateColumn = case when bitColumn is null or bitColumn = 0 then null else getdate() end
``` | How to copy values from bit column to datetime column? | [
"",
"sql",
"sql-server",
"datetime",
"sql-server-2012",
""
] |
I have a Table like this.
```
NoteID CustomerID CustomerName Note Type Date Active
6 81 Paris test Info 2015-06-04 1
10 81 Rotterdam Everything is allright Comment 2015-06-04 1
11 81 Hamburg Everyt... | Sure. It's called operator precedence (or more generally, operator evaluation order).
If you add parentheses, this is what you're evaluating:
```
WHERE ((Note LIKE '%ddddddddddddddd%') AND Type != 'Comment') OR Type != 'error'
```
As per MSDN:
> When more than one logical operator is used in a statement, NOT is eva... | You have two options:
1. wrap the `OR` in paranthesis
2. repeat the `AND` + `OR`
First approach(\*):
```
SELECT *
FROM CarsNote
WHERE Note LIKE '%ddddddddddddddd%'
AND (Type != 'Comment' OR Type != 'error')
```
Second:
```
SELECT *
FROM CarsNote
WHERE Note LIKE '%ddddddddddddddd%' AND Type != 'Comment'
OR No... | Combination AND OR result | [
"",
"sql",
"sql-server",
""
] |
I have read many posts related to this issue but unfortunately none of the suggested solutions worked for me.
I am trying to set up a SQL statement that would create a column in my results table with values formatted as follows:
date + 8 digit number incremented by 1 for each new record and prefixed with leading zero... | You are on the right path, just need a little push...
Try this:
```
SELECT CONVERT(varchar(10), GETDATE(), 112) +
RIGHT('0000000'+
CAST( ROW_NUMBER() OVER(ORDER BY t_Id) As varchar(8))
,8)
FROM MY_TABLE
``` | Try this:
```
SELECT
'aaa',
CONVERT(VARCHAR(10),GETDATE(),112) +
RIGHT('0000000' + CAST(ROW_NUMBER() OVER (ORDER BY id) AS VARCHAR(8)), 8)
FROM yourTable
```
Concatenate the result from `ROW_NUMBER` with 7 `'0'`s so as to be sure that you will always have *at least* 8 digi... | How to increment and format integer in results table in SQL Server 2008? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
this is my data and I need the result with the fastest way.
 | Standart conditional aggregation:
```
select city,
sum(case when active = 'true' then 1 else 0 end) active,
sum(case when blacklist = 'true' then 1 else 0 end) blacklist,
sum(case when license = 'true' then 1 else 0 end) license,
sum(case when married = 'true' then 1 else 0 end) married
fro... | this gives output you are expecting
```
declare @t table (code int,name varchar(10),Active varchar(5),Black varchar(5),License varchar(5),married varchar(5),city int)
insert into @t (code,name,Active,Black,License,married,city)values (1,'john','true','false','true','true',1001),
(2,'jack','true','true','true'... | Get count by multiple condition | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have the following SQL
```
SELECT
a.StudentsID,
a.ClassGroup,
a.FinalGrade,
COUNT(*) AS ranknumber
FROM FinalAVG AS a
INNER JOIN FinalAVG AS b
ON (a.ClassGroup = b.ClassGroup)
AND (a.FinalGrade <= b.FinalGrade)
GROUP BY
a.ClassGroup,
a.StudentsID,
a.FinalGrade
HAVING COUNT(*) <= 3
ORDER BY a.ClassGroup,... | That's by design and a limitation of the GUI designer.
However, the SQL view is available for this type of queries.
Yes, just go ahead and correct errors if any. As is, your SQL seems valid. | Ms Access Design view can only handle queries where both path part of the join are of the same datatype and there is equality between them e.g
```
ON A.ID = B.ID
```
But on the SQL view you can do a;l kind of associations..a very common case is when one part is of String DataType (but numeric) and the other is Integ... | Microsoft Access can't represent the join expression "<=" operators | [
"",
"sql",
"ms-access",
"ms-access-2013",
""
] |
As I asked in this question : [Oracle SQL Group By if](https://stackoverflow.com/questions/30709480/oracle-sql-group-by-if) I log file usage in my application. There is 3 files sources:
* Pool
* MDA
* Other
If the file is opened twice from MDA and once from Pool, I'll get two entries:
```
TESTID SITE LA... | There's a few ways to do that and what is possible or best depends in part on you RDBMS. However, here is one way. I am substituting you query above with an IntermediateResults table for simplicity. In practice you could use your query with a CTE, derived table, temp table or table variable.
```
CREATE TABLE Intermedi... | Starting by the top you don't need a UNION ALL Query, you could retrieve your data with this query.
I omitted the range period for easy read.
```
SELECT COUNT(TESTID) AS OTHER_FILES,SITE
,CASE WHEN FILE_ORIGIN_ID < 2 THEN 'Files that are at least in Pool or MDA' ELSE 'OTHERS' END AS validCondition
FROM FILE_USAGE_LOG... | Percentage with union all request | [
"",
"sql",
"oracle",
"union-all",
""
] |
I have two tables `t1` and `t2`.
`t1` has this structure:
```
yearmonth
account
company
RCV_amount_t1
```
`t2` has this structure:
```
yearmonth
account
company
billing amount
billing amount CM_1
billing amount CM_2
RCV_amount_t2
```
I want to join `t2` to `t1` using `yearmonth`, `account`, and `company`. If they... | You'll want to use a [`MERGE`](https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm).
It allows you to join two tables and specify how to update the values if they match.
The general structure of a `MERGE` statement looks like:
```
MERGE INTO driver_table
USING other_table
ON
(
driver_tabl... | > I want to join t2 to t1 using yearmonth, account, and company. If they
> match, I want to update RCV\_amount\_t2 with the value in RCG\_amount\_t1.
> Otherwise, I want to set RCV\_amount\_t2 to spaces.
This will update the matching rows with the appropriate value, and update the rows with no match to `NULL`. If the ... | Table update based on match/nomatch | [
"",
"sql",
"oracle",
"join",
"sql-update",
""
] |
I have student marks in one database table, like
```
studid, studname, m1, m2, m3
```
and students' personal information in another database table, like
```
studid, studname.
```
* I want to join both tables to get studid, studname, ((m1,m2,m3) must be sum as 'total').
The students' results must display if m1,m2... | ```
select ID, Name, CASE WHEN total > 40 THEN 'Pass' ELSE 'fail' end from
(select m.studid as ID, m.studname as Name, sum(m1)+sum(m2)+sum(m3) as total from marks m NATURAL JOIN info i group by studid,studname )
``` | try this,
```
select studID, Studname, m1, m2, m3, (m1+ m2+ m3) as 'Total',
case
when(m1<40 OR m2<40 OR m3<40)
then 'FAIL'
else 'PASS'
end as 'Result'
```
it should work. you can join 2 tables to produce the desire results | How to find ranks for only students who got pass marks? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
One of the [core rules](http://en.wikipedia.org/wiki/Codd%27s_12_rules) for the relational model is the required uniqueness for tuples (rows):
> Every individual scalar value in the database **must** be logically addressable by specifying the name of the containing table, the name of the containing column and the **pr... | You're assuming that databases are there solely for storing relational data; that's certainly not what they're used for because practical considerations will always win.
A obvious example where there's no need for a primary key would be a "state" log of some description (weather/database/whatever). If you're never goi... | The short answer is that SQL is not relational and SQL DBMSs are not relational DBMSs.
Duplicate rows are a fundamental part of the SQL model of data because the SQL language doesn't really try to implement the relational algebra. SQL uses a bag (multiset)-based algebra instead. The results of queries and other operat... | Why does SQL standard allow duplicate rows? | [
"",
"sql",
"relational-database",
""
] |
How to check if there exist only one record for a certain Id
I have two tables called `Tbl_Company` and `Tbl_Employee`
I am fetching employees as follows-
```
SELECT DISTINCT emp.employee_id
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.comp... | I have solved this by using ans by `@davegreen100` in comment
```
SELECT comp.companyid, count(distinct emp.employee_id),
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.company_id = 1234
GROUP BY comp.companyid
```
This will give me the coun... | this would return one row per company
```
SELECT comp.companyid, max(emp.employee_id) lastEmployeeID
FROM Tbl_Company comp
, Tbl_Employee emp
WHERE
emp.company_id = comp.company_id
AND emp.company_id = 1234
GROUP BY comp.companyid
``` | How to check if there exist only one record for a certain Id | [
"",
"sql",
"oracle",
"oracle10g",
"distinct",
""
] |
I have a cursor C1 which selects column status from table test.
Using `for` loop, I have to check the previous value for status is `ERROR` and current value for status is `VALID`.If so then I have to update table `test1`.
E.G.
```
for 1 in 1..c1 loop
if previous.status = ERROR and current.status then
update tes... | To my understanding, this should do the work for your with minor changes:
```
declare
v_previous_status test.status%type;
cursor c1
is
select status
from test;
begin
open c1;
fetch c1 bulk collect into l_status;
for i in 1..l_status.count
if (v_previous = 'ERROR' and l_status(i) = 'VALID' ) t... | You would DECLARE your cursor. DECLARE a variable to hold the previous value.(Set a default because there is no previous at this point) OPEN your cursor. FETCH your first record. Then you would WHILE loop over the rest of the records. At the end of each WHILE loop you'll do another FETCH. So you want to set the variabl... | How to store previous value and current value in for loop | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have the following table:

From a `select` statement what I want is the latest unique rows (in green) for each `policy`. Some cause the `policy` information will be from the day before (all `policies` will not be published on the same day) .
In this scenario `ACB1`... | This will get the latest row for each policy by id column:
```
SELECT id, policy, first, last, amount, created
FROM yourtable yt
INNER JOIN
(SELECT policy,MAX(id) as id
FROM yourtable
GROUP BY policy) maxid ON yt.policy = maxid.policy
... | Use `row_number` window function:
```
select * from
(select *, row_number() over(partition by policy order by id desc) rn from TableName) t
where rn = 1
``` | selecting latest result from a table using SQL query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm facing a logic issue with my Query.
I have two tables **`Table1`** and **`Table2`**, where `Table1` consists of:
* `value` *to be summed*
* `Id` *to be grouped by*
* `Code` *holds foreign-key to `Table2`*
And `Table2` consists of
* `Code`
* `Des` *the text description of code*
What I'm trying to do is, group b... | You have somehow to show the value pair `(D,2)` eg. by making a code list with possible values and translating `NULL` to `0`:
```
SELECT code.code,
code.id,
des.des,
NVL (SUM (val.value), 0) sum_val
FROM (SELECT 'A' code, 1 id FROM DUAL
UNION
SELECT 'A', 2 FROM DUAL... | If you want all the combinations of id and value, then use `cross join` to get the rows and a `left join` to bring in the rest of the values:
```
select t2.code, i.value, t2.desc, coalesce(cnt, 0) as cnt
from (select distinct id from table1) i cross join
table2 t2 left join
(select id, value, count(*) as cnt... | Full Join on Group | [
"",
"sql",
"oracle",
"oracle10g",
"full-outer-join",
""
] |
This is how my articles table looks like: (tbl\_articles)
```
ID | SHORT_DESCRIPTION | DESCRIPTION | GROSS | NET
1 | v00556 | valve washroom | 9.00 | 7.49
```
etc.
My supplier provided me a new price list, in this format (tbl\_supplier)
```
SHORT_DESCRIPTION | DESCRIPTION | GROSS | NET
v0056 ... | Create a unique index on `short_description`:
```
create unique index idx_articles_shortdesc on articles(short_description);
```
Then use `insert . . . on duplicate key update`:
```
insert into tbl_articles(SHORT_DESCRIPTION, DESCRIPTION, GROSS, NET)
select s.SHORT_DESCRIPTION, s.DESCRIPTION, s.GROSS, s.NET
... | Assuming the `SHORT_DESCRIPTION` field is an actual primary/unique in the table, the easiest thing to do would be to have an `insert` statement with an `on duplicate key update` clause:
```
INSERT INTO tbl_articles
(short_description, description, gross, net) -- Assumes ID is autogenerated
SELECT short_description, d... | Update prices in mysql | [
"",
"mysql",
"sql",
"sql-update",
"sql-insert",
""
] |
I am running a very basic select against an oracle database (not sure of the version).
```
SELECT * FROM ACCOUNTING WHERE ID = 123456 ORDER BY DATE
```
I want to return only the most recent record. So I have tried ...
```
SELECT ROWNUM, * FROM ACCOUNTING WHERE ID = 123456 ORDER BY DATE
SELECT * FROM ACCOUNTING WHERE... | Your **actual** query might be using `ROWNUM` within double quotes. Otherwise, this error is not possible.
Though your first query would be `ORA-00936: missing expression`
```
select * from dual WHERE "ROWNUM" < =3;
Error report -
SQL Error: ORA-00904: "ROWNUM": invalid identifier
00904. 00000 - "%s: invalid identi... | Can try this approach:
```
SELECT * FROM
(SELECT ROWNUM R, * FROM ACCOUNTING WHERE ID = 123456 ORDER BY DATE
) WHERE R < 2;
``` | ROWNUM returns as "invalid identifier" | [
"",
"sql",
"oracle",
"odac",
""
] |
find below my HQL query
```
Query query = session.createQuery("select u from UserLog u where u.userLogSerialno = " + "(select max(uu.userLogSerialno) from UserLog uu where uu.userId = u.userId)");
```
This query is working fine but in this, I want to pass the value of userId but I am not able to figure out how to do... | I is very simple to add parameter to an HQL
```
Query query = session.createQuery("select u from UserLog u where u.userLogSerialno = " + "(select max(uu.userLogSerialno) from UserLog uu where uu.userId = :userId)").setParameter("userId", 15);
```
here i have hard coded 15 you can simply use variable instead of it | Simple example:
```
Integer id = 1;
Query query = session.createQuery("from Employee e where e.idEmployee=:id");
query.setParameter("id", id);
``` | How to pass parameter in HQL query | [
"",
"sql",
"hibernate",
"hql",
""
] |
In sql (MS sql server specifically) is it possible to combine multiple rows into a single string as an expression which is itself part of an update that is being applied to multiple rows. I have come across the approaches of using COALESCE or FOR XML PATH (e.g. [How to get multiple rows into one line as a string?](http... | The problem you have is that in the SET stage of your query you only have access to one of the matching Launches as there is no grouping applied.
You can achieve want you want by moving your Launch lookup into a sub-query over the ProjectOutput rows. A simplified example:
```
UPDATE ProjectOutput
SET LaunchNamesColum... | It's a little bit difficult to understand your SQL without description of the tables, but what you should do is have the query with the XML path so that it returns only those items that you want to be concatenated for that single row, so my guess is that you want actually something like this:
```
UPDATE O
SET LaunchNa... | Sql: How to combine multiple rows into a string as an expression within an update | [
"",
"sql",
"sql-server",
""
] |
I'm a beginner to SQL so this is quite possibly a very simple question. I have a table with postage service information like so:
```
ID Service Max_Weight Cost
----------------------------------------
1 SecondClassStandard 0.10 0.95
2 SecondClassStandard 0.25 1.19
3 SecondClassStandard ... | I think you meant to use [`LIMIT`](https://www.sqlite.org/lang_select.html) clause like
```
SELECT * FROM table
WHERE Service = 'SecondClassStandard'
AND Max_Weight >= 0.075
LIMIT 1;
``` | You need to use `LIMIT` to just get the first row
```
SELECT * FROM table WHERE Service = 'SecondClassStandard' AND Max_Weight >= 0.075 LIMIT 1;
SELECT * FROM table WHERE Service = 'SecondClassStandard' AND Max_Weight >= 0.105 LIMIT 1;
``` | SQL Selecting the minimum value after a WHERE clause | [
"",
"sql",
"sqlite",
""
] |
I need to compare the value in a single column in a single table. Here is a sample table:
```
ID Cat Color
======================
1 red maroon
2 red orange
3 red pink
4 blue violet
5 blue purple
6 blue indigo
7 green puke green
8 green hunter green
```
I am given 2 colors... | In addition to [Beginner's answer](https://stackoverflow.com/a/30716806/477563), it's possible to solve this problem without a `GROUP_CONCAT`:
```
SELECT cat
FROM foo
WHERE color IN ('maroon', 'orange')
GROUP BY cat
HAVING COUNT(*) = 2
;
```
This works by selecting all cats with the specified colors. When we group th... | You can try this:
```
SELECT x.cat
FROM (
SELECT cat, GROUP_CONCAT(color) AS colors
FROM tablename
GROUP BY cat) AS x
WHERE FIND_IN_SET('maroon', x.colors) > 0
AND FIND_IN_SET('orange', x.colors) > 0
```
> **Edit 1:** Another Alternative
```
SELECT IF(
FIND_IN_SET('maroon', GROUP_CONCAT(color)) > ... | Compare Two Values in Same Column | [
"",
"mysql",
"sql",
""
] |
I am using sql server 2008 r2 and I have two database, which is one have 11.000 record and another is just 3000 record, when i do run this query
```
SELECT Right(rtrim(tbltransac.No_Faktur),6) as NoUrut,
tbltransac.No_Faktur,
tbltransac.No_FakturP,
tbltransac.Kd_Plg,
Tblcust.Nm_Plg,
... | as already mentioned before, you have three issues in your query.
Just as an example, change the query to this one:
```
SELECT Right(rtrim(tbltransac.No_Faktur),6) as NoUrut,
tbltransac.No_Faktur,
tbltransac.No_FakturP,
tbltransac.Kd_Plg,
Tblcust.Nm_Plg,
GRANDTOTAL AS Total_Faktur,
... | ***Note:*** first of all you should avoid any function in *Where clause* like this one
```
year(tbltransac.tgl_faktur)=2015
```
**[Here](https://sqlblog.org/2009/10/16/bad-habits-to-kick-mis-handling-date-range-queries)** ***Aaron Bertrand*** how to work with date in *Where clause*
"In order to make best possible us... | Why my sql query is so slow in one database? | [
"",
"sql",
"sql-server",
""
] |
I have two tables like these.
They represent an interaction of following/followers between two users.
```
users
---------------------------------------
id | username | <br>
1 | bobby | <br>
2 | jessica | <br>
3 | jonny | <br>
4 | mike | <br>
follows
-------------------------------------... | This is a bit more complicated than it first seems, because you want the name of the *other* user:
```
select u.username, f.*
from follows f join
users u
on (u.id = f.userid_1 and f.userid_2 = 1) or
(u.id = f.userid_2 and f.userid_1 = 1)
where 1 in (f.userid_1, f.userid_2);
```
Actually, the `where`... | You can **[JOIN](https://dev.mysql.com/doc/refman/5.0/en/join.html)** tables in following:
```
SELECT u.username, f.userid_1, f.userid_2
FROM users u
JOIN follows f
ON u.Id = f.Id
``` | SQL Query Multiple Conditions | [
"",
"mysql",
"sql",
""
] |
So as the title says, I'm trying to run a query in my ASP Classic page but for some reason it doesn't return a record set while it does returns a record set it if the query is copied directly in Access.
There is one thing where it probably goes wrong, namely:
* The query uses an `LIKE operator` on a `NUMERIC value`.
... | Figured it out myself. Seems that I only had to replace the `*` wildcards with the `%` wildcard. This did the trick.. | use `%` in "LIKE" comparisons for wildcards:
```
"SELECT Description, MyNumber FROM Orders where MyNumber LIKE '%23%'"
``` | LIKE operator in SQL for my Access Database returns no values in ASP CLASSIC while it does if the query gets copied directly in Access | [
"",
"sql",
"ms-access",
"asp-classic",
"sql-like",
""
] |
I have an old dynamic SQL query as below where the conditions in the where clause is appended dynamically based on the search text.
> **Example 1** : Search string **'AMX AC-DIN-CS3 Bracket'**
```
SELECT * FROM Tx_Product
Where Fk_CompanyId=1
and (ModelNumber like '%AMX%' or Manufacturer like '%AMX%' or Category ... | I prefer to use CTEs to make the query text more readable.
I assume that the table `Tx_Product` has a primary key `ID`.
At first we convert `@SearchString` to a table. Then count number of rows in it to get the total number of keywords.
You want to find those products that have all the given keywords.
For each keyw... | The problem is the partial matches.
Try the query below.
The match for each keyword get its number and if product max number is equal to total count of keywords, then the match is full and product should be selected
```
select * from
(
SELECT
DISTINCT Prod.*
,row_number() over
(partition by Pk_Pr... | SQL Search Query with Dynamic search condition | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have this query
```
SELECT poll_numbers.number_title as totale_stemmen,
count(poll_stemmen.number_id) as stem
FROM poll_stemmen
LEFT JOIN poll_numbers on number_id = poll_numbers.id
group by poll_stemmen.number_id
```
And the output is like this:
```
totale_stemmen stem
name 1
another... | You can use your query to get count per `number_id` and use a sub-query to get overall count:
```
SELECT number_title, COUNT(*) AS count_number,
(SELECT COUNT(*)
FROM poll_stemmen
WHERE number_id IN (SELECT id FROM poll_numbers)) AS total_number
FROM poll_numbers AS pn
LEFT JOIN poll_stemmen AS ... | In most databases, you would just use window functions. But, MySQL doesn't support this.
One method is to use a subquery, either in the `from` clause or `select`:
```
SELECT n.number_title, count(s.number_id) as stem,
x.total_number
FROM poll_stemmen s LEFT JOIN
poll_numbers n
on s.number_id = n.id C... | count all values and group by with count | [
"",
"mysql",
"sql",
""
] |
I have a case where I insert multiple datasets into a temp table. At the end, I would like to display the total number of rows for these multiple datasets across all the rows of the temp table. For example:
```
cnt1 name age
300 peter 21
200 piper 22
```
Desired result set:
```
cnt1 name age
500 ... | With window function:
```
select sum(cnt1) over() as cnt1, name, age
from TableName
```
**EDIT:**
```
select (select sum(distinct cnt1) from TableName) as cnt1, name, age
from TableName
``` | Try this (you can use `union all` to append it to your earlier results if you want).
```
Select sum(Cnt1) over () as Cnt1, name, age
from MyTable
```
My answer originally used `over (partition by 1)`, but I see that that is unnecessary. | Sum of 1 column to be displayed for all rows in a dataset | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
Does SQLite offer a way to search every column of a table for a searchkey?
```
SELECT * FROM table WHERE id LIKE ...
```
Selects all rows where `...` was found in the column `id`. But instead to only search in the column `id`, I want to search in every column if the searchstring was found. I believe this does not wor... | A simple trick you can do is:
```
SELECT *
FROM table
WHERE ((col1+col2+col3+col4) LIKE '%something%')
```
This will select the record if any of these 4 columns contain the word "something". | I could not comment on [@raging-bull answer](https://stackoverflow.com/a/30732523). So I had to write a new one. My problem was, that I have columns with `null` values and got no results because the "search string" was `null`.
[Using coalesce](https://www.sqlitetutorial.net/sqlite-functions/sqlite-coalesce/) I could s... | SQLite WHERE-Clause for every column? | [
"",
"sql",
"sqlite",
""
] |
I have a table
```
TABLE [dbo].[IssueStatus](
[Id] [int] PRIMARY KEY ,
[IssueId] [varchar(50)],
[OldStatus] [int] ,
[NewStatus] [int] ,
[Updated] [datetime]
```
The 2 status columns can have 3 possible values 1, 2 and 3 (1 for open, 2 for in progress and 3 for resolved).
`Updated` contains th... | My query below shows for how long each entry was in status 2.
using this sample data:
```
Id IssueId OldStatus NewStatus Updated
1 aa NULL 1 2015-01-01 14:00:00
2 aa 1 2 2015-01-01 16:00:00
4 aa 2 3 2015-01-01 17:30:00
5 bb ... | The sql window function can really come in handy in situations as this.
Assuming you use sql server 2012 or later, you can use the [lead](https://msdn.microsoft.com/en-us/library/hh213125.aspx) function.
For example: this lead usage adds the datetime of the 'next' record:
```
SELECT *, lead(updated,1,getdate()) over ... | how to calculate time duration within a table | [
"",
"sql",
"sql-server",
"database",
""
] |
I am new to SQL and I am not sure what to Google. I have three tables with different numbers of columns. I would like to combine these following three tables into a single column(no duplicates).
**Table1**
```
Col1 Col2 Col3
1 a aa
2 b ab
3 ... | The term you would want to Google would be: `UNION` and `CONCAT`.
> Note: CONCAT is not supported in prior versions to SQL Server 2012.
To get your expected output, I would do this:
```
select
concat(cast(col1 as varchar(10)),col2,col3) as FileOutput
from table1
UNION
select
concat(cast(col1 as varchar(10)),c... | Not sure how you would parse the data, but you could do this:
```
select convert(varchar(100), col1) + convert(varchar(100), col2) + convert(varchar(100), col3) as fileOutput
from table1
union all
select convert(varchar(100), col1) + convert(varchar(100), col2) as fileOutput
from table2
union all
select convert(varc... | Combine columns from three different tables into a single column | [
"",
"sql",
"sql-server-2012",
""
] |
I am trying to add another statement to the WHERE clause of this SQL query to throw out some entries I do not need.
```
SELECT DATEPART(Year, CreateTimestamp) Year
, DATEPART(Month, CreateTimestamp) Month
, COUNT(*) Accepted
FROM Interactions t
WHERE t.QueueName = @queuName
AND (CAST(CreateTimestamp AS DATE) BE... | If `AbandonTimestamp` is null, the date calculation result will be null, so just use `COALESCE()` to provide a passing value in this case:
```
WHERE COALESCE(DATEDIFF(SECOND, CreateTimestamp,
AbandonTimestamp), 11) > 10
```
To explain in more detail, the `COALESCE()` function returns the first term in its list... | You could use ISNULL and use CreateTimestamp when AbandonTimestamp is NULL. This will result in DATEDIFF being false, since the number of elapsed seconds would be 0.
```
SELECT DATEPART(Year, CreateTimestamp) Year
, DATEPART(Month, CreateTimestamp) Month
, COUNT(*) Accepted
FROM Interactions t
WHERE t.QueueName = @que... | Limiting SQL Search When a Value is NULL | [
"",
"sql",
"sql-server",
""
] |
i have a User table which has many users but some users are having same first name and Last Name but only one user will have status active . So my requirement is if the user is unique i need the user regardless of Status but if the user is duplicate i need the record having status active.
How can i achieve this in SQL ... | ```
SELECT UserId, FirstName, LastName, Status FROM (
SELECT *
, ROW_NUMBER() OVER (PARTITION BY FirstName, LastName
ORDER BY Status DESC) AS rowNum
FROM [User]
) u
WHERE u.rowNum = 1
```
This essentially groups by first and last name, orders by Status so that active are higher pri... | I didn't get you question. But, as per your subject line. It seems like you want the record, which is `active`, if record is duplicate.
```
select T.* from yourTable T INNER JOIN (select user, count(*) cnt FROM yourTable GROUP BY user) A ON A.user=T.user
WHERE A.cnt>1 and T.status='A';
```
If it wasn't your requireme... | How to write a Sql query for retrieving one row from duplicate rows? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I need to split a string in a column into one character each into it's own column in SQL Server 2012.
Example: if I have a column with `'ABCDE'`, I need to split it into `'A'`, `'B'`, `'C'`, `'D'`, `'E'`, with each of these into their own columns.
The length of the column to be split may vary, so I need this to be as... | You can do this like this:
```
DECLARE @t TABLE(id int, n VARCHAR(50))
INSERT INTO @t VALUES
(1, 'ABCDEF'),
(2, 'EFGHIJKLMNOPQ')
;WITH cte AS
(SELECT id, n, SUBSTRING(n, 1, 1) c, 1 AS ind FROM @t
UNION ALL
SELECT id, n, SUBSTRING(n, ind + 1, 1), ind + 1 FROM cte WHERE LEN(n) > ind
)
SELECT *
FROM cte
PIVOT (MAX... | If you want a new column for every character you simply need:
```
SELECT [1] = SUBSTRING(Col, 1, 1),
[2] = SUBSTRING(Col, 2, 1),
[3] = SUBSTRING(Col, 3, 1),
[4] = SUBSTRING(Col, 4, 1),
[5] = SUBSTRING(Col, 5, 1),
[6] = SUBSTRING(Col, 6, 1),
[7] = SUBSTRING(Col, 7, 1),
... | Split a string with no delimiters into columns | [
"",
"sql",
"sql-server",
"database",
""
] |
In production, issuing a `SELECT COUNT` can be a bad idea - it can be a performance hit depending on your database engine. In Oracle, if I want to get an idea of the size of a table without having to resort to a `COUNT`, I can do the following:
```
SELECT
table_name,
num_rows,
last_analyzed
FROM all_tables... | You can use the management studio also
```
Right Click on table -> Properties -> Storage
```
or you can use the query like this:
```
sp_spaceused 'TableName'
```
To get it for all the tables you can use it like tihs:
```
CREATE TABLE #tmp
(
tableName varchar(100),
numberofRows varchar(100),
reservedSiz... | You can call `sp_spaceused 'table_name'`.
If you want to do this for all tables, wrap it inside `sp_MSforeachtable`:
```
sp_MSforeachtable 'sp_spaceused ''[?]'''
```
Calling `sp_spaceused` without any parameter will give you the database size. | SQL Server - Get approximate size of table | [
"",
"sql",
"sql-server",
""
] |
I have two tables, Product and ProductImages.
Product table has 2 columns: ProductID and Name
ProductImages table has 4 columns: ID, ProductID, ImageName and Primary(bit).
The relation between Product and ProductImages is one to many, so one product can have many images, but for each product only one ProductImage wi... | You can do this simply like this with `row_number` window function:
```
select * from Products p
join (select *, row_number()
over(partition by ProductID order by ID) rn from ProductImages)pi
on p.ProductID = pi.ProductID and pi.rn = 1
```
I assume that primary image `ID` will precede non pr... | This is kind of "quick and dirty" but i works:
```
SELECT pr.ProductID, pr.Name, prim.ImageName, 1 AS IsPrimary
FROM @product pr
INNER JOIN @productimage prim ON pr.ProductID = prim.ProductID
WHERE prim.[Primary] = 1
UNION ALL
SELECT pr.ProductID, pr.Name, prim.ImageName, 0 AS IsPrimary
FROM @product... | Always Get 1 record from Table 2 based on some condition | [
"",
"sql",
"sql-server",
"sql-server-2008",
"azure-sql-database",
""
] |
How can i retrieve *(select)* half of records from a table, for example, a table with 1000 rows, retrieve 500 (50%) from the table. (in this case i can use rownum because we know the exact quantity of rows (1000) - `select * from table where rownum <= 500`), but i have to count every table to achieve the statement.
Wh... | Well, you could count the rows and select half:
```
select *
from my_table
where rownum <= (select count(*)/2 from my_table)
```
That would *tend* to select rows that are contiguous within the physical segments.
Or ...
```
select *
from (select rownum rn, * from my_table)
where mod(rn,2) = 0
```
That would *... | With `NTILE` window function:
```
select * from (SELECT *, NTILE(2) OVER(ORDER BY (SELECT NULL FROM DUAL)) nt FROM TableName) as t
where nt = 1
```
or:
```
select * from (SELECT *, NTILE(2) OVER(ORDER BY NULL) nt FROM TableName) as t
where nt = 1
``` | How to retrieve half of records from a table - Oracle 11g | [
"",
"sql",
"oracle",
""
] |
I'm trying to run a query that will update a field in one table if a field in another table is equal to test. Here is the code:
```
UPDATE Table1 AS t1 INNER JOIN Table2 AS t2
ON t1.Field1 = t2.F_Name
SET t1.Field4 =
(CASE
WHEN t2.PlayField = 'test' THEN 'test'
ELSE 'No test'
END);
```
How... | Since you only want to understand the issue..Your SQL :
```
UPDATE Table1 AS t1 INNER JOIN Table2 AS t2
ON t1.Field1 = t2.F_Name
SET t1.Field4 =
(CASE
WHEN t2.PlayField = 'test' THEN 'test'
ELSE 'No test'
END);
```
MS Access doesn't support the `CASE` statement. It looks like SQL Server, n... | `CASE ... WHEN` is not supported in Access SQL. Use `IIf` instead.
```
UPDATE Table1 AS t1 INNER JOIN Table2 AS t2
ON t1.Field1 = t2.F_Name
SET t1.Field4 =
IIf(t2.PlayField = 'test', 'test', 'No test');
``` | SQL Syntax Error Missing Operator MS Access | [
"",
"sql",
"ms-access",
""
] |
I created a function as shown below:
```
CREATE FUNCTION my_func(value INTEGER) RETURNS VOID AS $$
BEGIN
END;
$$ LANGUAGE plpgsql;
```
But I need to specify the parameter to drop the function as shown below:
```
DROP FUNCTION my_func(value INTEGER);
```
Because if not specifying the parameter as shown below:
```
D... | In Postgres functions [can be overloaded](http://www.postgresql.org/docs/9.4/static/xfunc-overload.html), so parameters are necessary to distinguish overloaded functions. To unambiguously identify a function you can put only types of its parameters.
```
DROP FUNCTION my_func(INT);
``` | As of Postgres 10 you can drop functions by name only, as long as the names are unique to their schema.
Example:
```
drop function my_func;
```
Documentation [here](https://www.postgresql.org/docs/current/static/sql-dropfunction.html). | PostgreSQL: Drop a function without parameters | [
"",
"sql",
"database",
"postgresql",
"plpgsql",
"drop",
""
] |
I have a huge `INSERT INTO TABLE1 (....) SELECT .... FROM TABLE2` statement. It gives me the error
> "String or binary data would be truncated".
I know that one of the columns from TABLE2 is way bigger for one column from TABLE1 in the `INSERT` statement.
I have more than 100 columns in each table. So it is hard to ... | You can query `Information_Schema.Columns` for both tables and check the difference in content length.
Assuming your tables have the same column names, you can use this:
```
SELECT t1.Table_Name, t1.Column_Name
FROM INFORMATION_SCHEMA.Columns t1
INNER JOIN INFORMATION_SCHEMA.Columns t2 ON (t1.Column_Name = t2.Column_... | To figure out which column the data is too long fit in, I would use following statement to output the results to a temp table.
```
SELECT ...
INTO MyTempTable
FROM Table2
```
Then use the query example from [this article](http://blogs.lessthandot.com/index.php/datamgmt/datadesign/maximum-length-of-data-in/) to get ... | how to find "String or binary data would be truncated" error on sql in a big query | [
"",
"sql",
"sql-server",
""
] |
I am using the Microsoft sample database and the questions from SQLZOO.net to learn SQL for my job. I am stuck on the question:
> For every customer with a 'Main Office' in Dallas show AddressLine1 of
> the 'Main Office' and AddressLine1 of the 'Shipping' address - if
> there is no shipping address leave it blank. Use... | You need to alias the table to join onto itself. For example:
```
SELECT T1.Column1, T2.Column2, ...
FROM Table1 AS T1
JOIN Table1 AS T2
ON T1.Column1 = T2.Column1
``` | I browsed the AdventureWorks schema and I think this is the right approach. It does involve a self-join which is accomplished by bring the same table into the query with a second alias (Person.Address as "oa" and "sa" below.) Since the shipping address join is apparently optional I would say that that is actually the t... | Using the same table in a join | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
This is my Azure configuration:
1. I have a Virtual Network with a couple of subnets and a gateway
configured to allow point-to-site.
2. There is one Virtual Machine with SQL Server (2014) installed. There
are some databases in there already. SQL Server is set up to allow
SQL Server and Windows Authentication... | The other answers gave me the guidelines to find out the solution.
I'll try to describe the steps I followed:
1. Using the new azure portal (portal.azure.com currently in preview) I
established a connection between the Azure Web App and the Virtual
network:
* Home > Browse > Click on Azure Web App name
* ... | Check your connection string against this connection string for Entity Framework designer files (<https://msdn.microsoft.com/en-us/data/jj556606.aspx#Connection>)
Just from a quick glance I see two possible errors:
1. Semicolon missing added after provider=System.Data.SqlClient (the example on the page I provided the... | Publishing a MVC App in Azure Web App | [
"",
"sql",
"sql-server",
"asp.net-mvc",
"azure",
""
] |
I have a simple data set of customers (about 40,000k)
It looks like:
```
customerid, group, other_variable
a,blue,y
b,blue,x
c,blue,z
d,green,y
e,green,d
f,green,r
g,green,e
```
I want to randomly select for each group, Y amounts of customers (along with their other variable(s).
The catch is, i want to have two rando... | `proc surveyselect` is the general tool of choice for random sampling in SAS. The code is very simple, I would just sample 4000 of each group, then assign a new subgroup every 2000 rows, since the data is in a random order anyway (although sorted by group).
The default sampling method for `proc surveyselect` is `srs`,... | ```
data custgroup ;
do i=1 to nobs;
set sorted_data nobs=nobs ;
point = ranuni(0);
end;
proc sort data = custgroup out=sortedcust
by group point;
run;
data final;
set sortedcust;
by group point;
if first group then i=1;
i+1;
run;
```
Basically what I am doing is first assign a random number to all observations in t... | SAS how to get random selection by group randomly split into multiple groups | [
"",
"sql",
"sas",
"sample",
"proc",
""
] |
I have two sets of records
Set 1:
```
-11
-12
-12 AN
''
-134
-125
+135
```
Set 2:
```
1.15
1.1
```
In Set 1 I need to check which values are either blank `''` or start with a `+` sign and are greater than 125.
In Set 2 I need to check which values have less than two decimal places
Example output for the ... | In SQL-Server could be something like that:
```
WITH cte AS (
SELECT Col
FROM set1
WHERE Col = '' OR Col LIKE'+%' AND (CAST(REPLACE(REPLACE(Col,'+',''),'-','') AS INT) > 125)
)
SELECT * FROM cte
UNION ALL
SELECT Col
FROM set2
WHERE Col LIKE '%._'
```
OUTPUT:
```
'' -- blank
+135
1.1
```
**[SQL FIDDLE](http://sqlfi... | For the first set, you can use the `like` operator to check if a string starts with '+' and then cast it to `numeric` and compare it with `125`. Using `isnumeric` beforehand will help avoid casting errors:
```
WHERE col = '' OR
(col LIKE '+%' AND ISNUMERIC(col) AND CAST(col AS NUMERIC) > 125)
```
For the second... | Check for two decimal digit number in string | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
""
] |
I often find myself running into situations like this one (which is contrived but illustrative of the problem):
```
CREATE TABLE customer (
id SERIAL PRIMARY KEY,
type TEXT
-- other columns...
);
CREATE TABLE product_order (
id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customer (id),
t... | If you create a unique *constraint* on the `customer.type` you can reference it from the `product_order` table:
```
CREATE TABLE customer (
id SERIAL PRIMARY KEY,
type TEXT,
-- other columns...
constraint unique_cust_type unique (id, type) -- this makes the combination id/type "referencable"
);
CREATE TABL... | You could make a lookup table for types, and use the FKEY relationship to enforce
```
CREATE TABLE type (
id integer, PRIMARY KEY,
name TEXT
);
CREATE TABLE customer (
id SERIAL PRIMARY KEY,
type_id INTEGER, NOT NULL
-- other columns...
FOREIGN KEY (type_id) REFERENCES type(id)
);
CREATE TABLE produc... | What is the best way to enforce constraints across tables? | [
"",
"sql",
"postgresql",
""
] |
I need to add a where condition for a SQL query , means when the dept id become 9 only i need that where condition , else i dont required.
i have written the below query , is the approach is correct?
```
SELECT
b.DeptId,
b.DeptName,
a.SurveyID,
a.SurveyName,
a.Status,
a.AllUsers,
IsNull(a.SelectedUsers,'') as Selec... | If I understand you correctly, you only need rows where DeptId is not 9, or DeptId is not null. Also, your gross disregard for consistency in your capitalization hurts me. What is this beast?!
```
SELECT
b.DeptID, b.DeptName,
a.SurveyID, a.SurveyName, a.Status, a.AllUsers,
ISNULL(a.SelectedUsers,'') as Sel... | ```
and CASE WHEN DeptId == 9
```
You only need one = sign for this comparison. | adding a where condition for one criteria in sql query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"rdbms",
""
] |
I have two tables with same structure: `tmp_grn` and `grn`.
I have to delete rows from table `tmp_grn` which already exists in table `grn`.
Problem is I don't have a unique or primary key but I can determine a unique row with the combination of two columns. Let's say column names are `grn_code` and `item_skucode`.
... | If you want to combine two columns, you need to put them into parenthesis:
```
DELETE FROM tmp_grn
WHERE (grn_code, item_skucode) IN (SELECT grn_code, item_skucode
FROM grn);
```
But suslov's answer using an `exists` is most probably faster - you need to check the execution pl... | You can use `exists` (*if you want to check the pair of values*):
```
delete from tmp_grn t
where exists ( select *
from grn
where grn_code = t.grn_code
and item_skucode = t.item_skucode);
``` | Subquery has too many columns | [
"",
"sql",
"postgresql",
""
] |
A simple table contains the one column with integer vales.The Figure is given below.

I am using COALESCE to construct the 'numbers' by comma.

So, now there is a problem... | When you concatenate all the numbers you are converting it a string so it no longer acts like an integer. If you want to check for a value in a list, do it directly like. SQL was made to have different values in different rows and work with them that way. Try this out:
```
DECLARE @failIds INT = 23;
IF @failIds IN (S... | Instead of the comma separated string, you should use a table variable, temp. table or just the original table. For example, something like this:
```
declare @Ids table (id int)
insert into @Ids
select numbers
from model
where numbers in (23,234)
declare @failIds int = 23
if (exists (select 1 from @Ids where id = @... | How to check a comma delimited integer values by "IF" condition T-SQL? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table with the structure below:
```
create table roster
(
date date not null,
first nvarchar(20) not null,
second nvarchar(20) not null,
third nvarchar(20) not null,
fourth nvarchar(20) not null,
)
go
```
And that has the following data inserted:
```
insert into roster values ('2015-06-10 12:45:34', 'e', 'm... | Why need a `group by` if you just need a single `exists()`?
```
;with data as
(
select ROW_NUMBER() OVER (ORDER BY date) AS number, * from roster
)
select * from data where
not exists -- Just compare with the previous column, if match say bye
(
select * from data prev where 1 = 1
and p... | You can group by the values of first, second, third, fourth
then select the first date those values are encountered with min(date) or the last time they occur with max(date)
example for the last date encountered: [fiddle](http://sqlfiddle.com/#!3/349c1/2)
```
SELECT min(date) as startdate ,max(date) as enddate, firs... | Selecting distinct consecutive rows amongst duplicates | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
What I am doing is pretty straight forward dug around at a few posts and couldn't figure out how to express it properly
TVP Declaration
```
CREATE TYPE [dbo].[CustomSeoDic] as table (
[RecordID] [int] NULL,
[Name] [nvarchar](125) NULL)
GO
```
Attempt 1
```
BEGIN
MERGE INTO Listings L
USING @... | You don't need a MERGE. You need conditional `SET ColumnX = (this or that)` statements.
Something like this.
```
Update Listings
Set L.OriginalSubdivisionName =
case when L.OriginalSubdivisionName IS NULL Then
L.SubdivisionName
else
L.OriginalSubdivisionName / * a little trick to keep it the same value */
end
,
L.Su... | I am mostly guessing here but it seems like a simple update along these lines should be close to what you are trying to do.
```
UPDATE l
SET OriginalSubdivisionName = CASE WHEN l.OriginalSubdivisionName IS NULL THEN L.SubdivisionNam ELSE Tvp.Name END
FROM Listing l
JOIN @CustomSeo Tvp ON Tvp.RecordID = l.ListingID
``` | Sql Server TVP Merge with Where/Case Statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
"table-valued-parameters",
""
] |
I have a table with two columns:
```
No Value
1 20
2 10
3 50
4 35
5 17
```
I also have a variable or parameter where the variables will reduce the value of a column in a row.
So, if my variable `V = 5` then my column will update:
```
No Value
1 15
2 10
3 50
4 35
5 17
```
Or if `V ... | ```
DECLARE @qty int
SET @qty= 50
WHILE @qty> 0
BEGIN
SELECT @qty= @qty- value
FROM table
WHERE no = (SELECT MIN(no) FROM table WHERE value > 0)
IF @qty< 0
BEGIN
UPDATE table
SET value = ABS(@qty)
WHERE (SELECT MIN(no) FROM table WHERE value > 0)
END
ELSE
BEGIN
UPDATE table
SET... | First prepare the structure and the data:
```
CREATE TABLE TAB
(
[No] int identity(1,1) primary key,
[Value] int
);
INSERT INTO TAB VALUES (20);
INSERT INTO TAB VALUES (10);
INSERT INTO TAB VALUES (50);
INSERT INTO TAB VALUES (35);
INSERT INTO TAB VALUES (17);
```
So now we define your variable to reduce the [Va... | How to reduce the value of a column in a row with? | [
"",
"sql",
"sql-server",
"row",
""
] |
I have a database in SQL Server with a lot of tables and wish to export all tables in csv format. From a very similar question asked previously - [Export from SQL Server 2012 to .CSV through Management Studio](https://stackoverflow.com/questions/17471994/export-from-sql-server-2012-to-csv-through-management-studio)
> ... | The export wizard allows only one at a time. I used the powershell script to export all my tables into csv. Please try this if it helps you.
```
$server = "SERVERNAME\INSTANCE"
$database = "DATABASE_NAME"
$tablequery = "SELECT s.name as schemaName, t.name as tableName from sys.tables t inner join sys.schemas s ON t.sc... | Instead of clicking `Export Data`, choose `Generate Scripts`. Select the tables you want, click next and click the `Advanced` button. The last option under `General` is `Types of data to script`. Chose `Schema and data` or just `Data`. | SQL Server Management Studio 2012 - Export all tables of database as csv | [
"",
"sql",
"sql-server",
"ssms",
""
] |
I have a table like this:
*(Pay attention to the sequence numbers for every word)*
```
// tablename
+---------+----------+
| word | number |
----------------------
| jack | 1 |
| jack | 2 |
| jack | 3 |
| ali | 1 |
| ali | 2 |
| ali | 3 |
| ali | ... | I have to head out but if your data looks like this with the ID column:
```
+---------+----------+----+
| word | number | ID |
---------------------------
| jack | 1 | 1 |
| jack | 2 | 2 |
| jack | 3 | 3 |
| ali | 1 | 4 |
| ali | 2 | 5 |
| ali | 3 ... | If you have an Id column, this is a simple way to do what you need
```
SELECT
word, number
FROM
Test
WHERE
id BETWEEN
(SELECT id FROM Test WHERE word = 'ali' AND number = '2') AND
(SELECT id FROM Test WHERE word = 'peter' AND number = '3');
```
[Here](http://sqlfiddle.com/#!9/1c199/2) you have a wor... | How to select a range of my table | [
"",
"mysql",
"sql",
"select",
"range",
""
] |
I have date column in table
ColumnName: event\_timestamp
2015-06-01 15:23:31.000
2015-06-01 15:25:21.000
2015-06-03 09:00:41.000
2015-06-03 09:14:49.000
2015-06-03 09:15:03.000
2015-06-03 09:15:23.000
2015-06-06 08:40:06.000
2015-06-06 08:40:19.000
2015-06-06 11:13:35.000
2015-06-06 11:13:53.000 ... | using sql server
```
WITH cteEvents AS
(
SELECT
CONVERT(VARCHAR,event_timestamp,101) event_date,
RANK()OVER(ORDER BY CONVERT(VARCHAR,event_timestamp,101) DESC) rnk
FROM
events
WHERE
event_timestamp BETWEEN '01-Jun-15 11:14:40 AM'
AND '11-Jun... | Stick with ISO-standard date formats and built-in types:
```
SELECT DISTINCT CONVERT(DATE, e.event_timestamp) myDate
FROM events e
WHERE e.event_timestamp Between '2015-06-01T11:14:40' AND '2015-06-11T11:14:40'
```
This will probably fix your problem. | Get max date and exact previous from max date from a given date range sql server | [
"",
"sql",
"datetime",
""
] |
I need to select the last 12 months. As you can see on the picture, May occurs two times.
But I only want it to occur once. And it needs to be the newest one.
Plus, the table should stay in this structure, with the latest month on the bottom.

And th... | In `Oracle` and `SQL-Server` you can use `ROW_NUMBER`.
`name` = month name and `num` = month number:
```
SELECT sub.name, sub.num
FROM (SELECT ROW_NUMBER () OVER (PARTITION BY name ORDER BY num DESC) rn,
name,
num
FROM tab) sub
WHERE sub.rn = 1
ORDER BY num DESC;... | ```
WITH R(N) AS
(
SELECT 0
UNION ALL
SELECT N+1
FROM R
WHERE N < 12
)
SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month]
FROM R
```
The `With R(N)` is a Common Table Expression.The R is the name of the result set (or table) that you are generating. And the N is the month numbe... | How to select the last 12 months in sql? | [
"",
"sql",
"sql-server",
"select",
""
] |
I have two tables which are not fully equal but similar. They look like this:
```
CREATE TABLE FIRST_TABLE(
FIRST_ID RAW(16) NOT NULL CONSTRAINT FIRST_PK PRIMARY KEY,
FIRST_NAME VARCHAR2(2000),
FIRST_VALID NUMBER(1) NOT NULL,... | Just use `insert . . . select`:
```
insert into second_table(second_id, second_name, audit_cre_at, audit_cre_from)
SELECT first_id, first_name, audit_cre_at, audit_cre_from
FROM FIRST_TABLE f
WHERE f.FIRST_VALID = 1;
```
You don't need PL/SQL for this. Also, when comparing numbers, use numeric constants a... | You don't need a loop. You could use an insert-select statement instead:
```
INSERT INTO second_table (second_id, second_name, audit_cre_at, audit_cre_from)
SELECT first_id, first_name, audit_cre_at, audit_cre_from
FROM first_table
WHERE valid = 1
``` | Migrate records to another table | [
"",
"sql",
"oracle",
"plsql",
""
] |
I want to display a List of Instructors with only first name and last name, from Georgia and whose last name ends in ‘son’.
I have written this so far:
```
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'ga'
AND lastname LIKE '%son'
```
But it is not returning the information requested just a blank... | FINALLY !!!!!
I Figured It Out!
```
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'ga'
AND lastname LIKE '*son*'
```
Instead of using the %WildCard I inserted \*WildCard on both ends and it displayed exactly what I was requesting !
Thanks Everyone For Your Help! | To find names ending in 'son' you need to make a small change and remove the second '%' sign. with both it looks for 'son' any where such as 'sonnentag'
The second one I would guess that the DB has Georgia as 'GA' not 'ga'. Case is important.
```
SELECT firstname, lastname, state
FROM instructors
WHERE state = 'GA'
A... | How To Use The Where & Like Operator Together in SQL? | [
"",
"sql",
"ms-access",
"where-clause",
"sql-like",
""
] |
I'm not very good at SQL, and I have a very peculiar request to do.
My table looks something like this :
```
FOO BAR
----+----
foo1 bar1
foo2 bar3
foo1 bar1
foo1 bar1
foo2 bar3
foo4 bar3
foo3 bar2
foo2 bar4
foo5 bar4
```
I manage easily to count the number of each different "bar" entries with a
```
SELECT ba... | If you need to nest aggregates you must use a Derived Table (or Common Table Expression):
```
select barcount, count(*) as occurrences
from
(
SELECT bar, COUNT(*) as barcount
FROM table
GROUP BY bar
) as dt
group by barcount
ORDER BY barcount
``` | ```
select barcount, count(*) as occurences
from
(
SELECT bar, COUNT(*) as barcount
FROM your_table
GROUP BY bar
) tmp
group by barcount
``` | SQLite: Count the number of similar COUNT(*) rows resulting from a GROUP_BY statement | [
"",
"sql",
"sqlite",
""
] |
I'm trying to do something similar to this:
```
CASE
WHEN number IN (1,2,3) THEN 'Y' ELSE 'N' END;
```
Instead I want to have a query in the place of the list, like so:
```
CASE
WHEN number IN (SELECT num_val FROM some_table) THEN 'Y' ELSE 'N' END;
```
I can't seem to get this to work. Also, here is an example of... | Yes, it's possible. See an example below that would do what you are intending. The difference is that it uses `EXISTS` instead of `IN`.
```
SELECT a.number,
(CASE WHEN EXISTS (SELECT null FROM some_table b where b.num_val = a.number)
THEN 'Y'
ELSE 'N'
END) AS YES_NO
FROM ... | I suggest using an OUTER JOIN instead of trying to use a subquery in a CASE expression:
```
SELECT t.NUMBER,
CASE
WHEN s.NUM_VAL IS NOT NULL THEN 'Y'
ELSE 'N'
END AS YES_NO
FROM SOME_OTHER_TABLE t
LEFT OUTER JOIN SOME_TABLE s
ON s.NUM_VAL = t.NUMBER
```
Best of luck. | Can Oracle PL/SQL CASE statement include a SELECT query? | [
"",
"sql",
"oracle",
"plsql",
"case",
"plsqldeveloper",
""
] |
I have a table like this:
```
| id | name | description | publish
1 B text 1
2 B text2 1
3 B3 text3 1
4 B4 text4 1
5 B5 text 1
```
Tw... | Considered table name as `temp1`
```
update temp1 set publish=0 where id in (select x.id from (select a.id from temp1 a ,temp1 b
where
a.id<>b.id and (a.name=b.name or a.description=b.description)and a.id>b.id
group by a.id) as x);
```
Check Here : <http://www.sqlfiddle.com/#!9/19863/1>
This will work fine. | using `"pubs"` as table name
```
UPDATE
pubs
LEFT JOIN
(
SELECT
MIN(id) minId
FROM
pubs
GROUP BY
name
) minPubs ON
minPubs.minId = pubs.id
SET
pubs.publish = 0
WHERE
minPubs.minId IS NULL;
```
<http://sqlfiddle.com/#!9/54fae/1> | How to group duplicate records and then update all members except lowest id for each group? | [
"",
"mysql",
"sql",
""
] |
I have table named `boolean` which contain 'true' and/or 'false' values as strings in one column.
I have problem to create `case` statement to show me whether there are only 'true' or 'false' or 'both' values
Example 1:
```
'true'
'true'
```
result:'true'
Example 2:
```
'false'
'false'
'false'
```
Result:... | You could aggregate the `max` and `min` of the column, and then evaluate the results - if they are the same, there's only one value in the column. If not, there must be both. Note that since these are string representations the values are sorted lexicographically:
```
SELECT CASE WHEN MAX(col) = MIN(col) THEN MAX(col)... | ```
SELECT CASE WHEN MIN(Col) <> MAX(Col) THEN
'Both'
ELSE
MIN(Col)
END
FROM YourTable
``` | SQL Server : case statement | [
"",
"sql",
"sql-server",
"select",
"case",
""
] |
I have a table
```
StudentID StudentName Subject Marks
1 Savita EC1 50
1 Savita EC2 55
1 Savita EC3 45
1 Savita EC4 34
1 Savita EC5 23
2 Rajesh EC1 34
2 Rajesh EC2 56
2 Rajesh EC3 12
... | You can try this
```
SELECT
StudentName,
CASE WHEN EC1 < 30 THEN EC1 + 7 ELSE EC1 END AS EC1,
CASE WHEN EC2 < 30 THEN EC2 + 7 ELSE EC2 END AS EC2,
CASE WHEN EC3 < 30 THEN EC3 + 7 ELSE EC3 END AS EC3,
CASE WHEN EC4 < 30 THEN EC4 + 7 ELSE EC4 END AS EC4,
CASE WHEN EC5 < 30 THEN EC5 + 7 ELSE EC5 ... | Maybe this is something you're looking for:
```
SELECT A.StudentName, EC1,EC2,EC3,EC4,EC5,Total,
case when fail2 >= 2 then 'Failure'
when fail >= 2 then 'Near Pass'
else 'Pass' end as Result
FROM
( SELECT StudentName, EC1, EC2, EC3, EC4, EC5
FROM Student
PIVOT(sum(Marks) for subject in([EC... | Using if else block in pivot query | [
"",
"sql",
"sql-server",
""
] |
I want to find few data from SQL Server that only query by current date. The purpose is to view today transaction only
Here is my code
```
SELECT * FROM dbo.Student.studentProfile
WHERE TransactionDate = curdate()
```
RESULT
> Curdate is not a recongined built-in function name | If you are looking for the current date:
```
WHERE TransactionDate = cast(getdate() as date)
```
Or if you prefer ANSI standards:
```
WHERE TransactionDate = cast(CURRENT_TIMESTAMP as date)
``` | Different sql implementations (ie SQL Server, Mysql, postgresql etc) can have different methods supported. For SQL Server the method you want to use is GETDATE() instead of CURDATE()
The documentation for this method is here: <https://msdn.microsoft.com/en-us/library/ms188383.aspx> | sql server query current date from database | [
"",
"sql",
"sql-server",
"date",
""
] |
I have three tables for listing products with product attributes
**Product Table** with dummy data


**Product\_Attributes** with dummy data
)
from product
left outer join product_attributes pa
on (pa.productId = product.productId)
left outer join attributes attr
on (attr.attributeId = pa.attribu... | Your question requires a pivot, which needs to be predefined. Meaning, if you want to include 2 extra COLUMNS in your result set, your query can then only store up to 2 attributes. This is a PRESENTATION layer problem, not query layer. But alas, I have a general solution for you. It assumes you will have a max number o... | Joining product attributes table with the product table to display product | [
"",
"mysql",
"sql",
"database",
"join",
"left-join",
""
] |
I have a Sql Procedure that receives a string as a parameter.
Now the task that I need to perform is that the parameter contains data that is separated by two different kinds of delimiters i.e **":"** and **","**
There are two columns in the DB **Id** and **Value**.
```
sample Data: "10:0,11:1,12:3,13:4,15:5,16:... | You can use following function:
```
CREATE FUNCTION Split (
@InputString VARCHAR(8000),
@Delimiter VARCHAR(50)
)
RETURNS @Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
... | ```
IF OBJECT_ID('tempdb..#Test') IS NOT NULL
DROP TABLE #Test
GO
CREATE TABLE #Test(ID INT,Val INT)
DECLARE @t table (val varchar(50))
INSERT INTO @t (val)values ('10:0,11:1,12:3,13:4,15:5,16:6')
;WITH CTE AS (
SELECT
Split.a.value('.', 'VARCHAR(100)') AS String
FROM (SELECT
CAST ('<M>' + ... | Use data separated by delimiters in Sql Procedure | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I have a query that is supposed to pull the highest primary key id for a specific request code:
```
SELECT id
FROM [QTRA410].[Admin].[qt_request]
WHERE id IN (SELECT Max(id)
FROM [QTRAX4619410].[QTRAXAdmin].[qt_request])
AND requestcode = 'FOREMAN';
```
Here is the current data in the ta... | you might also try if [QTRAX4619410].[QTRAXAdmin].[qt\_request] doeos not contain the requestcode:
```
SELECT id
FROM [QTRA410].[Admin].[qt_request]
WHERE id IN (SELECT Max(r1.id)
FROM [QTRAX4619410].[QTRAXAdmin].[qt_request] r1
join [QTRA410].[Admin].[qt_request] r2 on r1.id = r2.... | Try this:
```
SELECT id
FROM [QTRA410].[Admin].[qt_request]
WHERE id IN (SELECT Max(id)
FROM [QTRAX4619410].[QTRAXAdmin].[qt_request]
WHERE requestcode = 'FOREMAN')
``` | Getting highest primary key for specified column value | [
"",
"sql",
"sql-server",
""
] |
I was writing a `Stored Procedure` today and Wrote the line:
```
SELECT pv1.Version FROM depl...
```
and the word `Version` turned blue shown below:

so I assumed it was a reserved word, so did some investigating here:
[Reserved Keywords (TRANSACT... | As you rightly noted, `Version` is not in the official reserved word list. It's just a "feature" of SQL Server Management Studio that is showing it in blue.
There are many words like this. Here's a few more:
```
DESCRIPTION
SERVER
INSTEAD
```
There are even some words that show as pink such as `LOOKUP`. | "Version" is not a SQL Server reserved keyword.
However, it is used in a global variable used to show the OS name & version, SQL Server version, SQL Server patches and hardware attributes of the SQL Server being used.
```
SELECT @@VERSION
```
Perhaps the "Version" text turns blue in Transact-SQL because it is known ... | Is "Version" a Reserved word in TRANSACT-SQL? (Shows Blue but not in Reserved word list) | [
"",
"sql",
"sql-server",
"reserved-words",
""
] |
I am struggling to find an elegant solution to this problem.
I have 5 tables and their relationships are described in the image.

A page can have multiple products and each product can have many ProductRates. A Page with specific Product could have ma... | ```
SELECT p2p.PageID
FROM
PageToProduct as p2p
inner join Product as pr
on p2p.Product = pr.Product
inner join PageToProductToRate as p2p2r
on p2p2r.PageToProductID = p2p.PageToProductID
inner join ProductRates as r
on r.ProductRatesID = p2p2r.ProductRatesID
WHERE
(pr... | My best guess.
```
WITH products AS
(
SELECT [Product],
[ProductRatesID]
FROM Product p
JOIN ProductRates pr ON p.[Product] = pr.[Product]
WHERE (p.[Product] = 'ALMOND' AND pr.CommissionType = 'PREMIUM' AND pr.Rate = 0.25)
OR (p.[Product] = 'WALNUT' AND pr.Commiss... | SQL SELECT multiple conditions many to many relationship | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Consider this schema
```
CREATE TABLE [PrimaryTable]
[Id] int IDENTITY(1,1) NOT NULL
ALTER TABLE [PrimaryTable]
ADD CONSTRAINT [PK_PrimaryTable]
PRIMARY KEY ([Id])
CREATE TABLE [SecondaryTable]
[PrimaryTableId] int NOT NULL
[Name] nvarchar(4000) NOT NULL
[Value] nvarchar(4000) NULL
ALTER TAB... | Using NOT IN
```
SELECT Id
FROM PrimaryTable
WHERE Id NOT IN (
SELECT PrimaryTableId
FROM SecondaryTable
WHERE Name='xxx' AND Value='yyy')
```
Using NOT EXISTS
```
SELECT pt.Id
FROM PrimaryTable pt
WHERE NOT EXISTS (
SELECT *
... | I simply added a null check on the joined table so the value would be included.
```
SELECT Id
FROM PrimaryTable
LEFT OUTER JOIN SecondaryTable ON PrimaryTable.Id = SecondaryTable.PrimaryTableId
WHERE (
SecondaryTable.Name = 'xxx'
AND SecondaryTable.Value NOT LIKE 'yyy'
)
OR SecondaryTable.PrimaryTableId IS NULL
... | SQL join against a table with both a NOT LIKE condition and a value not existing | [
"",
"sql",
"sql-server",
""
] |
I'm trying to find an effective way to filter out result set produced by chained three tables left join, where second table join would take into account third table's properties.
Fiddle: <http://sqlfiddle.com/#!2/e319e/2/0>
A simplified example would be a join between three tables: Post, Comment and Author. Posts can... | I think you want this `from` clause:
```
FROM Post p LEFT JOIN
(Comment c JOIN
Author a
ON a.id = c.author_id AND a.is_active = 1 and c.is_active = 1
)
ON c.post_id = p.id
```
As I mention in the comment, though, you might want to inactivate comments by inactive authors. That would involve ... | This should do too:
```
select a.title, p.title, c.title
from author a
left join comment c on a.id = c.author_id
left join post p on c.post_id = p.id
where a.id in (select id from author where is_active = 1)
and c.is_active = 1
```
<http://sqlfiddle.com/#!2/e319e/1> | MySQL three table chained left join, filtering by last table | [
"",
"mysql",
"sql",
""
] |
I have this table:
```
SELECT * FROM #BH2
BookingID | Detail | CreatedAgentCode | ChangeDate
----------|------------------------------------------------------|------------------|--------------------------
196162093 | MRS LUCIENE CORREA correa MRS LUCIENE CORREA ... | You can try this.[SQL Fiddle](http://sqlfiddle.com/#!6/6e8d2/1)
```
WITH cteBookingPassengerVersion AS
(
SELECT BookingID,
RTRIM(
CONCAT (
ISNULL(Title + ' ', ''),
ISNULL(FirstName + ' ', ''),
ISNULL(MiddleName + ' ', ''),
... | You can try this in [SqlFiddle](http://sqlfiddle.com/#!6/6e8d2/13)
I update the user1221684 answer to remove duplicated rows.
```
WITH cteBookingPassengerVersion AS
(
SELECT BookingID,
RTRIM(
CONCAT (
ISNULL(Title + ' ', ''),
ISNULL(FirstName + '... | Search specific row in another table by date | [
"",
"sql",
"sql-server",
""
] |
Given is following mysql table:
```
CREATE TABLE fonts
(`id` int, `fontName` varchar(22), `price` int,`reducedPrice` int,`weight` int)
;
INSERT INTO fonts
(`id`, `fontName`, `price`,`reducedprice`,`weight`)
VALUES
(1, 'regular', 50,30,1),
(2, 'regular-italic', 50,20,1),
(3, 'medium', 60,30,2),
... | Write a subquery that gets the number of occurrences of each weight, and join with this. Then you can test the number of occurrences to decide which field to put in `NewPrice`.
```
SELECT f.*, IF(weight_count = 1, Price, ReducedPrice) AS NewPrice
FROM fonts AS f
JOIN (SELECT weight, COUNT(*) AS weight_count
FROM... | ```
select *,if(occurences>=2,reducedPrice,price) as newPrice from fonts
left join (Select count(id) as occurences, id,weight from fonts
where fonts.id in(1,2,3,5,6,7) group by weight) t on t.weight = fonts.weight
where fonts.id in(1,2,3,5,6,7);
```
The mysql if keyword reference is here:<https://dev.mysql.com/doc/ref... | select: result based on occurrence of explicit value | [
"",
"mysql",
"sql",
""
] |
I have 2 tables. Player and Stats. Player has the fields: Name, Age, DOB and SSN. Stats has the fields: Tackles, Goals, Assists, and SSN. SSN is a foreign key. How can I write a query to find the stats of players with DOB >= '1994'. DOB is not a foreign key, I was wondering how that could work. | ```
SELECT * FROM Player INNER JOIN Stats ON Player.SSN = Stats.SSN WHERE Player.DOB >= '1994-01-01'
```
If you just want specific fields then specify these instead of SELECT \* | this is a simple Join commmand.
```
SELECT * FROM Stats
INNER JOIN Player
On Player.SSN = Stats.SSN
WHERE DOB > 1994
```
there is an issue from here however as you imply that DOB is a string, not a datetime or Integer with those quotes. you cant compare Strings as numbers like you are trying to do. if DOB is just ye... | Sql: Selecting from other tables | [
"",
"mysql",
"sql",
"database",
"join",
"foreign-keys",
""
] |
I have a function to convert a string to `datetime (101)` format.
But it gives me an error when I convert this value.
```
2016-03-01 00:00:00.0000000
```
And the error is
```
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
```
And my function is ..
```
A... | Too many zeros in the millisecond part. This works fine
```
DECLARE @Value nVarchar(MAX)='2016-03-01 00:00:00.000'
SELECT CONVERT(DATETIME,@Value,101)
```
You can try using `LEFT` like this
```
DECLARE @Value nVarchar(MAX)='2016-03-01 00:00:00.000000'
SELECT CONVERT(DATETIME,LEFT(@Value,23),101)
``` | It is problem your data. It is not converting.
Your data should be like this
```
'2016-03-01 00:00:00.0000000'
```
But you can change your data like this
```
'2016-03-01 00:00:00.000'
``` | Conversion failed when converting date and/or time from character string in sql server | [
"",
"sql",
"sql-server",
""
] |
I'm trying to do something that's very simple to do in other languages but in SQL it's proving rather puzzling.
I have a database with the patient ID as row, and 100 symptoms as columns. Symptoms are binary, 0 or 1 if the patient has it or not. Let's say Patient 1 has 0, 1, 1, ... for coughing, sneezing, headaches, et... | This answer by @GarethD, helped solved the problem: Thanks!
The key is to unpivot your data so that you have one row per patient per symptom, then join this data to itself to get pairs of symptoms, then pivot the joined data back up to get your counts. Since I don't know which DBMS to use, I cannot answer the question... | Your question needs to write functions and using cursors in them.
However, there is an alternative approach:
Suppose you have a table with four columns:
```
a b c d
-------------------------
1 0 1 1
1 1 0 0
0 0 1 0
0 0 0 1
1 1 1 1
0 1 0 1
1 0 1 0
0 1 1 1
0 0 ... | Counting the number of join symptoms | [
"",
"sql",
"data-analysis",
""
] |
I am trying to join two views I created, however I am joining them using their common field (cAuditNumber).
The issue is, once I have done the joins, it will not let me create the view as it cannot have the field name cAuditNumber twice.
Is the cAuditNumber the PK I should use?
How do I correct this and still join t... | Substitute your own column names instead of ColumnA, Column B, etc, but it should follow this format:
```
CREATE VIEW KFF_Sales_Data_Updated AS
SELECT CustSalesUpdated.cAuditNumber
,CustSalesUpdated.ColumnA
,CustSalesUpdated.ColumnB
,CustSalesUpdated.ColumnC
,StkSalesUpdated.ColumnA as StkColumnA
,... | ```
CREATE VIEW KFF_Sales_Data_Updated AS
SELECT csu.cAuditNumber cAuditNumber1 , ssu.cAuditNumber cAuditNumber2
FROM CustSalesUpdated csu
INNER JOIN StkSalesUpdated ssu
ON StkSalesUpdated.cAuditNumber = CustSalesUpdated.cAuditNumber
```
You could add any other column in the select statement from the two tables but ... | SQL Change View Name / Joins | [
"",
"sql",
"sql-server",
"t-sql",
"view",
""
] |
I have a table called `tourn_results` there are multiple records that share the same `tournamentId`.
Example of a `tourn_result` record set
```
uniqueId tournamentId playerRank
1 111 1
2 111 2
3 111 3
4 222 1
5 222 2
6 222 ... | This will delete everything but the rows with the lowest `uniqueid` for each combination of (`tournamentId`,`playerRank`).
```
delete from tourn_results x
where uniqueid <> ( select min(y.uniqueid)
from tourn_results y
where y.tournamentid = x.tournamentid
... | You can add a unique index on the columns you don't want to have duplicates. It will drop all your duplicates.
```
ALTER IGNORE TABLE tourn_result ADD UNIQUE INDEX idx_name (tournamentId, playerRank);
```
The other option is to create a new temp table, insert your duplicates rows and delete them from your actual tabl... | Find duplicates based on two fields and delete them | [
"",
"mysql",
"sql",
""
] |
I have a table `CommentsTable` with columns like, `CommentA, CommentB, CommentC, CommentD, CommentE`.
All comments columns are `VARCHAR (200)`, by default all columns are `NULL` also.
The data looks like:
```
CommentId CommentA CommentB CommentC CommentD CommentE
---------------------------------------... | You can use `ISNULL` like this `ISNULL(',' + CommentA, '')` and write your query like this.
```
SELECT CommentId,
STUFF(
ISNULL(',' + CommentA, '') +
ISNULL(',' + CommentB, '') +
ISNULL(',' + CommentC, '') +
ISNULL(',' + CommentD, '') +
ISNULL(',' + CommentE, ''),1,1,'') as [CommentDetails]
FROM CommentsTable
WHER... | The above answers are correct and no challenge to the accepted answer but in case some columns have empty string instead of null then below might help. Please don't hesitate for a better approach and correct me if it's wrong.
```
SELECT CommentId,
STUFF(
ISNULL(',' + CASE WHEN CommentA= '' THEN NULL ELSE CommentA END... | Multiple column values into a single column as comma separated value | [
"",
"sql",
"sql-server",
""
] |
Im a lil bit stuck here, really hope somebody could help me out.
I couldn't found yet the answer from google.
Ok let say the data is like below:
```
TableName=> Events
| Node_Name| Status |
+----------+-----------+
| Node_1 | Completed |
| Node_1 | Completed |
| Node_2 | Failed |
| Node_2 | Completed |... | To get only the "never failed" nodes:
```
select node_name
from events
group by node_name
having max(status) = 'Completed'
```
To get all nodes with a 'Failed' count:
```
select node_name,
sum(case when status = 'Failed' then 1 else 0 end )
from events
group by node_name
``` | In SQL Server, the `EXCEPT` operator can do this.
```
select node_name
from events
group by node_name
EXCEPT
select node_name
from events
where status<>'Completed' ;
```
**Explanation:** You query **all** different node names, and you remove all names which are not completed. As a result, only those will stay whi... | SQL Query: How to show the opposite result of your query in select statement | [
"",
"sql",
""
] |
I have two tables:
* `Table1` with columns `colA, colB, colC`
* `Table2` with columns `colX, colY, colZ`
I'm trying to get all rows from `Table1` which have `colC` values that match `Table2` on `colZ`.
I tried the following:
```
select Table1.colA,Table1.colB,Table1.colC
from Table1 inner join Table2 on Table1.col... | You can use [`EXISTS`](https://msdn.microsoft.com/en-us/library/ms188336.aspx) like this.
```
select Table1.colA,Table1.colB,Table1.colC from Table1
WHERE EXISTS (SELECT 1 FROM Table2 WHERE Table1.colC = Table2.colZ)
``` | Three options:
1. Use `INNER JOIN` with `DISTINCT`
```
SELECT DISTINCT Table1.colA,
Table1.colB,
Table1.colC
FROM Table1
INNER JOIN Table2 ON Table1.colC = Table2.colZ
```
2. Use `EXISTS`
```
SELECT Table1.colA,
Table1.colB,
... | Join two tables to get common data based on a column | [
"",
"sql",
"sql-server",
""
] |
I'm doing a query on a table in which I have to count all records on different 1 hour interval time (eg from 13:00:00 to 14:00:00). What I'm doing right now is like this:
```
select count (*)
from tabel
where TO_CHAR(ins_ts, 'DD-MON-YYYY HH24') like ('02-GIU-2015 13');
```
RESULT: 23
```
select count (*)
from tabel
... | If you actually want to use an index on the datetime you need to stop using functions on ins\_ts (in the where clause).
```
select TO_CHAR(ins_ts, 'DD-MON-YYYY HH24'),count (*)
from table where
ins_ts >= TO_DATE('01/JAN/2015 00:00:00', 'dd/mon/yyyy HH24:MI:SS')
and ins_ts < TO_DATE('08/JAN/2015 00:00:00', 'dd/mon/... | You want to truncate the time value to the nearest hour and do a count. You have the basic components in your query, you just want a `group by`:
```
select TO_CHAR(ins_ts, 'DD-MON-YYYY HH24') as thehour, count(*)
from tabel
group by TO_CHAR(ins_ts, 'DD-MON-YYYY HH24')
order by min(ins_ts) ;
```
The `order by min(ins_... | SQL Searching multiple interval times on ORACLE DB | [
"",
"sql",
"database",
"oracle",
"datetime",
""
] |
How to display SQL Statements in the log ? I'm using EBeans and it fails to insert for some reasons but I can't see what's the problem.
I tried to edit my config to:
```
db.default.logStatements=true
```
and add this to logback.xml
```
<logger name="com.jolbox" level="DEBUG" />
```
to follow some answers I found o... | Logging has changed with **Play 2.4**. Starting from now, to display the SQL statements in the console, simply add the following line to the conf/logback.xml file:
```
<logger name="org.avaje.ebean.SQL" level="TRACE" />
```
It should work just fine.
As @Flo354 pointed out in the comments, with **Play 2.6** you shoul... | From Play 2.5 Logging SQL statements is very easy, Play 2.5 has an easy way to log SQL statements, built on [jdbcdslog](https://github.com/jdbcdslog/jdbcdslog), that works across all JDBC databases, connection pool implementations and persistence frameworks (Anorm, Ebean, JPA, Slick, etc). When you enable logging you w... | Play 2.4 - Display Ebeans SQL statement in logs | [
"",
"sql",
"logging",
"playframework",
"ebean",
"playframework-2.4",
""
] |
I am using Microsoft SQL Server 2008 R2, and I am trying to compare counted results from the same query I ran the following:
```
select
e.JobTitle,
COUNT(p.BusinessEntityID) [NO. of persons]
from
AdventureWorks2008.person.Person p with (Nolock)
join
AdventureWorks2008.HumanResources.Employee e with ... | You can do this with cte:
```
with cte as(select e.JobTitle,
COUNT(p.BusinessEntityID) [NO. of persons]
from AdventureWorks2008.person.Person p with (Nolock)
join AdventureWorks2008.HumanResources.Employee e with (nolock) on e.BusinessEntityID = p.BusinessEntityID
... | You could use a `join` to search for other rows with the same count but a different job title:
```
; with List as
(
... your query here ...
)
select *
from List l1
join List l2
on l1.[NO. of persons] = l2.[NO. of persons]
and l1.JobTitle > l2.JobTitle -- Filter out duplica... | Compared counted data from the same table | [
"",
"sql",
"sql-server",
""
] |
So data is something like this:
```
ID | START_DATE | END_DATE | UID | CANCELED
-------------------------------------------------
44 | 2015-10-20 22:30 | 2015-10-20 23:10 | 'one' |
52 | 2015-10-20 23:00 | 2015-10-20 23:30 | 'one' |
66 | 2015-10-21 13:00 | 2015-10-20 13:30 | 'two' |
```
There are more ... | I would start with this query:
```
update table t
set cancelled = true
where exists (select 1
from table t2
where t.end_date > t2.start_date and
t.uid = t2.uid and
t.id < t2.id
)
```
An index on `table(uid, st... | This will do the trick without dynamic query nor correlated subqueries, but it consume some memory for the `with` clauses:
```
MERGE INTO Table1
USING
(
with q0 as(
select rownum fid, id, start_date from(
select id, start_date from table1
union all
select 999999 id, null start_date from du... | oracle sql - finding entries with dates (start/end column) overlap | [
"",
"sql",
"oracle",
"date",
"range",
""
] |
I have two tables similar to shown below (just leaving out fields for simplicity).
*Table `lead` :*
```
id | fname | lname | email
---------------------------------------------
1 | John | Doe | jd@test.com
2 | Mike | Johnson | mj@test.com
```
*Table `leadcustom` :*
``... | If your columns are fixed, you can do this with group by + case + max like this:
```
select
fname,
lname,
email,
max(case when name = 'utm_medium' then value end) as utm_medium,
max(case when name = 'utm_term' then value end) as utm_term
from
lead l
join leadcustom c
on l.id = c.leadid
group by
fna... | You can try with [`pivot`](https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx) and `join`:
```
select [id]
, [fname]
, [lname]
, [email]
, [utm_medium]
, [utm_term]
from ( select t2.*
, t1.[name]
, t1.[value]
from [leadcustom] t1
join [le... | Rotate columns to rows for joined tables | [
"",
"sql",
"sql-server",
"join",
"pivot",
""
] |
I am trying to do an INNER JOIN on two tables that have similar values, but not quite the same. One table has a fully qualified host name for its primary key, and the other the hosts short name, as well as the subdomain. It it safe to assume that the short name and the subdomain together are unique.
So I've tried:
``... | So in this case, I used a subquery to get the initial results, and then used a join.
```
SELECT table1.nisinfo.* FROM table1.nisinfo JOIN (SELECT distinct(fqhn) FROM table2.hosts WHERE package = 'bash') AS FQ ON ((SUBSTRING_INDEX(FQ.fqhn, '.', 1)) = table1.nisinfo.shortname);
``` | Try putting your results into a temp table and then view the table to make sure that the columns are as expected.
```
SELECT table1.nisinfo.*, table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com' AS ColID
INTO #temp
FROM table1.nisinfo;
Select *
from #temp INNER JOIN table2.hosts ON @#t... | JOIN on keys that don't have the same value | [
"",
"mysql",
"sql",
"join",
""
] |
I am managing a large databse. I am trying to Join a table. but the data in the Colums dont actualy match. One has dashes and the other has space.
Such GPD 142 pol (Partnumber)in the Company table and GPD-142-pol (PartNumber)in the Customer table.
My query is written like this:
```
SELECT *
FROM CompanyPartsList
... | again doing this will be very slow , a solution would be a trigger to create the correct formatted column on either side
```
SELECT *
FROM CompanyPartsList
JOIN SalesReport
On FordPartsList.[Company Part Number] = Replace(SalesReport.[Customer Part #],'-',' ')
``` | Try replacing characters that can cause the values to be different.
```
SELECT
*
FROM
CompanyPartsList cpl,
SalesReport sr
WHERE
REPLACE(REPLACE(cpl.[Company Part Number],'-',''),' ','') = REPLACE(REPLACE(sr.[Customer Part #],'-',''),' ','')
``` | Sql How to Join a table where data in Colums are alike | [
"",
"sql",
"sql-server",
"database",
""
] |
I want to know how many rows were removed in a certain DELETE operation.
I took [the Microsoft example B](https://msdn.microsoft.com/de-de/library/ms177564.aspx) which is
```
DELETE Sales.ShoppingCartItem
OUTPUT DELETED.*
WHERE ShoppingCartID = 20621;
```
and tried to modify it to return only the `count` of deleted... | Just run your query and get the modified rows
```
DELETE
FROM datacache
WHERE userId=@id
SELECT @@ROWCOUNT
``` | You can not use aggregates in `OUTPUT` clause. You can output any column into table variable instead and count from there:
```
DECLARE @t TABLE(id int)
DELETE FROM Sales.ShoppingCartItem
OUTPUT Deleted.ShoppingCartID INTO @t
WHERE ShoppingCartID = 20621;
SELECT COUNT(*) FROM @t
``` | DELETE ... OUTPUT COUNT(DELETED.*) | [
"",
"sql",
"sql-server",
"output-clause",
""
] |
I want to match up Buyers and Sellers. I'm doing this to make it as simple as possible.
I have a table: tmpSales. In it, I have a TransID, BuyerID, SellerID, Item and Date.
Sometimes buyers are sellers too, and vice versa.
What I want is a record where a buyer sold to a seller and that same seller sold to that same ... | You can easily limit the data in your select to be just one way by selecting which one is the first, like this:
```
SELECT *
FROM [dbo].[tmpSales] T1
INNER JOIN [dbo].[tmpSales] T2
ON T1.[BuyerID] = T2.[SellerID]
AND T2.[BuyerID] = T1.[SellerID]
AND T2.[BuyerID] > T1.[BuyerID]
```
So this way the one that has bigger ... | You can use the following query to retrieve all the mutual map
```
SELECT DISTINCT T.BuyerID AS ID1,T.SellerID AS ID2
FROM [dbo].[tmpSales] T
WHERE EXISTS (SELECT *
FROM [dbo].[tmpSales] T1
WHERE T1.BuyerID = T.SellerId
AND T1.SellerID = T.BuyerID)
```
If you want to c... | Getting mutual matches in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.