Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have been struggling with the concept of combining results of two queries together via a join on a common table and I was hoping I could gain some assistance. The following is a rough guide to the tables:
```
dbo.Asset (not returned in the SELECT statement, used for joins only)
- dbo.Asset.AssetID
- dbo.Asset.Cata... | Think I see the issue. Assuming that the joins themselves are correct (ie your columns do relate to each other), the order of your joins is a little off - when you join WorkOrder to WorkOrderSpare, neither of those two tables relate back to any table you've identified up until that point in the query. Think of it as jo... | I think you were close. As a slightly different approach to joining, try this:
```
SELECT CatalogueGroup.CatalogueGroupName,
Catalogue.CatalogueNumber,
Catalogue.CatalogueDescription,
Catalogue.CatalogueID,
Asset.IsActive,
WorkOrderSpare.WorkOrderSpareDescription,
WorkOrderSpare.ActualQuantity,
WorkOrder... | Joining Two Queries onto a Shared Table | [
"",
"sql",
"sql-server",
""
] |
If I have to write this query in SQL Server:
```
SELECT *
FROM Table1
WHERE data BETWEEN interval1 AND interval2
```
* `interval1` is `fld1` if `fld1` >= '2014-1-1' otherwise it's '2014-1-1'
* `interval2` is `fld2` if `fld2` is <= '2014-12-31' otherwise it's '2014-12-31'
How can I write it without using variables?... | ```
SELECT *
FROM
Table1
WHERE
data BETWEEN interval1 AND coalesce(interval2, '2014-12-31')
and data between '2014-1-1' and '2014-12-31'
``` | Try this
```
select * from Table1
WHERE data between
case when fld1 < '20140101' then '20140101' else fld1 end and
case when fld2 >'20141231 then '20141231' else fld2 end
``` | SQL between min of two values | [
"",
"sql",
"sql-server",
"between",
""
] |
I need to find the missing id's from the table `#a` below:
```
id |SEQ|Text
1 |1 |AA
1 |3 |CC
1 |4 |DD
1 |5 |EE
1 |6 |FF
1 |7 |GG
1 |8 |HH
1 |10 |JJ
2 |1 |KK
2 |2 |LL
2 |3 |MM
2 |4 |NN
2 |6 |PP
2 |7 |QQ
3 |1 |TT
3 |4 |ZZ
3 |5 |XX
```
The max and min SEQ of the table ... | You use recursive CTE to [generate a set of numbers](http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1). It is quite inefficient way to do it (see charts for generating 50K numbers [here](http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2)). I'd recommend to have a persisted table of number... | Two things that come to my mind are:
* Use a numbers / tally table. Either by creating a normal table or create a virtual using CTE. Use that to find numbers that don't exist.
* If there's not a lot of missing numbers, you can use a trick with row\_number() to find the ranges of numbers that don't have any gaps with s... | I need to find the missing Id's from the table after checking the min and max id's from another table | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have table t1
```
ID NAME AGE GENDER BALANCE
----- ----- --------- ----- ---------
1001 John 10 M 10
1002 Meena 5 F 0
1003 Nikh 11 M 0
1004 divs 7 F 0
1005 neha 4 F 0
```
from second row, if Gender ... | How about something like this?
```
with sample_data as (select 1001 id, 'John' name, 10 age, 'M' gender, 10 balance from dual union all
select 1002 id, 'Meena' name, 5 age, 'F' gender, 0 balance from dual union all
select 1003 id, 'Nikh' name, 11 age, 'M' gender, 0 balance fro... | ```
select ID, NAME, AGE, GENDER, @b:=if(GENDER='M', @b+AGE, @b-AGE) BALANCE
from t1, (select @b:=0) b
```
[**Demo on sqlfiddle.com**](http://sqlfiddle.com/#!9/cc5ec/1) | Calculation in two columns of different row in sql | [
"",
"sql",
"oracle",
""
] |
Refering to this:
[Is there any difference between GROUP BY and DISTINCT](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct)
```
Given a table that looks like this:
name
------
barry
dave
bill
dave
dave
barry
john
This query:
SELECT name, count(*) AS count FROM table GR... | `Distinct` and `Group By` are going to give you different results. To get the results you expect you'll want to use
```
Person.group(:name).count
(1.2ms) SELECT COUNT(*) AS count_all, name AS name FROM "people" GROUP BY "people"."name"
=> {"Dan"=>3, "Dave"=>2, "Vic"=>1}
```
Seen above, group will return things as a ... | Note that the accepted answer will return a hash:
```
Tagging.joins(:tag).group(:name).size
(0.4ms) SELECT COUNT(*) AS count_all, `name` AS name FROM `taggings` INNER JOIN `tags` ON `tags`.`id` = `taggings`.`tag_id` GROUP BY `name`
=> {"applesauce"=>1, "oranges"=>2}
```
But what if you want to return the count p... | GROUP BY and COUNT using ActiveRecord | [
"",
"sql",
"ruby-on-rails",
"ruby",
"postgresql",
"activerecord",
""
] |
I have this table:
```
table1
+------+----------+-----------+----------+
| id | org1 | org2 | org3 |
+------+----------+-----------+----------+
| 1 | HR | (NULL) | Staff |
+------+----------+-----------+----------+
| 2 | (NULL) | IT | Dev |
+------+----------+-----------+... | **UPDATE:**
Based on the **cars10** answer need to switch the order `COALESCE(org2,org3)` and take into account when all 3 columns are `NOT NULL`
```
SELECT id, o1,
CASE WHEN o2!=o1 THEN o2 END o2,
CASE WHEN o3!=o2 THEN o3 END o3
FROM
(
SELECT id
,COALESCE(org1,org2,org3) o1
,IF((org1 IS NOT NULL) AND... | Use `coalesce()` and a subquery
```
select id, o1,
CASE WHEN o2!=o1 THEN o2 END o2,
CASE WHEN o3!=o2 THEN o3 END o3
FROM
( select id, coalesce(org1,org2,org3) o1,
coalesce(org2,org3) o2,
org3 o3 from tbl ) t
```
**UPDATE**
The previous answer was not... | How to shift column values in MySQL? | [
"",
"mysql",
"sql",
""
] |
This is the function that I am trying to create
```
CREATE FUNCTION fnGetValue
(
@WhereClause VARCHAR(256)
)
RETURNS TABLE
AS
RETURN
SELECT A.Name, B.Value
FROM A
INNER JOIN B ON A.Akey = B.AKey
WHERE + @WhereClause +
GO
```
The parameter `@WhereClause` is built from my PHP, something like
`... | I think that you would be better off building the SQL function in PHP and calling that. Using your approach it would be very hard to guarantee what went into the query and it's just asking for an SQL injection attack.
Using something similar to (but not necessarily) [Laravel](http://laravel.com/docs/4.2/queries "Larav... | Here the `where clause` is dynamically send, hence you have to use `dynamic sql`;
One limitation here is in a `function` you cannot use `dynamic sql`.
> Only functions and some extended stored procedures can be executed
> from within a function.
see ==> [Getting an error when executing a dynamic sql within a functio... | How to pass the actual where clause to SQL function? | [
"",
"sql",
"sql-server",
""
] |
I have some data coming from a source in my Oracle database.
If a particular Office\_ID has been deactivated and it has all three clients (A,B,C) for a particular day, then we have to check whether all clients have gone. If yes, then we need to check whether timeframe for all clients is within 10 Minutes.
If this rep... | A solution using the [`COUNT`](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions039.htm#i82697) [analytic function](http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions004.htm) with a `RANGE BETWEEN INTERVAL '10' MINUTE PRECEDING AND INTERVAL '10' MINUTE FOLLOWING` that avoids self-joins:
[SQL... | To identify records you can join table to it self three times like this:
```
SELECT
a.*, b.*, c.*
FROM FailLog a INNER JOIN
FailLog b ON b.OFFICE_ID = A.OFFICE_ID AND
a.CLIENT = 'A' AND
b.CLIENT = 'B' AND
b.ACTIVITY_DAY = a.ACTIVITY_DAY INNER JOIN
FailLog c ON c.OFFICE_ID = ... | Select records all within 10 minutes from each other | [
"",
"sql",
"oracle",
"plsql",
"oracle10g",
""
] |
I have the following situation:
1 Table for a Warehouse where I have: the ProductID, the qty and the address
1 Table for the Stores Where I have: The ProductID and qty
1 table for the Stores Storage addresses
What I need to know is if a product is "in Stock" or "out of Stock" using the criteria that for a product to ... | Simply remove the QtyStore column from your `GROUP BY` clause, and put `SUM(QtyStore)` in the `SELECT`-part of your query.
```
SELECT Product_Cod, qty_wh, SUM(QtyStore) AS TotalQtyStore,
CASE
WHEN sum(QtyStore) BETWEEN 1 AND 20000 THEN
CASE
... | You could try maxing qty\_wth then summing QtyStore like so:
```
SELECT Product_Cod, max(qty_wh) as qty_wh, sum(QtyStore) as QtyStore,
CASE
WHEN sum(QtyStore) BETWEEN 1 AND 20000 THEN
CASE
WHEN qty_wh > 0 THEN 'In Stock'
... | SQL query using case and Group by aggregation | [
"",
"sql",
"sql-server",
""
] |
I have a table that looks like this:
```
+----+-------+---------+--------+--------+
| id | meta1 | meta2 | value1 | value2 |
+----+-------+---------+--------+--------+
| 1 | foo | bar | 0.1 | 0.01 |
| 1 | baz | quux | 0.2 | 0.01 |
| 1 | lorem | ipsum | 0.1 | 0.05 |
| 2 | dolor | sit ... | You want all records for which no better record (ie. with lower value1 or same value1 and lower value2) exists:
```
select *
from mytable
where not exists
(
select *
from mytable better
where better.id = mytable.id
and
(
better.value1 < mytable.value1
or
(better.value1 = mytable.value1 and bett... | You can use `not exists`:
```
SELECT t.*
FROM test t
WHERE NOT EXISTS (SELECT 1
FROM test t2
WHERE t2.id = t.id AND
(t2.value1 < t.value1 OR
(t2.value1 = t.value1 and t2.value2 < t.value2) )
);
```
An alternative met... | Select a single result from groups by the min of two values | [
"",
"mysql",
"sql",
""
] |
I have a table with the following values
```
id Level Threshold
1 1 5000
2 2 10000
3 3 15000
```
What i need to achieve is that when i pass 6000 , I need to get Level 1.
12000 Level 2 and 16000 Level 3?
```
6000 - Level 1
12000 - Level 2
16000 - Level 3
```
Can someone let me know how this can be... | What I understood from your question is that when user will give 6000 then it should check which value is less than 6000 so it's 5000 and it's level is 1 same as when 12000 so it has two output as 5000 (level1) and 10000 (level2) but you need maximum one so it is 10000 (Level2). So according to this understanding the q... | [**Fiddle Demo**](http://sqlfiddle.com/#!3/c68682/1)
```
create table temp (id int, level int, Threshold int);
insert into temp values (1,1, 5000);
insert into temp values (2,2, 10000);
insert into temp values (3,3, 15000);
select max(LEVEL) from temp where Threshold<= 8000; (8000 or any other value)
``` | Find the Range from a Table | [
"",
"sql",
"sql-server",
""
] |
I know it's kind of a confusing question so let me first explain the scenario.
The scenario is:
there are 3 tables
1. `service_master (id, name, cost, duration, visit_count, remarks)`
2. `product_master (id, name, cost)`
3. `sell (id, item_id, item_type)`
so, in **`sell`** table
**`id`** goes for the `primary key`... | If IDs are unique over both, the service and the product table, (perhaps by using a sequence) you could just:
```
SELECT
sell.id sell_id
, sell.item_type
, item_detail.id
, item_detail.name
, item_detail.cost
FROM sell
JOIN
(SELECT id, name, cost FROM service_master
UNION ALL
SELECT id, name, cost FR... | *How* to select depends on *what* you want to select of course :-)
Here is an example on how to select all data:
```
select s.*, sm.name, sm.cost, sm.duration
from sell s
join service_master sm on sm.id = s.item_id
where s.item_type = 'SERVICE'
union all
select s.*, pm.name, pm.cost, null
from sell s
join product_mas... | how to fetch data when a single column contains values from 2 different tables? | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
Hi I have a database full of records of players and theirs match Stats.
Example:
[](https://i.stack.imgur.com/LoCoL.png)
( number means goals scored in match )
What I'm, trying to do is, select top X players that scores most of goals in Season.
I'm trying som... | You need to `SUM` number field and order by it like this;
```
SELECT TOP 10
playerID,
SUM([number]) as goals,
[league],
[yearID],
SUM([YellowCard]) as YellowCards,
SUM([RedCard]) as RedCards,
FROM [ms4033].[dbo].[Shooter]
WHERE yearID=28 AND league=4
GROUP BY playerID, leag... | ```
select top 10
t.[playerID]
,t.totalgoals
,s.[league]
,s.[yearID]
,s.[YellowCard]
,s.[RedCard] from (
SELECT -- TOP 10
[playerID]
,sum([number]) as totalgoals
,[league]
,[yearID]
-- ,[YellowCard]
-- ,[RedCard]
FROM [ms4033].[dbo].[Shooter]
where yearID=28 AND league=4
group by playerID,[league],[year... | SQL - select top 10 rows with the highest number (counted) | [
"",
"sql",
"sql-server",
""
] |
This is a slightly strange use case admittedly, but how do you order the results of a simple union like this alphabetically?
```
select name
from Reviewer
union
select model
from Car;
``` | Ironically, in many databases, your query *would* return the values in alphabetical order. The sorting is done during the duplicate removal for `union`.
Of course, you can't depend on that. So, you should include an `order by` clause:
```
select name
from Reviewer
union
select model
from Car
order by name;
```
The ... | ```
select val
from (
select name as val
from Reviewer
union
select model as val
from Car
) as x
order by val
``` | SQL: How to order a union alphabetically? | [
"",
"sql",
""
] |
In Table 1, I have customer ID and the list of Items the customer ID has purchased.
**Table 1**
```
Customer ID | Item Code
------------------------
1000 | 10
1000 | 20
1000 | 30
1000 | 40
2000 | 10
2000 | 60
2000 | 90
2000 | 100
-----------------------... | Updating the query as OP got updated and shows recursion.
If you want to **add a column** in Table 1 to show precedence data. Here how you can accomplish it.
```
ALTER TABLE Table1
ADD Result int
GO
;WITH CTE([This has Precedence], [Over This])
AS
(
--First find the top level ... | Doing an update, assuming those are your real column names:
```
ALTER TABLE Table1
ADD result int
UPDATE a
SET result = [Item Code] - [This has precedence]
from Table1 a
inner join Table2 b
on a.[Item Code] = b.[Over this]
``` | How do I delete values from a column based on a Hierarchy in a given table? | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I need to examine ACCT\_NUMS values om TABLE\_1. If the ACCT\_NUM is prefixed by "GF0", then I need to disregard the "GF0" prefix and take the rightmost 7 characters of the remaining string. If this resulting value is not found in account\_x\_master or CW\_CLIENT\_STAGE, then, the record is to be flagged as an error.
... | As other people said, your concern is valid.
I'd make two changes to your query.
1) To avoid having negative value in the `SUBSTRING` parameter we can rewrite it using `STUFF`:
```
SUBSTRING(ACCT_NUM, 4, LEN(ACCT_NUM) - 3)
```
is equivalent to:
```
STUFF(ACCT_NUM, 1, 3, '')
```
Instead of extracting a tail of a s... | You have a very valid concern, because SQL Server will rearrange the order of evaluation of expressions in the `WHERE`.
The only way to guarantee the order of operations in a SQL statement is to use `case`. I don't think there is a way to catch failing calls to `substring()` . . . there is no `try_substring()` analogo... | Is this simple UPDATE SQL an error waiting to happen? How to rewrite it? | [
"",
"sql",
"sql-server",
""
] |
I have a table like this:
```
+---------+------------+--------+--------------+
| Id | Name | Status | Content_type |
+---------+------------+--------+--------------+
| 2960671 | PostJob | Error | general_url |
| 2960670 | auto_index | Done | general_url |
| 2960669 | auto_index | Done | document ... | You want this
```
select Content_type,
count(Status)
from Indexing
where Status='Error'
group by Content_type;
``` | GROUP BY should do the job:
```
SELECT Content_type, COUNT(Id) from Indexing where Status = 'Error' GROUP BY Content_type;
```
**Explanation:**
`COUNT (x)` counts the number of rows in the *group*, `COUNT (*)` would do the same.
`COUNT (DISTINCT x)` counts the number of distinct values in the *group*.
Without a `G... | SQL select counts on 1 value | [
"",
"sql",
""
] |
I have this below query
```
SELECT FullUrl
,Title
,NextWebGroupId
,TimeCreated
FROM AllWebsTest
WHERE (Title LIKE '%' + @Title + '%')
OR (FullUrl LIKE '%' + @FullUrl + '%')
```
Title and FullURL are parameter through TextBox.
What I expect is,
1. If I put text in Title textbox and search, it doesnt ... | Try this query:
```
SELECT FullUrl
,Title
,NextWebGroupId
,TimeCreated
FROM AllWebsTest
WHERE (Title LIKE '%' + ISNULL(@Title, '') + '%')
AND (FullUrl LIKE '%' + ISNULL(@FullUrl, '') + '%')
```
Take a look at this [SQLFiddle](http://sqlfiddle.com/#!3/ce9ad/7) and confirm that this behaviour is what yo... | Most likely something along the way is using `NULL` instead of an empty string, resulting in a `WHERE Title LIKE NULL` which will fail. Try the following instead, explicitly checking for the null case:
```
SELECT FullUrl, Title, NextWebGroupId, TimeCreated
FROM AllWebsTest
WHERE (@Title IS NULL OR Title LIKE '%' + @T... | SQL Where, LIKE , OR combination issue with Blank textBox | [
"",
"sql",
"asp.net",
"sql-server",
""
] |
I'd like to get a count of negative values and positive values for each id.
[Sample Fiddle](http://sqlfiddle.com/#!4/db410)
`ID=1 has 2 positive and 0 negative transactions. etc.`
```
with trans_detail as
(
select 1 as trans_id, 100 as trans_amount from dual union all
select 1 as trans_id, 200 as trans_amount ... | Count 1 each time you see a positive or negative amount and sum that up.
```
select trans_id,
sum(case when trans_amount >=0 then 1 else 0 end) as pos_amt,
sum(case when trans_amount < 0 then 1 else 0 end) as neg_amt
from trans_detail
group by trans_id
```
<http://sqlfiddle.com/#!4/db410/12> | ```
select trans_id,
nvl(sum(case when trans_amount < 0 then 1 end),0) as neg,
nvl(sum(case when trans_amount > 0 then 1 end),0) as pos
from trans_detail
group by trans_id
```
SQL Fiddle: <http://sqlfiddle.com/#!4/db410/15> | How to get count of postitive and negative numbers per ID? | [
"",
"sql",
"oracle",
"count",
"window-functions",
""
] |
I'm trying to create a Update from Select where in a specific case (88) the previous value should be used to update the column field
```
UPDATE myTable
SET MyDateCol = CASE MYSelect.Indicator
WHEN 88 THEN @previosValue
ELSE MYSelect.NewValue
FROM myTable
INNER JOIN ( ... ) A... | Please try the below query.
It has optimized your query and also takes care of cases where there are repeated `88` values. In my case I've used `NULL` instead of `88`.
> Can we have two rows in succession that both have an 88 indicator? –
> Damien\_The\_Unbeliever
```
CREATE TABLE #temp(
BestellDetailId int, row_num ... | ```
UPDATE myTable
SET MyDateCol = CASE MYSelect.Indicator
WHEN 88 THEN (select lag(newvalue) over(order by newvalue) from MySelect) -- @previosValue
ELSE MYSelect.NewValue
FROM myTable
INNER JOIN ( ... ) AS MYSelect
ON myTable.ID = MYSelect.ID
```
This is assuming the previ... | sql case when newValue else previousValue | [
"",
"sql",
"sql-server",
"select",
"sql-update",
"case",
""
] |
I have the following stored procedure with four parameters.
Stored procedure `spTest`:
```
CREATE PROCEDURE spTest
@Name varchar(20) = '',
@Address varchar(100) = '',
@City varchar(50) = '',
@Pin varchar(50) = ''
AS
DECLARE @DynamicWhere varchar(max)
DECLARE @Query varchar(max)
/* Here I ... | It's called catch-all queries and it basically goes like this:
```
CREATE PROCEDURE spTest
@Name varchar(20) = '',
@Address varchar(100) = '',
@City varchar(50) = '',
@Pin varchar(50) = ''
AS
SELECT *
FROM Test_Table
WHERE (@Name = '' OR Name = @Name)
AND (@Address = '' OR Address = @... | You can use ISNULL and NULLIF also in this case:
below code should work :
```
CREATE PROCEDURE spTest
@Name varchar(20) = '',
@Address varchar(100) = '',
@City varchar(50) = '',
@Pin varchar(50) = ''
AS
SET @Name=NULLIF(@Name,'')
SET @Address=NULLIF(@Address,'')
SET @City=NULLIF(@City,'')... | SQL Server 2008 R2: Prepare Dynamic WHERE Clause | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
We have a file that needs to be imported that has dates in it. The dates are in a format that I have not seen before and the day part can vary in length (but not the month or year seemingly) and position based on wether the number is double digit or not, i.e.
Dates:
```
13082014 is 13th February 2014
9092013 is 9th ... | LPAD a zero when it is missing so to always get an eight character date string. Here is an example with Oracle, other DBMS may have other string and date functions to achieve the same.
```
select to_date(datestring, 'ddmmyyyy')
from
(
select lpad('13082014', 8, '0') as datestring from dual
union all
select lpad(... | One of the simple way is using STUFF.
example:
```
select STUFF(STUFF('13082014 ',3,0,'/'),6,0,'/');
//result: 13/08/2014
```
Good luck. | Format date where the position of the parts is variable | [
"",
"sql",
"datetime",
""
] |
I'm currently building a simple view and need to combine both the `First Name` and `Last Name` columns to create a new `Customer` column. If a `First Name` and `Last Name` are not provided I'd like to change this new combined value to 'Name Not Provided'.
Currently I use a simple select statement:
`LastName + ', ' + F... | ```
SELECT Customer = CASE WHEN FirstName IS NULL AND LastName IS NULL
THEN 'Name Not Provided'
WHEN FirstName IS NULL AND LastName IS NOT NULL
THEN LastName
WHEN FirstName IS NOT NULL AND LastName IS NULL
... | ```
SET CONCAT_NULL_YIELDS_NULL ON
SELECT ISNULL(LastName + ', ' + FirstName, 'Name Not Provided') AS Customer
``` | SQL: Combine First Name and Last Name columns but if Null change to 'Name Not Provided' | [
"",
"sql",
"t-sql",
""
] |
I have a column which represent the values as seconds. The Result of this column are as (465109,352669,351949.... etc). I need the results to be always in decimals and less then one. So the 465109 result should come as 0.465109, Similarly the 352669 should come as 0.352669.
Is there a way i can do that in SQL Sever 20... | Can you just use division?
```
select seconds / 1000000.0
```
Note the `.0` so it does floating point division rather than integer division.
If you want these as a decimal, then cast afterwards:
```
select cast(seconds / 1000000.0 as decimal(10, 6))
``` | A trick is this:
```
CAST('.' + REPLACE(CAST(@value AS varchar(30)), '.', '') AS Numeric(28,10))
```
And as a math solution:
```
CAST(@valueAS Numeric(28,10)) / (POWER(10, LEN(CAST(FLOOR(@value) AS varchar(20)))))
``` | SQL Server: Converting a number to decimal | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
CREATE TABLE WRITTEN_BY
( Re_Id CHAR(15) NOT NULL,
Pub_Number INT NOT NULL,
PRIMARY KEY(Re_Id, Pub_Number),
FOREIGN KEY(Re_Id) REFERENCES RESEARCHER(Re_Id),
FOREIGN KEY(Pub_Number) REFERENCES PUBLICATION(Pub_Number));
CREATE TABLE WORKING_ON
( Re_Id CHAR(15) NOT NULL... | You haven't said which platform you're on but try this. It handles the case where there are ties as well.
```
select g.Pro_Code, g.Re_Id, g.numpublished
from
(
SELECT work.Pro_Code, WORK.Re_Id, count(WRITE.pub_number) as numpublished
FROM WORKING_ON WORK JOIN WRITTEN_BY AS WRITE ON WORK.Re_Id = WRI... | If you are using MS SQL, this should work:
```
With cte as (
select a.Re_Id, Pub_Number,Pro_Code, COUNT(distinct Pub_Number) as pubs
from WRITTEN_BY a
inner join WORKING_ON b
on a.Re_Id = b.Re_Id)
SELECT Re_Id,pubs from cte
HAVING pubs = MAX(pubs)
GROUP BY Re_Id
``` | SQL query : SELECT | [
"",
"sql",
"select",
""
] |
I am trying to update the amount using Join but getting exception:
```
UPDATE tab1
SET tab1.total_adjusted_cost = tab1.total_adjusted_cost + t1.total
FROM table1 tab1,
(SELECT tab3.name, tab3.add, SUM(tab2.amount) AS total
FROM table2 tab2,
table3 tab3,
table4 tab4
... | Try to use merge
```
merge into table1 tab1
using
(
SELECT tab3.name, tab3."add", SUM(tab2.amount) AS total
FROM table2 tab2,
table3 tab3 ,
table4 tab4
WHERE tab2.id = tab3.id
AND tab3.id = tab4.id
AND tab4.indicator ='Y'
GROUP BY tab3.name,
tab3."add"
)t1
on(tab1.i... | `group` is a keyword in sql. You have to escape it.
```
UPDATE tab1 SET tab1.total_adjusted_cost = tab1.total_adjusted_cost + t1.total
FROM table1 tab1,
(SELECT tab3.name, tab3."add", SUM(tab2.amount) AS total
FROM table2 tab2,
table3 tab3 ,
table4 tab4
WHERE tab2.id = tab3.id
AND tab3.id ... | Oracle Update Query using Join | [
"",
"sql",
"oracle",
"sql-update",
"ora-00933",
""
] |
I want to write a select query that will compare the two table. By comparing it should tell that what record are need to be updated, inserted or deleted from table 2.
Contents of the tables:
```
Table 1
----- ---------
id name
----- ---------
1 shubham
2 ravi
3 aman
4 vijay
Table 2
----- ---... | I would do it like here:
```
select coalesce(t1.id, t2.id) id, t1.name new_name, t2.name old_name,
case when t1.id is null then 'row deleted'
when t2.id is null then 'row inserted'
when t1.name <> t2.name
or t1.name is null and t2.name is not null
or t1.name is not null an... | No set operators involved in this solution, but they are probably easier to use when there are more than just a couple of columns to compare:
```
select coalesce(s.id, d.id) id
, coalesce(s.name, d.name) name
, case when s.id is null then 'D'
when d.id is null then 'C'
when s.name != ... | Compare two tables and select the record that is no in table 2 | [
"",
"sql",
"oracle",
""
] |
I'm using SQL Server 2012.
I have created a trigger the code is below.
I'm slightly confused though as running an update query on my table I get an error message 'Violation of PRIMARY KEY constraint'. However where I query the table the value I'm updating doesn't exist in the table? directory is the primary key colum... | Your `UPDATE` statements will update the entire table - not just those rows that have been modified. That's *usually* not what you want.
You'll need to add a `JOIN` between your `Inserted` pseudo table and the actual underlying data table that you want to update.
```
if @permission = 1
begin
update mytable
... | In your trigger, your first UPDATE doesn't have a WHERE clause. And the second one has a WHERE clause that doesn't reference the table being updated.
That means it's going to try to update every row in the table with the same values from the inserted table.
Also your trigger isn't coded to handle inserts/updates that... | primary key violation even though record doesn't exist | [
"",
"sql",
"sql-server",
"triggers",
"sql-server-2012",
""
] |
I'm trying to query the SQL database for all lines where the date is after a date given through user input. I've run into a variety of errors from "incorrect syntax near" when I surround my date with "#" to "arithmetic overflow error converting expression to". My current code looks like this:
```
inputdate = InputBox(... | The primary issue is that dates must be enclosed in single-quotes. Here is a complete working example (minus a valid connection string) that should explain how to achieve your objective. Note that you will also want to switch to the ISO date format, in which the order is Year-Month-Day (`YYYY-MM-DD`).
```
Sub UpdateRe... | Dates for SQL Server should be formatted as a date or date/time, qualified with single-quotes:
**Date** in ISO unseparated date format
```
querydate = "(DTG > '" & Format(inputdate, "yyyymmdd") & "')"
```
**Date/Time** in ISO 8601 format
```
querydate = "(DTG > '" & Format(inputdate, "yyyy-mm-ddThh:mm:ss.000") & "'... | VBA variable in SQL date query | [
"",
"sql",
"vba",
"date",
"variables",
""
] |
When I try to run below update query, It takes about 40 hours to complete. So I added a time limitation(Update query with time limitation). But still it takes nearly same time to complete.Is there any way to speed up this update?
EDIT: What I really want to do is only get logs between some specific dates and run this ... | Log tables can easily fill up with tons of rows of data each month and even the best indexing won't help, especially in the case of a `LIKE` operator. Your `log_detail` column is 100 characters long and your search query is `CONCAT("%",user.userID,"%")`. Using a function in a SQL command can slow things down because th... | First, the right place to put the time limitation is in the `where` clause, not an `if`:
```
update logs l left join
user u
on l.log_detail LIKE concat("%", u.userID)
set l.userid = u.userID
where l.log_time between '2015-08-11 00:39:41' AND '2015-08-01 17:39:44';
```
If you want to set the others t... | How to increase query speed with using like command | [
"",
"mysql",
"sql",
""
] |
```
Dim sel As String = "select * from personal_i where number= @number"
Dim adapter As New SqlDataAdapter(sel, conn)
adapter.SelectCommand.Parameters.AddWithValue("@number", Label61.Text)
Dim dataset As New DataSet
adapter.Fill(dataset)
Label1.Text = dataset.Tables(0).... | You are looking for the format function.
```
Label1.Text = Format(dataset.Tables(0).Rows(0).Item(6).ToString, “Short Date”)
``` | I would suggest something like :
```
Dim sel As String = "select * from personal_i where number= @number"
Dim adapter As New SqlDataAdapter(sel, conn)
adapter.SelectCommand.Parameters.AddWithValue("@number", Label61.Text)
Dim dataset As New DataSet
ad... | How to display only the date from sql result | [
"",
"sql",
"asp.net",
"vb.net",
""
] |
One model separated by records with dates and same verification codes.
I want to select and group same records by verification code and select dates range. I wrote next sql, but his executing is to long..
```
SELECT
(
SELECT DATE
FROM user_day_status
WHERE ... | You don't need to do a self join at all:
Check here:
<http://www.sqlfiddle.com/#!9/acf12/3>
Basically:
```
SELECT MIN(uds1.DATE) AS DATE_FROM,
MAX(uds1.DATE) AS DATE_TO,
uds1.USER_ID,
uds1.VERIFICATION_TOKEN,
uds1.DESCRIPTION
FROM user_day_status uds1
GROUP BY uds1.USER_ID,
... | Does this work for you :
```
SELECT MIN(uds1.DATE) AS DATE_FROM, MAX(uds1.DATE) AS DATE_TO, uds1.USER_ID,uds1.VERIFICATION_TOKEN,uds1.DESCRIPTION
FROM user_day_status uds1
JOIN user_day_status uds2 ON uds1.VERIFICATION_TOKEN = uds2.VERIFICATION_TOKEN
GROUP BY uds1.VERIFICATION_TOKEN
``` | How to Optimaze this sql | [
"",
"mysql",
"sql",
"optimization",
""
] |
I am new to Oracle PL/SQL, although I have a lot of experience with SQL.
At the moment I am trying to convert a couple of T-SQL statements to PL/SQL. I am trying to execute the following code, but I get some errors.
If the table does not exist yet, then the error is: Table or view does not exist.
But when I run the qu... | Change:
```
DECLARE
cnt NUMBER;
stmt VARCHAR2(1000) := 'CREATE TABLE LAST_LOG_ARCHIVE (LAST_LOG_ARCHIVE TIMESTAMP NULL)';
BEGIN
SELECT COUNT(*) INTO cnt FROM all_tables WHERE table_name = 'LAST_LOG_ARCHIVE';
IF (cnt = 0) THEN
EXECUTE IMMEDIATE stmt;
END IF;
SELECT COALESCE((
SELECT LAST_LOG_ARCHIVE FRO... | your second query needs the INTO statement
```
SELECT COALESCE((
SELECT LAST_LOG_ARCHIVE FROM LAST_LOG_ARCHIVE WHERE ROWNUM = 1
), TO_TIMESTAMP('2015-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')) AS LAST_LOG_ARCHIVE
INTO l_someVariable
FROM dual;
```
remember to declare the `l_someVariable` in the `DECLARE... | Excute SELECT after CREATE in Oracle PL/SQL | [
"",
"sql",
"oracle",
"plsql",
"select-into",
""
] |
There are several status an the status table. I want query like that.
```
select * from command where status <> 's' and status<> 'sc'
```
But query retrieve data with 'Status' S.
What was the issue on that? | The checks `Col <> 's'` depends on the collation of the columns. If the collation is case insensitive, then `'S' = 's'` and your checks will not return `S`. If your collation is case sensitive which I believe is the case, will return `S`.
For example note the following two collations `Latin1_General_CI_AS_KS_WS` and `... | Is the status in the DB `S` or `s`?
Try
```
select * from command where lower(status) NOT IN ('s', 'sc')
``` | Two Where conditions on same column | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Why `"where SomeDate between getdate() and DATEADD(m, -1, getdate()))" -` not working?
(I try calculate some value over last month) | You should use other way
```
where SomeDate between DATEADD(m, -1, getdate()) and getdate()
``` | Because when you use `between` the *lower* value needs to go first. So, you want:
```
where SomeDate between DATEADD(month, -1, getdate()) and getdate()
``` | between getdate() and DATEADD(m, -1, getdate())) on where clause | [
"",
"sql",
""
] |
So I'm playing around with SQL window functions following on-line help tutorials using AdventureWorks 2012.
I selected out data from the below query into a new table
```
SELECT sh.CustomerID AS AccountID,
sd.SalesOrderDetailID AS TransactionID,
sh.OrderDate AS TransactionDate,
sd.LineTotal AS Amount
INTO Transactions... | If you order by a non-unique column there's no guaranteed result set.
In your case the result is exactly what you request, a cumulative MIN/MAX, there's a `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` automatically added to your query due to the `ORDER BY`. Additionally the `ORDER BY` in the Windowed Aggregate Fu... | You are not very explicit about your intent, but it sounds like you want the `min/max` for each `account/transactionDate` grouping. If that's the case, you probably didn't mean to put `transactionDate` in the `order by` clause of the window function.
I think you meant to do this instead:
```
MIN(Amount) OVER(Partitio... | SQL windows function using MAX not giving expected result | [
"",
"sql",
"sql-server",
"aggregate-functions",
""
] |
I'm trying to determine withing if If I should create or alter and trigger. My Code is below.
```
IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
ALTER TRIGGER Sales.bonus_reminder
ON Sales.SalesPersonQuotaHistory
AFTER INSERT
AS RAISERROR ('Notify Compensation', 16, 10);
else
CREATE TRIGG... | If you don't want to the *create trigger* statement as dynamic SQL, then you can do something like this:
```
IF OBJECT_ID(N'Sales.bonus_reminder', N'TR') IS NOT NULL
exec sp_executesql N'DROP TRIGGER Sales.bonus_reminder';
GO
CREATE TRIGGER Sales.bonus_reminder
ON Sales.SalesPersonQuotaHistory
WITH ENCRYP... | Using [this articular](https://www.mssqltips.com/sqlservertip/4640/new-create-or-alter-statement-in-sql-server-2016-sp1/) as my source of truth. here is the short answer.
As of `SQL Server 2016 sp1` you can use `create or alter` statements instead of other drop and create methods (my personal fav till this) on some of... | Create or alter trigger if exists | [
"",
"sql",
"sql-server",
"t-sql",
"triggers",
""
] |
I'm trying to figure it ou a way to make this selects in the same query. I'm working on the wordpress database, and I have these SQL queries that works by themselves:
```
SELECT `meta_value` AS 'Name' FROM `wp_postmeta` WHERE `meta_key` = "myfield1" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Department' FROM `... | To get a resultset with five columns (one for each custom field) you have to join the table to itself five times...
Something like this:
```
SELECT
pm1.meta_value AS 'Name'
pm2.meta_value AS 'Department'
pm3.meta_value AS 'Location'
pm4.meta_value AS 'Job Title'
pm5.meta_value AS 'Social Number'
... | One method is to use conditional aggregation:
```
SELECT MAX(CASE WHEN `meta_key` = 'myfield1' THEN meta_value END) as Name,
MAX(CASE WHEN `meta_key` = 'myfield2' THEN meta_value END) as Department,
MAX(CASE WHEN `meta_key` = 'myfield3' THEN meta_value END) as Location,
MAX(CASE WHEN `meta_key` = ... | Multiple selects on the same table | [
"",
"sql",
"wordpress",
"select",
""
] |
I have points table with data as follows:
```
+----+---------+--------+
| id | user_id | points |
+----+---------+--------+
| 1 | 1 | 10 |
| 2 | 3 | 5 |
| 3 | 1 | 12 |
| 4 | 2 | 27 |
| 5 | 1 | 14 |
+----+---------+--------+
```
i need user-id's from above data t... | You can't user `WHERE` in your query since you are trying to operate on aggregates of users. Instead, use a `GROUP BY` along with a `HAVING` clause like this:
```
SELECT t.user_id FROM
table t
GROUP BY t.user_id
HAVING SUM(t.points) > 10
```
Here is a **[SQL Fiddle](http://sqlfiddle.com/#!9/16e48/1)** where you can t... | Try this query
```
select user_id from tablename
group by user_id
having sum(points)>10
``` | mysql SUM() in a WHERE clause | [
"",
"mysql",
"sql",
"select",
"sum",
""
] |
I have a table with a series of dates, customer ID's, and integers that updates each week with a new date and integer values for all ID's.
I'd like to be able to write a query that will detect if the most recent three values are in decreasing order, and return TRUE or FALSE, for each ID.
So, for the table:
```
ID | ... | Not sure about performance but using the `lag` window function like this should work:
```
select *,
case when
value < lag(value, 1) over (partition by id order by weekending)
and value < lag(value, 2) over (partition by id order by weekending)
then 'True' else 'False' end
from t
order by id, we... | If you can select the relevant records based only on the weekending values (so assuming that all ids have records for every recent week), you could select the values into an array and use array methods to detect whether the values are descending or not:
```
with cte_values as (
select id,
array_agg(value or... | Detect a series of declining values in a postgres table | [
"",
"sql",
"postgresql",
""
] |
I have the following table:
```
PrimaryKeyColumn1 |PrimaryKeyColumn2 | Column_A | Column_B | Column_C|
ID1 Key1 0 1 0
ID2 Key2 1 0 1
ID3 Key3 1 1 0
`... | I think the easiest way is just to use `CASE` and some string logic:
```
select PrimaryKeyColumn1, PrimaryKeyColumn2,
stuff(((case when column_a = 1 then ',A' else '' end) +
(case when column_b = 1 then ',B' else '' end) +
(case when column_c = 1 then ',C' else '' end)
)... | i've done something like this
```
CREATE TABLE #test
(
primaryKey nvarchar(150)
, columnA bit
, columnB bit
, columnC bit
) -- create some test table
INSERT INTO #test
VALUES
('ID1',1,0,0)
,('ID2',1,1,0)
,('ID3',1,0,1) -- as well as the test values
... | Need a simple T-SQL Query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
Originally this is what the Claim Number looks like. 000000165130 it has 12 digits. I'd like to remove the zeros on the left side and the last zero on the right side making it 16513.
select [Policy Number], left([Claim Number],11 ) [Claim Number] from DW.CLAIMDATA where [Policy Number] = 'P000463500'
```
Policy Numbe... | Assuming this is fixed-width, you can use `right`.
```
right(left([Claim Number],11), 5)
```
Alternately, if the number of zeros is variable, you could cast to an integer:
```
cast(left([Claim Number], 11) as int)
```
And if you need it as a string instead:
```
cast(cast(left([Claim Number], 11) as int) as varchar... | This will convert the varchar to an int, which will remove leading zeros. it then reverses the digits and converts to an int again to remove the trailing zeros. then just reverse on more time to get the original string without leading or trailing zeros.
```
SELECT [Policy Number]
REVERSE(CONVERT(VARCHAR(50), CO... | How do I remove the digits from the left and right side in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I have a table that is as follows:
```
id value date
---------------
a, test, 01-01-15
a, test, 01-02-15
a, test, 01-03-15
a, test1, 01-04-15
a, test1, 01-05-15
b, test, 01-01-15
b, test, 01-02-15
```
I need to write a query to be able to grab the latest mapping for both a & b
for instance, I w... | Depending on what version of SQL you use, you may have a function called `ROW_NUMBER() OVER()` that can help.
```
WITH x AS
(SELECT id, value, date
, ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) AS RowNum
FROM table
)
SELECT id, value, date
FROM x
WHERE RowNum = 1
```
The above would work in SQL Se... | If your database supports `Row_number` then use this
```
select id,value,date from
(
select row_number() over(partition by value order by date desc) as RN,
id,value,date
from yourtable
) A
where RN=1
```
another way is by joining the result back to the table.
```
SELECT A.id,
A.value,
A.date ... | Getting most recent date values where other column values change | [
"",
"sql",
"postgresql",
"date",
"max",
""
] |
I have a query that fails to execute with "Could not allocate a new page for database 'TEMPDB' because of insufficient disk space in filegroup 'DEFAULT'".
On the way of trouble shooting I am examining the execution plan. There are two costly steps labeled "Clustered Index Scan (Clustered)". I have a hard time find out... | > I would appreciate any explanations to "Clustered Index Scan
> (Clustered)"
I will try to put in the easiest manner, for better understanding you need to understand both index seek and scan.
SO lets build the table
```
use tempdb GO
create table scanseek (id int , name varchar(50) default ('some random names')... | Expanding on Gordon's answer in the comments, a clustered index scan is scanning one of the tables indexes to find the values you are doing a where clause filter, or for a join to the next table in your query plan.
Tables can have multiple indexes (one clustered and many non-clustered) and SQL Server will search the a... | What "Clustered Index Scan (Clustered)" means on SQL Server execution plan? | [
"",
"sql",
"sql-server",
"sql-execution-plan",
""
] |
I have this query :
```
SELECT Company_Name FROM tblBeneficaries WHERE BeneficaryID IN ()
```
When I execute it it returns the message:
> Incorrect syntax near ')'.
What is the problem? | That's because, your `IN` clause has no parameter/argument `WHERE BeneficaryID IN ()`. It should be `WHERE BeneficaryID IN (id1,id2,id3, ...,idn)`
Your current query is same as saying below, no need of the `WHERE` condition
```
SELECT Company_Name FROM tblBeneficaries
``` | Your query as it reads should return no rows, because the set of desired BeneficaryIDs is empty. This syntax however is not valid, as the IN clause *must* contain at least one value, unfortunately. In order to represent an empty set, add NULL:
```
SELECT Company_Name FROM tblBeneficaries WHERE BeneficaryID IN (NULL);
... | sql query "WHERE IN" | [
"",
"sql",
"where-clause",
""
] |
If two independent scripts call a database with update requests to the same field, but with different values, would they execute at the same time and one overwrite the other?
as an example to help ensure clarity, imagine both of these statements being requested to run at the same time, each by a different script, wher... | This is what locking is for. All major SQL implementations lock DML statements by default so that one query won't overwrite another before the first is complete.
There are different levels of locking. If you've got row locking then your second update will run in parallel with the first, so at some point you'll have 1s... | from <https://dev.mysql.com/doc/refman/5.0/en/lock-tables-restrictions.html> (MySql)
> Normally, you do not need to lock tables, because all single UPDATE statements are atomic; no other session can interfere with any other currently executing SQL statement. However, there are a few cases when locking tables may provi... | Do Sql Update Statements run at the same time if requested at the same time? | [
"",
"mysql",
"sql",
"sql-update",
""
] |
I have a string which may be of below types
```
string expected result
15-th-rp 15
15/12-rp 12
15-12-th 12
4-5-6 5
```
Now i have to find the digit,
1) If a string contains only 1digit set then same will be displayed.
2) If there are multiple set of digits between character... | I think this is what you're after:
```
with a as (select '15-th-rp' data from dual union all
select '15/12-rp' data from dual union all
select '15-12-th' data from dual union all
select '4-5-6' data from dual)
select data,
coalesce(regexp_substr(data,'[0-9]+',1,2),
... | Do it in 2 steps. First match the first and second occurences of the pattern and then show the first set only if there is no second set (i.e. it's null).
```
with
a(data) as (
select '15-th-rp' from dual union all
select '15/12-rp' from dual union all
select '15-12-th' from dual union all
select '4-5-6' from d... | Find a 2nd set of digit in a string(SQL/PL-SQL) | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have a table with many rows that looks something like this:
```
Order_id Part_id Description GL_code
12345 Gk123 Gun mount 6850
12345 null Freight 4050.2
12346 Blac Lock 6790
12346 null Freight 4050
```
I want to make a query that returns all order in... | One way would be to use a correlated subquery that makes sure that there exists a row for the same order with the Freight code 4050.2:
```
select * from tab t
where (Part_id = 'Blac' or Part_id like 'GK%')
and exists (
select 1
from tab
where Order_id = t.Order_id
and Description = 'Freight'
... | It's probably easiest to join the table to itself; SQL is better at cross-column checks than cross-row checks.
```
Select a.* from MyTable a
inner join MyTable b
on a.Order_ID = b.Order_ID and b.Part_ID is null and b.Description = 'Freight' and b.GL_code = 4050.2
where (a.Part_ID like 'GK%' or a.Part_ID like 'Blac%')
... | How to filter order numbers by multiple columns | [
"",
"sql",
"sql-server",
""
] |
My present table structure is :
[](https://i.stack.imgur.com/QZSs2.png)
I want to calculate the time duration weighted average price for each product id for that day.
e.g.
Average Price for PA1 = (100\*4 + 105\*4 + 110\*8 + 115\*4) / 20
i.e Here p... | ```
with x as (
select
prodid,
price,
nvl(lead(extract(hour from cast(startdate as timestamp)))
over (partition by prodid order by startdate), 24)
- extract(hour from cast(startdate as timestamp)) as timediff
from producttable),
y as (
select
prodid,
sum(x.timediff*x.price) as sm,
sum(x.timediff) as s... | You basically want the `lead()` function and then some date arithmetic:
```
select prodid,
sum((least(trunc(startdate + 1, next_startdate) - startdate)*24) numhours
from (select p.*, lead(startdate) over (order by startdate) as next_startdate
from producttable t
) t
where date = date '2015-08-01'
gro... | Extract EndDate from the StartDate column using SQL i.e two dates coming from the same column | [
"",
"sql",
"oracle",
""
] |
I have a SQL Server stored procedure with nearly 300 variables within it.
The variables were created as follows:
```
CASE WHEN Grp1 = 'SALES' AND grp_mnth = MONTH_0 THEN SUM(Col) OVER(PARTITION BY grp_loc,COMM) ELSE 0 END AS "SALES_1"
```
As this has data issue all the variables were replaced like:
```
SUM(CASE WH... | Please re-write your query!
This issue occurs because SQL Server limits the number of identifiers and constants that can be contained in a single expression of a query. This limit is 65,535.
one approach might be :
> You can split the select query to multiple select queries.Store the
> result in temp tables and comb... | Right click on your Database => properties => click on options, then change compatibility level to lower one in the list.
See this image [compatibility level](https://i.stack.imgur.com/7ycac.png) | SQL Server - Internal error: An expression services limit has been reached | [
"",
"sql",
"sql-server",
""
] |
Is this all query same? I can't see any difference in result, It just change the number in table row according to our selection. but, why we always use 1. Does it has some technical meaning and advantages? | A query like `SELECT <Something> FROM Tablename` selects `something` per row of `tablename`.
Now if this `something` is not a column of table, and we just want to avoid computation on table, we use a number like `1` or `2` or anything that can be returned per row without calculation. They are all the same.
Even somethi... | You need to understand that the number you specify will be returned for as many times as there are rows in the table. The number of rows is same but the value returned is what you specify in the SELECT statement | select 1 from table, select 2 from table, select 3 from table e.t.c | [
"",
"mysql",
"sql",
"sql-server",
"database",
"oracle",
""
] |
I am trying to extract a substring using the following query. I am not getting the expected result.
```
DECLARE @st1 varchar(10)
SET @st1 = 'Case # 00548295'
SELECT @st1,ltrim(SUBSTRING(@st1, CHARINDEX('# ', @st1) + 1, LEN(@st1)))
```
I am getting 005 as the answer. I am trying to extract the integer values after 'Ca... | You define `@st1` as varchar(10), but then try to assign 15 characters (`'Case # 00548295'`) to it. SQL Server silently truncates the data in this case.
Simply increase the size:
```
DECLARE @st1 varchar(20)
SET @st1 = 'Case # 00548295'
SELECT @st1,ltrim(SUBSTRING(@st1, CHARINDEX('# ', @st1) + 1, LEN(@st1)))
``` | You did not give your varchar variable enough characters to hold the entire string to begin with.
```
DECLARE @st1 varchar(20)
SET @st1 = 'Case # 00548295'
SELECT @st1,ltrim(SUBSTRING(@st1, CHARINDEX('# ', @st1) + 1, LEN(@st1)))
-------------------- --------------------
Case # 00548295 00548295
(1 row(s) affect... | Substring in sql server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Lets say you have the next code:
```
DECLARE @A INT = 1,
@B INT = NULL;
IF (@B != @A)
SELECT 1;
ELSE IF (@B = @A)
SELECT 2;
ELSE
SELECT 3;
```
As you can see variable `@A` equals *'1'* for sure and variable `@B` certainly doesn't. I'm executing that part of code in *Microsoft SQL Server Managemen... | You cannot compare null with other values. You need to handle nulls separately.
So,this will work
```
DECLARE @A INT = 1,
@B INT = NULL;
IF (@B != @A or @B is null )
SELECT 1;
ELSE IF (@B = @A)
SELECT 2;
ELSE
SELECT 3;
``` | The correct version should be:
```
IF (@B = @A OR (@B IS NULL AND @A IS NULL))
SELECT 2;
ELSE IF (@B != @A OR @B IS NULL OR @A IS NULL)
SELECT 1;
ELSE
SELECT 3;
```
because NULL comparison must always be handled separately in SQL.
I inverted the `!=` and the `=` cases because tsql doesn't have a logical ... | Comparing two variables in SQL | [
"",
"sql",
"t-sql",
"sql-server-2014",
""
] |
I've written this code and someone helped me out but I can't figure out what ''?'' means to the DB engine. It would really help me understand what I've written here.
```
USE master
EXEC sp_MSforeachdb 'use ? select ''?'', st.NAME, sc.NAME,
sc.system_type_id, db_name()
FROM sys.tables st
INNER JOIN sys.co... | `sp_msforeachdb` is kind of... special. And I mean partly in the "riding the short bus" sense of the word (and even that's not entirely fair here; my main complaint is that it's undocumented), but mostly I just mean that it's unique. This syntax is only used with `sp_msforeachdb` and `sp_msforeachtable`, and nowhere el... | From <http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx>
> Notice that [?] is used as a placeholder for the heretofore unspecified database name
So the `?` will be replaced with the database name.
Note that it is probably better to write it as
```
EXEC sp_MSforeachdb 'use [?] select ''?'', st.NAME, sc.N... | What does ''?'' mean in SQL Server? | [
"",
"sql",
"sql-server-2012",
""
] |
Let's say we have two tables, **`Incidents`** and **`IncidentTracking`**:
```
Incidents (Id INT PRIMARY KEY,
CreatedOn Datetime,
State VARCHAR(50))
IncidentTracking (Id INT PRIMARY KEY,
IncidentId INT FOREIGN KEY REFERENCES TO Incidents.Id,
TrackingDate Dat... | I'd use [`OUTPUT`](https://msdn.microsoft.com/en-us/library/ms177564.aspx) clause.
As `IncidentTracking` has a foreign key, it is not possible to OUTPUT directly to it. You'll get an error message if you try:
> The target table 'dbo.IncidentTracking' of the OUTPUT INTO clause
> cannot be on either side of a (primary ... | Write a stored procedure to perform your task. You can put that kind of logic in a stored procedure easily enough.
If you will allow access to the table(s) outside of the procedure and still want the same behavior, a trigger is likely what you want (not a fan of them myself). Make sure, when writing your trigger, you ... | SQL Server: how to insert a record into related table during an update? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I wish to retrieve data from two tables with a twist, I need multiple values (prices from different dates) from the second table. The following works fine, but I am not much of a SQL jockey and I have a sneaking suspicion that there must be a better way than joining the second table twice. Is there?
```
SELECT A.date,... | It is perfectly fine to do it the way you're doing it, but to expand a bit more on the comment, there is a potential issue with your query. Since you are doing a `LEFT JOIN` with the conditional logic in the `WHERE` clause for the joined table, it is effectively transforming the `LEFT JOIN` into an `INNER JOIN`.
Shoul... | You can handle the pivoting with `case` expressions and `group by`:
```
SELECT
p.date, p.symbol,
min(p.value) value, /* dummy aggregate */
min(CASE WHEN s.Date = p.Date THEN s.close END) Close1,
min(CASE WHEN s.Date = DATE_ADD(p.Date, INTERVAL 1 DAY THEN s.close END) Close2
FROM
Potential p
LEF... | SQL query, two tables, multiple items | [
"",
"mysql",
"sql",
""
] |
I managed to create a simple query that selects a random first and last name and inserts them into a result table. I wanted to create something I could interchange with the various tests I run where I have to manufacture a lot of data. Here is the code (I only included 5 first and last names each for simplicity purpose... | The following code will allow you to generate a series of random names, where a cross join solution allows only one at a time. Not sure if you need to do this more than once, but if you do:
```
create table #table (firstname varchar(50), lastname varchar(50))
declare @counter int = 1
declare @max int = 5 --set numbe... | The problem is your join. This is how you can do it:
```
SELECT FirstName, LastName
FROM
(SELECT TOP 1 FirstName
FROM (SELECT 'John' AS FirstName
UNION SELECT 'Tim' AS FirstName
UNION SELECT 'Laura' AS FirstName
UNION SELECT 'Jeff' AS FirstName
UNION SELECT 'Sara' AS FirstName) AS First_Names ORDER BY NEWID())n1
CR... | SQL random name generator not inserting first and last name in the same row | [
"",
"sql",
"sql-server",
"t-sql",
"join",
"outer-join",
""
] |
I have a table with thousands of records:
```
+-----+-------+------+----------+
| id | group | code | label |
+-----+-------+------+----------+
| 1 | abc | 345 | myLabel1 |
| 2 | abc | 345 | myLabel4 |
| 3 | def | 987 | myLabel2 |
| 4 | def | 345 | myLabel4 |
| 5 | def | 987 | myLabel2 |
|... | This will give you duplicate rows in table with number of time occurrence
```
SELECT [group], [code] , COUNT(1) as CNT
FROM YourTableName
GROUP BY [group], [code]
HAVING COUNT(1) > 1
ORDER BY CNT;
``` | You can do the first as:
```
select group, min(code) as implied_code
from records
group by group
having count(distinct code) = 1;
```
And the second as:
```
select group, code, min(label) as implied_label
from records
group by group, code
having count(distinct label) = 1;
```
Note: `group` is a really bad name fo... | Find similarities in tables | [
"",
"sql",
"database",
"similarity",
""
] |
I want set two conditions in query, but query does not work.
```
SELECT IF((I.num_ip <> '100.100.100.100') &&
(I.num_ip <> '100.100.100.101'), I.num_ip, null) AS num_ip
FROM company C, computers
WHERE C.id_ip = I.id_ip
AND C.date_conn = '2015-08-12'
GROUP BY num_ip
``` | It can be written in other way as well using `CASE` expression like
```
Select case when I.num_ip not in ('100.100.100.100', '100.100.100.101')
then I.num_ip else null end) as num_ip
From company C
join computers I on C.id_ip = I.id_ip
Where C.date_conn = '2015-08-12';
```
\*\* Not sure though why you need a `GROU... | IN your query there are multiple issues
1. Condition (I.num\_ip <> '100.100.100.100') && (I.num\_ip <> '100.100.100.101) wont be true almost all the time since num\_ip will have value either 100.100.100.100' or '100.100.100.101'
2. there is one ' missing at end on 101.
please go through "<http://dev.mysql.com/doc/ref... | Mysql: how send two parameters in constraction IF() | [
"",
"mysql",
"sql",
""
] |
Thanks in advance for your time
I have the following table from the mondial database ([Website](http://www.dbis.informatik.uni-goettingen.de/Mondial/), [Documentation](http://dbis.informatik.uni-freiburg.de/content/courses/SS12/Praktikum/Datenbanken%20und%20Cloud%20Computing/mondial/mondial-print.pdf)).
```
CREATE TA... | User [jpw](https://stackoverflow.com/users/1175077/jpw) solved the problem in a comment.
Many users suggested to make a view of the table in order to make the couples or nations symmetrical like this:
```
CREATE VIEW borders_symmetrical AS
SELECT Country1, Country2 FROM borders
UNION ALL
SELECT Country2, Country1 FRO... | Assuming that the data has reciprocal values, meaning both ('France', 'Italy') and ('Italy', 'France') are in the data, then you can do this basically with a join and filtering:
```
select b1.country1, b2.country2
from borders b1 join
borders b2
on b1.country2 = b2.country1
where not exists (select 1
... | Query to find all couples of countries separated by another nation | [
"",
"mysql",
"sql",
"database",
""
] |
I am trying to sort data by applying case when statement in the order by clause but looks like Big Query doesn't support even though it worked fine in other SQL environments. Can somebody share your thoughts on this. | ```
select x
from (
select x ,
case when x = 'a' then 'z' else x end as y
from
(select 'a' as x),
(select 'b' as x),
(select 'c' as x),
(select 'd' as x)
)
order by y desc
``` | Update (2021) - Bigquery now does support ORDER BY with expressions, e.g.
```
SELECT event_type, COUNT(*) as event_count
FROM events
GROUP BY event
ORDER BY (
CASE WHEN event='generated' THEN 1
WHEN event='sent' THEN 2
WHEN event='paid' THEN 3
ELSE 4
... | Does Big Query support custom sorting? | [
"",
"sql",
"google-bigquery",
""
] |
I am using SQL Server 2014 and want to know how to check my active transactions? | 1. Query with `sys.sysprocesses`
```
SELECT * FROM sys.sysprocesses WHERE open_tran = 1
```
2. **[DBCC OPENTRAN](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-opentran-transact-sql)** : helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN disp... | If you want to know more details about active sessions like
session ID, Host Name,Login Name,Transaction ID,Transaction Name,Trnasaction Begin Time,Databse ID,Database Name you can use below sql query
```
SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transacti... | How to check active transactions in SQL Server 2014? | [
"",
"sql",
"sql-server-2014",
""
] |
I am writing a simple query in SQL Server:
```
Select
EmpId, EmpName, Sal
from
Emp
where
EmpId in (10,9,5,7,3,8);
```
I want to get the output in a same order which is given i.e; `10,9,5,7,3,8`
Actually whatever I'll give the result will display with given order without
order by ascending or descen... | No way to do this natively.
Try:
```
SELECT EmpId,EmpName,Sal
FROM Emp
WHERE EmpId IN (10,9,5,7,3,8)
ORDER BY CASE EmpId
WHEN 10 THEN 1
WHEN 9 THEN 2
WHEN 5 THEN 3
WHEN 7 THEN 4
WHEN 3 THEN 5
WHEN 8 THEN 6
ELSE 7
END;
``` | You can use a table variable to pass the inputs. You must insert the records into this table variable in the desired order.
```
Declare @empids table(id int identity(1,1),empid int)
insert into @empids values(10),(9),(5),(7),(3),(8)
Select e.EmpId,e.empname,e.sal from Emp e
join @empids t on e.EmpId = t.empid
order... | Display order of a SQL Query without order by clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm using SQL Server 2014 and I need to know which set of students have an action code used only once, and which students have an action code used more than once.
[](https://i.stack.imgur.com/kIhoW.png)
I'm trying to see if a student has more than on... | ```
SELECT
StudentID,
ActionCode,
ActionCodeCount = Count(*)
FROM
dbo.StudentActionCodes
WHERE
ActionCode IN (51201, 51206, 51207, 51208, 51209)
GROUP BY
StudentID,
ActionCode
ORDER BY
StudentID DESC,
ActionCode
;
```
## [See this working in a live demo at SqlFiddle](http://sqlfiddle.com/#!6... | Please try the below query:
SQL fiddle link: <http://sqlfiddle.com/#!6/d1dc6/6>
It gives sum of same type of actions per student as well as sum of all allowed actions per student
```
SELECT DISTINCT
StudentID,
Actioncode,
COUNT(1) OVER (PARTITION BY StudentID,Actioncode ) as [Count_of_this_action_instan... | TSQL- How to count number of instances | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a question about select in SQL Server.
First I'm getting columns name from temp table with proper type query looks like this:
```
select
sc.name, st.name
from
tempdb.sys.columns sc
left join
sys.types st on sc.system_type_id = st.system_type_id
where
object_id = object_id('tempdb..#_tmpDocs... | Here's a dynamic sql that will do what you need:
```
CREATE TABLE #_tmpDocs (id INT, x CHAR(10), y VARCHAR(100))
DECLARE @cols NVARCHAR(1000)
DECLARE @sql NVARCHAR(1000)
SELECT @cols = COALESCE(@cols + ',', '') + QUOTENAME(SC.name)
FROM tempdb.sys.columns sc
LEFT JOIN sys.types s... | I don't think you can reference columns dynamically in SQL like that. Just doing a pure sql version, it won't work:
```
declare @x varchar(50) = 'MyColumn';
select @x from dbo.MyTable
```
You'll need to use [dynamic sql](https://msdn.microsoft.com/en-us/library/ms188001.aspx), and build a string:
```
declare @x nvar... | Select columns name from subquery in main query | [
"",
"sql",
"sql-server",
""
] |
I have one table transaction with columns (id, amount) all positive integers and I have another table refund with same columns but here amount is expected to be negative.
Now I want to use Insert into command to select from transaction and insert into refund. How can I make the amount negative while inserting. followin... | ```
INSERT INTO refund (id,amount)
SELECT id, (0 - amount) as amount FROM `transaction`
```
as all data in `transaction` is positive.
```
INSERT INTO refund (id,amount)
SELECT id, (-1 * amount) as amount FROM `transaction`
``` | If you, for some reason, are not guaranteed you get a positive amount every time you insert a new row, take the absolute value and multiply it by -1
```
INSERT INTO refund (id,amount)
SELECT id, -1 * ABS(amount) FROM `transaction`
```
Otherwise, the `ABS()` part is not needed
```
INSERT INTO refund (id,amount)
SEL... | Mysql: How to convert positive value to negative while inserting | [
"",
"mysql",
"sql",
""
] |
We have a table of days like:
```
ID Date
1 2015-07-29
2 2015-07-30
3 2015-07-31
4 2015-08-01
5 2015-08-03
7 2015-08-04
8 2015-08-05
9 2015-08-06
10 2015-08-07
11 2015-08-10
```
And we want to find all the sequences (day+1). The result should be something like this:
```
Start End
2015-07-... | This is an [Islands and Gap problem](https://www.simple-talk.com/sql/t-sql-programming/the-sql-of-gaps-and-islands-in-sequences/). You can use `ROW_NUMBER` and `DATEDIFF`. Something like this.
**[SQL Fiddle](http://sqlfiddle.com/#!6/06763/1)**
**Sample Data**
```
DECLARE @Dates TABLE
([ID] int, [Date] datetime)... | As I started from an answer which was already posted, maybe I made it very complex. But it works.
```
DECLARE @T TABLE(ID INT, DATE DATE)
INSERT INTO @T
SELECT 1, '2015-07-29' UNION ALL
SELECT 2, '2015-07-30' UNION ALL
SELECT 3, '2015-07-31' UNION ALL
SELECT 4, '2015-08-01' UNION ALL
SELECT 5, '2015-08-03' ... | Get sequence of days from days | [
"",
"sql",
"t-sql",
""
] |
I have created a temporary table to hold some values like this:
```
CREATE TABLE #TempCount (PendingOrders INT, OpenOrders INT, ClosedOrders INT);
```
I want to update the columns with a value from a `SELECT` statement as such:
```
UPDATE #TempCount
SET PendingOrders =
(
SELECT
COUNT(OrderID) AS 'Pe... | You need a row in order to update it. Do one "initializing" INSERT first:
```
INSERT INTO #TempCount VALUES(0, 0, 0)
``` | Seems to me like you need an insert statement first to generate the row.
```
INSERT #TempCount (PendingOrders)
SELECT COUNT(OrderID) AS 'PendingOrders'
FROM dbo.Products
WHERE OrderStatus = 1
``` | How to update a temporary table with a value from a select statement? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table with values like this
```
listid email
1 test@email.com
5 test@eamil.com
1 test123@email.com
```
From the above example you can see that the same email can show up in the email column with a different `listid`.
I want to return emails that have a `listid` of 1 but not not also h... | You could use the `exists` operator:
```
SELECT `email`,`listid`
FROM `table` t
WHERE `emailaddress` LIKE '%@email%' AND
`listid` = 1 AND
NOT EXISTS (SELECT *
FROM `table` t2
WHERE t1.`emailaddress` = t2.`emailaddress` AND
t2.`listid... | You could use a join:
```
SELECT t.email, t.listid
FROM `table` t
JOIN `table` t2 ON t.email = t2.email AND t2.listid != 5
WHERE t.listid = 1
``` | select where id == value and id != value mysql | [
"",
"mysql",
"sql",
"select",
""
] |
Pretty stuck and hoping someone can help
I need to use a common table expression to display (select) all the odd Employee\_ID rows first and then all the even Employee\_ID rows from the employee table.
This is what I have written so far, definitely not correct. Would be great if someone can help.
```
WITH MYCTE (Emp... | All you need is to add a `ORDER BY` similar to the one below:
`order by case when odd%2 = 1 then 0 else 1 end, odd asc`
Here is a sample [SQLFiddle](http://sqlfiddle.com/#!9/accc72/2).
Added to your code, this would look like:
```
With MYCTE(Employee_ID)
As
(
Select 1 as odd
From Employee_Table
UNION ALL
Select... | Try this
```
select t.* from
(
Select row_number() over (order by (select 1)) as sno, * From Employee_Table
) as t
order by case when sno%1=1 then 1 else 2 end, sno
``` | Recursive CTE - Returning odd and even records | [
"",
"sql",
"common-table-expression",
""
] |
Consider a SQL query with the following `WHERE` predicate:
```
...
WHERE name IS NOT NULL
...
```
Where `name` is a textual field in PostgreSQL.
No other query checks any textual property of this value, just whether it is `NULL` or not. Therefore, [a full btree index](http://www.postgresql.org/docs/9.3/static/indexe... | I'm interpreting you claim that it's "overkill" in two ways: in terms of complexity (using a B-Tree instead of just a list) and space/performance.
For complexity, it's not overkill. A B-Tree index is preferable because *deletes* from it will be faster than some kind of "unordered" index (for lack of a better term). (A... | You could use an expression index, but you shouldn't. Keep it simple, and use a plain b-tree.
---
An expression index can be created on `colname IS NOT NULL`:
```
test=> CREATE TABLE blah(name text);
CREATE TABLE
test=> CREATE INDEX name_notnull ON blah((name IS NOT NULL));
CREATE INDEX
test=> INSERT INTO blah(name)... | PostgreSQL: Create an index to quickly distinguish NULL from non-NULL values | [
"",
"sql",
"postgresql",
"indexing",
"null",
""
] |
How can I build a SQL Query to decompose some periods, for example in months.
database table:
```
id fromdate todate value
--------------------------------------------
100 01.01.2015 01.03.2015 10
```
desired query result:
```
id fromdate todate value
----------... | For calculations like this you can use `date dimension` - a table that contains all the dates in your domain as single rows (see this for [example](http://www.dwhworld.com/2010/11/date-dimension-sql-scripts-oracle/)).
Once you have date dimension in your database things become simple:
```
WITH data_by_date AS
( -- H... | Use a hierarchical query to generate a list of months for each entry:
[SQL Fiddle](http://sqlfiddle.com/#!4/045bc/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE TEST (id, fromdate, todate, value ) AS
SELECT 100, DATE '2015-01-01', DATE '2015-03-01', 10 FROM DUAL
UNION ALL SELECT 200, DATE '2014-12-22'... | SQL Query building: howto decompose periods of time in different rows | [
"",
"sql",
"oracle",
"relational-database",
""
] |
Here's the data I have (note that this is for only one entity id / employee id, there will be multiple. One entity ID can have multiple employee IDs under it):
```
SELECT EntityId,
EmployeeId,
PayPeriodStart,
IsFullTime
FROM dbo.Payroll
WHERE EmployeeId = 316691
AND PayPeriodStart... | I believe you are looking to use `ROW_NUMBER()` and the get the last value based on `payperiodstart` date:
```
SELECT t.EntityId
,t.EmployeeId
,t.LastIsFullTimeValue
FROM (
SELECT EntityId
,EmployeeId
,ROW_NUMBER() OVER (
PARTITION BY EntityId
,EmployeeId ORDER BY Pa... | Try adding `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`
I believe the default window for analytic functions that includes an `ORDER BY` ends at the current row.
```
LAST_VALUE(IsFullTime) OVER (
PARTITION BY EntityId, EmployeeId
ORDER BY EntityId, EmployeeId, PayPeriodStart
ROWS BETWEEN UNBO... | Why is LAST_VALUE() not working in SQL Server? | [
"",
"sql",
"sql-server",
""
] |
I have a PostgreSQL column of type text that contains data like shown below
```
(32.85563, -117.25624)(32.855470000000004, -117.25648000000001)(32.85567, -117.25710000000001)(32.85544, -117.2556)
(37.75363, -121.44142000000001)(37.75292, -121.4414)
```
I want to convert this into another column of type text like show... | As I put in the question, *I tried extracting the column to Java and performing my operations there. But due to sheer amount of records I have, I will run out of memory. I also cannot do this method in batched due to time constraints.*
I ran out of memory here as I was putting everything in a Hashmap of
**< my\_prim... | Assuming you also have a PK or some unique column, and possibly other columns, you can do as follows:
```
SELECT id, (...), string_agg(point(pt[1], pt[0])::text, '') AS col_reversed
FROM (
SELECT id, (...), unnest(string_to_array(replace(col, ')(', ');('), ';'))::point AS pt
FROM my_table) sub
GROUP BY id; -- assu... | Split multiple points in text format and switch coordinates in postgres column | [
"",
"sql",
"postgresql",
"replace",
""
] |
I have this query
```
SELECT
s.account_number,
a.id AS 'ASPIRION ID',
a.patient_first_name,
a.patient_last_name,
s.admission_date,
s.total_charge,
astat.name AS 'STATUS',
astat.definition,
latest_note.content AS 'LAST NOTE',
a.insurance_company
FROM
accounts a
INNER JOIN
services s ON a.id = s.account_id
INNE... | Here are two choices. If your `content` is not very long and don't have funky characters, you can use the `substring_index()`/`group_concat()` trick:
```
(SELECT account_id,
SUBSTRING_INDEX(GROUP_CONCAT(content ORDER BY created desc SEPARATOR '|'
), 1, '|') as content
FROM... | ```
SELECT
s.account_number,
a.id AS 'ASPIRION ID',
a.patient_first_name,
a.patient_last_name,
s.admission_date,
s.total_charge,
astat.name AS 'STATUS',
astat.definition,
latest_note.content AS 'LAST NOTE',
a.insurance_company
FROM
accounts a
INNER JOIN services s ON a.id = s.account_id
INNER JOIN facilities f ON f.id... | Getting max record on varchar field | [
"",
"mysql",
"sql",
"join",
"max",
""
] |
I have flat table which I have to join using EAN attribute with my main table and update gid (id of my main table).
```
id attrib value gid
1 weight 10 NULL
1 ean 123123123112 NULL
1 color blue NULL
2 weight 5 NULL
2 ean 33123131... | The reason your update does not work is that you don't have any link between your source and target for the update, although you reference `sidetable` in the `FROM` clause, this is effectively destroyed by the `PIVOT` function, leaving no link back to the instance of `SideTable` that you are updating. Since there is no... | try and break it down a bit more like this..
```
update SideTable
set SideTable.gid = p.ab_id
FROM
(
select gid, ab_id
from SideTable
pivot (max (value) for attrib in ([EAN],[MPN])) as b
join MainTable as c
on c.ab_ean = b.EAN
where b.EAN !='' AND c.ab_archive = '0'
) p
WHERE p.EAN = SideTable.EA... | How to UPDATE pivoted table in SQL SERVER | [
"",
"sql",
"sql-server",
"t-sql",
"pivot",
""
] |
I have this stored procedure:
```
create procedure [dbo].[GetCarsByDates]
(@startDate date, @returnDate date)
as
SELECT
ManufacturerName, ModelName,
CreationYear,
Gear, CurrentKM,
Picture,
DATEDIFF(D, @startDate, @returnDate) * PricePerDay AS [Totalprice],
Pr... | I feel your query should be written like below.
I assumed that you need to query all cars available from `startDate` to `returnDate` and need to check based on `CarsForRent` table's columns
`CarsForRent.RentalStartDate` and `CarsForRent.RentalReturnDate`
```
create procedure [dbo].[GetCarsByDates]@startDate date, @ret... | if you want the user only set startdate to values greater than returndate, you do this with an IF-Block before the actual query. For example so:
```
create procedure [dbo].[GetCarsByDates](@startDate date, @returnDate date)
as
if @startDate <= @returnDate OR @startDate IS NULL OR @returnDate IS NULL
BEGIN
/* may... | SQL Server - Dates, Greater than and Less than | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table with products like this:
```
PRODUCT_ID SUB_PRODUCT_ID DESCRIPTION CLASS
---------- -------------- ----------- -----
A001 ACC1 coffeemaker A
A002 ACC1 toaster A
A003 ACC2 coffee table A
A004 ACC5 ... | is this what you want?
```
insert into products(PRODUCT_ID, SUB_PRODUCT_ID, DESCRIPTION, CLASS)
select replace(product_id, 'A', 'B'),
replace(SUB_PRODUCT_ID, 'A', 'B'),
DESCRIPTION,
replace(CLASS, 'A', 'B')
from products
where class = 'A';
```
EDIT:
`replace()` might be o... | ```
Hi You can do a lilte bit of code twisting and here's the output :)
SELECT 'A001' PID,'ACC1'SPID,'cofeemaker' dsc,'A' clss FROM dual
UNION
SELECT REPLACE(a.pid,SUBSTR(a.pid,1,1),'B') PID,
REPLACE(a.SPID,SUBSTR(a.spid,1,1),'B')SPID,
a.dsc,
REPLACE(a.clss,SUBSTR(a.CLSS,1,1),'B') CLSS
FROM
(SELECT 'A001' PID,... | PLSQL - How to replicate a row changing columns first characters? | [
"",
"sql",
"plsql",
"substr",
"replicate",
""
] |
Is there a way to create a multi column index across tables?
For example, if I had the following tables:
```
Foo (Table Name)
FooID (PK)
BarID (FK)
FooName
Bar (Table Name)
BarID (PK)
BarName
```
I can do a
```
SELECT *
FROM Foo
LEFT JOIN Bar ON Foo.BarID = Bar.BarID
WHERE
FooName < "Bob"
AND BarN... | Came across my own post years later and figured I could add some details, in case others have similar issues. As Mark B pointed out, each index is per table, however we can set things up that make this efficent, see below.
There are a couple of different things going on here, so can use indexes to help accomplish what... | Smells like "over-normalization". Might it be worth moving those two fields into the same table?
Akiban was an Engine that could do cross-table `JOINs`, etc. But it no longer exists.
"Materialized Views" do not exist in MySQL (unless you implement them yourself). | SQL way to index across tables? | [
"",
"mysql",
"sql",
"indexing",
""
] |
I have the following piece of a SELECT query inside a stored procedure i'm developing:
```
AND (
CASE S.SWITCH
WHEN 'A' THEN P.TEST = T.OPTION_1
WHEN 'C' THEN P.TEST = T.OPTION_1 + T.OPTION_2
WHEN 'G' THEN P.TEST = T.OPTION_3
WHEN 'N' THEN TRUE
ELSE FALSE
END
)
```
I'm ... | You case comparison should be something like below, if you are testing `P.TEST` value based on `S.SWITCH` case.
```
AND (
P.TEST =
CASE
WHEN S.SWITCH = 'A' THEN T.OPTION_1
WHEN S.SWITCH = 'C' THEN T.OPTION_1 + T.OPTION_2
WHEN S.SWITCH = 'G' THEN T.OPTION_3
WHEN S.SWITCH = 'N'... | Boolean expressions don't work like that in SQL. You can reformulate your switch like this:
```
AND (
(S.SWITCH = 'A' AND P.TEST = T.OPTION_1) OR
(S.SWITCH = 'C' AND T.OPTION_1 + T.OPTION_2) OR
(S.SWITCH = 'G' AND P.TEST = T.OPTION_3) OR
(S.SWITCH = 'N')
)
``` | Sybase proc throws "Incorrect syntax near '='" | [
"",
"sql",
"syntax",
"syntax-error",
"sybase",
""
] |
`i have two table` [](https://i.stack.imgur.com/0aM2d.png)
`and table two data is`[](https://i.stack.imgur.com/mHH5J.png)
```
and i want to show just like this
```
[](https... | ```
select
a.serial,
b.word,
a.word as meaning
from tbl1 a
join tbl2 b on a.serial = b.serial
``` | This is the sql query your looking for ,details related to the same is been provided in the link below
```
INSERT INTO table3 (serial,word,meaning)
SELECT t1.serial,t2.word,t1.word
FROM table1 as t1
JOIN table2 as t2 ON t1.serial=t2.serial
```
click here [w3schools SQL tutorial](http://www.w3schools.com/sql/sql_ins... | joining two table in sqlite | [
"",
"android",
"mysql",
"sql",
"sqlite",
""
] |
I want to select all rows from my table where value of one column begins with value of another column.
```
Table
column_a column_b
abc abcdef
pqr rstrv
xyz xyzabc
uvw abcdef
```
I want to get
```
pqr rstrv
uvw abcdef
```
I'm usin... | You have the right idea, but MySQL doesn't support the `+` operator for string concatination, only for mathematical addition. Instead, just use the [`concat`](https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_concat) function:
```
SELECT * FROM table_name WHERE column_b NOT LIKE CONCAT(column_a, '... | In MySQL, you should use `CONCAT()` instead of `+`:
```
select *
from TableName
where column_b not like CONCAT(column_a,'%')
```
In SQL Server:
```
select *
from TableName
where column_b not like column_a+'%'
``` | select where one column part of another | [
"",
"mysql",
"sql",
"string",
"select",
"sql-like",
""
] |
I have table with many rows that have the same date. I want to query the max (latest) data but if the dates are the same, only return one. It doesn't matter which record but I could use the latest (GID).
I currently have this to to get the latest date:
```
SELECT ProjectNum,DateSaved,FilePath ,GID
FROM dbo.master_m_t... | Looks like you're looking for this:
```
SELECT ProjectNum,DateSaved,FilePath,GID
FROM (
select
ProjectNum,DateSaved,FilePath,GID,
row_number() over
(partition by FilePath order by DateSaved desc, GID desc) as RN
from dbo.master_m_table
) X
where RN = 1
```
Row number will create numbers for the... | Just use `top` and `order by`:
```
select top 1 t.*
from dbo.master_m_table t
order by t.datesaved desc;
```
If you wanted all of them, you can use `with ties`.
I'm not sure what you mean by "the latest GUID". You can add more columns to the `order by` to handle ties. | SELECT MAX DATE when records have identical dates | [
"",
"sql",
"sql-server",
"max",
""
] |
I want to select information from two SQL tables within one query, the information is unrelated though, so no potential joints exist.
An example could be the following setup.
tblMadrid
```
id | name | games | goals
1 | ronaldo | 100 | 100
2 | benzema | 50 | 25
3 | bale | 75 | 50
4 | ... | You can do something like this:
```
(SELECT
name, games, goals
FROM tblMadrid WHERE name = 'ronaldo')
UNION
(SELECT
name, games, goals
FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;
```
See, for example: <https://dev.mysql.com/doc/refman/5.0/en/union.html> | If you like to keep records separate and not do the union.
Try query below
```
SELECT (SELECT name,
games,
goals
FROM tblMadrid
WHERE name = 'ronaldo') AS table_a,
(SELECT name,
games,
goals
FROM tblBarcelona
WHE... | SQL: Two select statements in one query | [
"",
"sql",
"select",
""
] |
For Access 2013, I need a way to round up any fractional numbers to the next whole number in an SQL query.
Example:
```
SELECT ROUNDUP(NumberValues) FROM Table1
```
In the above query, a row with 1.25 should return as 2 after querying.
As far as I know, there's no ROUNDUP function in Access 2013 for use in a SQL qu... | I found a ROUNDUP equivalent from this link:
<http://allenbrowne.com/round.html#RoundUp>
> To round upwards towards the next highest number, take advantage of the way Int() rounds negative numbers downwards, like this:
> - Int( - [MyField])
>
> As shown above, Int(-2.1) rounds down to -3. Therefore this expression rou... | I have found the easiest way to round up a number in access is to use the round function like this:
Round([MyField]+0.4,0)
The number 10.1, for example then becomes 10.5. When the round function is applied, it rounds up to 11. If the number is 10.9, adding 0.4 becomes 11.3, which rounds to 11. | How to ROUNDUP a number in Access 2013? | [
"",
"sql",
"rounding",
"ms-access-2013",
""
] |
I'm trying to filter some records by date but the datetime field seems to be stored as varchar and I'm struggling to convert it. Below is a sample of the data:
```
ID DateField
0002 14/04/1989 01:30
0003 16/04/1989 09:45
0004 16/04/1989 06:00
0005 19/04/1989 01:07
0006 21/04/1989 16:03
```
When I ... | Use CONVERT with Style
```
CONVERT(DATETIME,Datefield ,103)
```
To find bad data, see what this returns
```
set dateformat dmy
select Datefield from table where isdate(where)=0
```
You should always use proper DATETIME datatype to store datetime values | Try this. You need to add style part to identify the format
```
SELECT CONVERT(DATETIME, dates, 103)
FROM (VALUES ('14/04/1989 01:30'),
('16/04/1989 09:45'),
('16/04/1989 06:00'),
('19/04/1989 01:07'),
('21/04/1989 16:03')) cs (dates)
``` | convert varchar to datetime field | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I have a temp table in SQL server like below
```
╔═══════╦═════════╦══════╦═════════╗
║Serial ║ Account ║ Due ║ Balance ║
║1 ║ A1 ║ 1000 ║ 3100 ║
║2 ║ A1 ║ 1000 ║ 3100 ║
║3 ║ A1 ║ 1000 ║ 3100 ║
║4 ║ A1 ║ 1000 ║ 3100 ║
║1 ║ A2 ║ 100 ║ 3100 ║
║2 ║ A... | At last, solved this with update query.
```
UPDATE A
SET
A.Balance = @Balance
, @PreBalance = @Balance
, @Balance = ( CASE WHEN (@Balance IS NULL OR @AccountType <> A.AccountType)
THEN
CASE WHEN A.Balance - A.Due >= 0
THEN A.Balance
... | Very simple
```
select * from account
where (Balance-(Select sum(ac.Due) from account ac where
ac.SerialNo<=account.SerialNo and ac.Account =account.Account )>0)
```
**Update**
there is no relation between A1 and A2 that say that balance 3100 is to be share between A1 and A2 and not with B1.
So you have to speci... | Complex select query for SQL Server | [
"",
"sql",
"sql-server",
""
] |
I'm trying to do with following with an SQL query in Impala. I've got a single data table that has (among other things) two columns with values that intersect multiple times. For example, let's say we have a table with two columns for related names and phone numbers:
`Names Phone Numbers
John Smith (123) 456-7890
Rob ... | Working with your query...
This generates a subset by name of users having more than 1 phone number it then joins back to the entire set based on name returning all phone numbers for users having more than 1 phone number. however if a user has the same phone number listed more than once it would get returned. to elimi... | One method is to use exists:
```
select t.*
from tablename t
where exists (select 1 from tablename t2 where t2.name = t.name and t2.phonenumber <> t.phonenumber)
``` | SQL Query: How to select multiple instances of a single item without collapsing into a group? | [
"",
"sql",
"hadoop",
"impala",
""
] |
I have a table with large amount of data and I need to get some information with only one query.
Content of `PROCESSDATA` table:
```
PROCESSID | FIELDTIME | FIELDNAME | FIELDVALUE
-------------------------------------------------------------------------
125869 | 10/08/15 10:43:47,139000000 | ID... | Use `MAX( ... ) KEEP ( DENSE_RANK FIRST ORDER BY ... )` to get the maximum of a column based on the maximum of another column:
[SQL Fiddle](http://sqlfiddle.com/#!4/473c3f/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE PROCESSDATA ( PROCESSID, FIELDTIME, FIELDNAME, FIELDVALUE ) AS
SELECT 125869, TO_T... | Try this
```
select t1.PROCESSID, t1.FIELDTIME,t1.FIELDNAME,t1.FIELDVALUE,
t1.STATE,t1.IDREQUEST from PROCESSDATA as t1
inner join
(
select PROCESSID, max(FIELDTIME) as FIELDTIME from PROCESSDATA
where FIELDNAME IN ('IDREQUEST', 'state', 'MsgReq')
group by PROCESSID
) as t2 on t1.PROCESSID=t2.PROCESSID and t1.FIELDTI... | Getting a value based on an another within a group by | [
"",
"sql",
"oracle",
"group-by",
""
] |
Table : Post
```
id user_id group_id Text
1 1 1 AAA
2 2 2 BBB
3 2 2 CCC
4 3 2 DDD
5 2 3 EEE
```
Table : UserMaster
```
user_id username
1 Raj
2 ... | ```
select p.id, u.username, g.groupname, p.text
from posts p
join userMaster u on u.user_id = p.user_id
join groups g on g.group_id = p.group_id
join joinRequest r on r.user_id = p.user_id
and r.group_id = p.group_id
where r.status = 'active'
``` | ```
Select p.id, um.username, g.Groupname, p.Text
From Post as p
JOIN UserMaster as um
ON p.user_id = um.user_id
JOIN Groups as g
ON p.group_id = g.group_id
JOIN JoinRequest as jr
ON p.user_id = jr.user_id
AND p.group_id = jr.group_id
WHERE jr.status = 'active'
``` | fetch records from four different table using join query | [
"",
"sql",
"sql-server",
"database",
""
] |
I have a table with an `identity` column in a server and have a other table with same structure in another server.. Now I want to copy all data from one table to other table but I can't help it...
I have already created a linked server..
I use this:
```
insert into [server].[database].[dbo].[table1]
select *
... | If you want to insert into a second table that also has an identity column, then you need to **explicitly define** the list of columns you're inserting into and omit the `identity` column:
```
insert into [server].[database].[dbo].[table1] (col1, col2)
select column1, column2
from table2
```
This way, SQL Serve... | Set [IDENTITY\_INSERT](https://msdn.microsoft.com/en-us/library/ms188059(v=sql.120).aspx) for table:
```
SET IDENTITY_INSERT [server].[database].[dbo].[table1] ON
insert into [server].[database].[dbo].[table1]
select column1,column2
from table2
SET IDENTITY_INSERT [server].[database].[dbo].[table1] OFF
``` | How to copy data in identity column? | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have date like this
```
CustId Frequency Date
------ --------- -----
C1 2 20-Jan-2015
C2 3 22-Feb-2015
```
I have to get the output like below
```
C1 20-Jan-2015
C1 20-Jan-2015
C2 22-Feb-2015
C2 22-Feb-2015
C2 22-Feb-2015
```
Can anyone please help me with this query.
Thanks ... | You can use a correlated hierarchical query to generate extra rows (without having to create an extra table and ensure that your frequencies do not exceed the match the range of those numbers):
```
SELECT CustID,
"Date"
FROM CustomerFrequencies c,
TABLE(
CAST(
MULTISET(
... | You need a numbers table. There are various ways to generate one. Here is an explicit method:
```
with numbers(n) as (
select 1 from dual union all select 2 from dual union all select 3 from dual
)
select d.CustId, d.date + n.n - 1 as date
from data d join
numbers n
on d.frequency <= n.n;
```
If ... | Splitting Aggregated counts into rows | [
"",
"sql",
"oracle",
""
] |
I'm beginner in SQL Server querying. I have assigned to a task where I need to self join a table.
[](https://i.stack.imgur.com/YM8LW.png)
Above is table structure. And I need result as below. I have tried using self join , sub query etc. I couldn't g... | What you are trying to get is achieved through a `cross join`. If you select the table twice you would get the desired result.
```
select a.reqstatusid, a.reqstatus, b.reqstatusid as childreqstatusid,
b.reqstatus as childreqstatus
from table a, table b
where a.reqstatusid <> b.reqstatusid
``` | use [*`CROSS JOIN`*](https://technet.microsoft.com/en-us/library/ms190690(v=sql.105).aspx), Which gives you the Cartesian product between two tables
```
Select *
From YourTable A
CROSS JOIN YourTable B
Where A.ReqStatusId <> B.ReqStatusId
``` | Joining a sql table rows with all other rows of same table | [
"",
"sql",
"sql-server",
""
] |
I have a table called `cars`. Cars has a one-to-many relation to `tires` table. Tires has a column called `condition` which can either be "flat" or "pumped".
I want to do a query where I count how many cars that has no pumped tires left. Meaning that ALL tires has to be flat. In order for the car to be counted. How do... | Ordinarily I would just:
```
SELECT COUNT(*)
FROM cars
where not exists (select null
from tires
where tires.car_id = cars.id and
tires.condition = 'pumped')
```
If, however, you had an extremely small proportion of cars for which any tire at a... | Count all cars that don't have any pumped tires:
```
select count(*)
from cars c
where not exists (select 1 from tires t
where c.id = t.car_id
and t.condition = 'pumped')
``` | SQL: count all where has no relation with certain condition | [
"",
"sql",
"postgresql",
""
] |
I have a data model like the following which is simplified to show you only this problem (**SQL Fiddle** Link at the bottom):
[](https://i.stack.imgur.com/M96QV.png)
A person is represented in the database as a meta table row with a name and with mul... | Use the aggregate function `json_object_agg(key, value)`:
```
select
name,
json_object_agg(key, value) as data
from data
join meta on fk_id = id
group by 1;
```
[Db<>Fiddle.](https://dbfiddle.uk/?rdbms=postgres_9.5&fiddle=349615c77f193e81f428c254bfd3bc06)
The function was introduced in [Postgres 9.4](https... | I found a way to return crosstab data with dynamic columns. Maybe rewriting this will be better to suit your needs:
```
CREATE OR REPLACE FUNCTION report.usp_pivot_query_amount_generate(
i_group_id INT[],
i_start_date TIMESTAMPTZ,
i_end_date TIMESTAMPTZ,
i_interval INT
) RETURNS TABLE (
tab TEX... | How to convert two rows into key-value json object in postgresql? | [
"",
"sql",
"json",
"postgresql",
"aggregate-functions",
"key-value",
""
] |
I need help getting a certain outcome from sql.
**users table:**
```
userid | name
-------|-----------
1 | Bob Robert
2 | Steve Smith
3 | Willard Henegar
4 | Max Rockwell
5 | Marion Paley
6 | Marcus Delisle
```
**orders table:**
```
orderid | userid
--------|-------
1 |1
2 ... | If you also want Users without any orders, you can do the following:
```
select NumOrders, count(*) as NumPeople
from (
select u.UserId, count(*) as NumOrders
from users u
left join orders o on o.UserId = o.UserId
group by o.UserId
) t
group by t.NumOrders
```
You could also do:
```
select NumOrders, cou... | You want a double histogram. This is the easiest way:
```
select cnt, count(*), min(userid), max(userid)
from (select u.userid, count(o.userid) as cnt
from users u left join
orders o
on u.userid = o.userid
group by u.userid
) u
group by cnt;
```
This will not, however, give you ... | SQL count number of people by number of orders | [
"",
"mysql",
"sql",
""
] |
I realize this has already been posted somewhere but due to keyword density I cannot find it.
I currently have the following query:
```
SELECT COUNT(t2.*), t1.t2id, t1.c2
FROM t1
LEFT JOIN t2 ON t1.t2id = t2.t2id
GROUP BY t1.t2id
```
Note `t2id` is a `nchar(256)` and t1.c2 is an `ntext`.
So basically I want to cou... | You need to to have
```
SELECT COUNT(t2.*), t1.t2id, t1.c2
FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t2id
GROUP BY t1.t2id, t1.c2
```
The r1.c2 isn't in an aggregate (count) or the group by so it needs to go into one.
Edit: deal with t1.c2 being ntext
```
SELECT COUNT(t2.*), t1.t2id, cast(t1.c2 as nvarchar(max))
FROM ... | Problem is that as error message tells you, you need to pass `t1.c2` to `GROUP BY`clause in following:
```
string query = "SELECT COUNT(t2.*),t1.t2id,t1.c2 FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t2id GROUP BY t1.t2id, t1.c2";
``` | How to get a column value after and count after join? | [
"",
"sql",
"sql-server",
""
] |
Say i have a string `ABC&EFG d.d.` , and after calling `initcap` like this
```
select initcap("ABC&EFG d.d.") from dual;
```
I would get `Abc&Efg D.D.` which is perfect for the 1st part but not what i need for the part where letters `d.d.` become `D.D.`.
So i would need a version of initcap that would not capitalize ... | ```
select
regexp_replace(
initcap(
regexp_replace('ABC&EFG d.d.', '(\w+\.)', chr(1)||'a\1')
),
chr(1)||'.')
from dual;
``` | You can use a regex to filter the string for text only, it will then skip the 'd.d.' since it wont be match the regex and runs `initcap` on the matched string. Then find the 'd.d.' and concatenate it to the string after `initcap`.
```
select initcap(REGEXP_SUBSTR('ABC'||chr(38)||'EFG d.d.','(\w\&?\w)+') )
|| REG... | How to camelcase a string like with Initcap but with exception of letters followed by dot? | [
"",
"sql",
"oracle",
""
] |
Considering the following table, how can I group these scores into three buckets (not more): less than equal 150, between 150 and 350, more than 350.
```
id | score
----+-------
1 | 5
2 | 5
3 | 5
4 | 4
5 | 5
6 | 4
7 | 4
8 | 4
9 | 2
10 | 2
11 | 6
12 | ... | This will give you the ranges you requested:
```
SELECT
CASE WHEN min(score) <= 150 THEN '*-150'
WHEN min(score) <= 350 THEN '151-350'
ELSE '350-*'
END AS scorerange, #A comma is needed here right after scorerange
count(*)
FROM scores
GROUP BY score <= 150, score <= 350;
``` | Group by a `CASE` statement, but make sure to *get the bounds right*:
```
SELECT CASE
WHEN score <= 150 THEN '0-150'
WHEN score <= 350 THEN '151-350'
ELSE '351+'
END AS score_range
, count(*) AS count
FROM scores
GROUP BY 1
ORDER BY 1; -- happens to work... | Group records into three predefined buckets in Postgres | [
"",
"sql",
"postgresql",
""
] |
I am starting to build something like system up to the just cooperate with suggestions coming into the database called `ForslagOpslag`.
Every time I try to update table with likes, you will see it with this one error:
> Update cannot proceed due to validation errors. Please correct the following errors and try again.... | You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a `Bruger` (User) table, where `fk_brugerid` in `ForslagOpslag` is the user who created the record with `opretdato` being the creation date, and `ForslagOpslagLikes` is an association table of users who likes... | Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to `ForslagOpslag.fk_brugerid` here:
```
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
```
but that column **is NOT** the primary key o... | CONSTRAINT to foreign keys to one table - causes error | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.