Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
when i am trying extract through `regexp` from the below source by using `\|(.*?),1,2` this, i am getting up to end but i need to 3rd / only. when i use `\|(.*/){1,3},1,2` it is giving `http://localhost:6148372/content/bdsajf` and i am stuck up at ending search position. please help me on this.
```
U=https://www.abcdf.com/aecb/app/login|http://llcwokhfkdvc.webs.com/sajc-services
U=http://localhost:7438/en.html|http://localhost:6148372/content/bdsajf/en/kjf-LKJf/FJKSF-cbxjs.html
```
O/P should be # `http://llcwokhfkdvc.webs.com` and `http://localhost:6148372`
Thanks | Try the following expression:
```
\|([^/]*/*[^/]*)
```
See [live demo](http://www.regex101.com/r/rH1qM1) | Try `'\|([^/]*/){1,3}'` (11i):
```
SQL> SELECT regexp_substr(txt, '\|(([^/]*/){1,3})', 1, 1, 'i', '1') regexp
2 FROM DATA;
REGEXP
--------------------------------------------------------------------------------
http://llcwokhfkdvc.webs.com/
http://localhost:6148372/
```
In 10g:
```
SQL> SELECT ltrim(regexp_substr(txt, '\|([^/]*/){1,3}'), '|') regexp
2 FROM DATA;
REGEXP
--------------------------------------------------------------------------------
http://llcwokhfkdvc.webs.com/
http://localhost:6148372/
``` | need to parse up to 3rd / in a string by using regexp in sql | [
"",
"sql",
"regex",
"oracle",
""
] |
Imagine 2 tables, the first one is a list of products (products), the second one a join table between products and another table (categories), called products-categories
products:
```
id | name
------------
1 Lorem
2 Ipsum
3 Dolor
4 Sit
```
products-categories
```
product_id | categories_id
---------------------------
1 3
1 6
4 1
2 2
```
How to get the orphan elements, I mean the elements in no category, so in this case: 3, in a efficient way (+30k records) using MyISAM?
This is somehow like showing all rows that are not joinable, but this syntax seams weird to me... | ```
select * from products p
left join product_categories pc on p.id=pc.product_id
where pc.product_id is null
```
will return all products in table products that are not found in product\_Category. LEft join and where is very fast. 30k records is also very little, so don't worry there. | You can achieve this in 2 ways:
Using SubQuery:
```
SELECT name FROM products
WHERE id NOT IN (SELECT product_id FROM products-categories);
```
or Using JOIN (preferred way)
```
SELECT name FROM products
LEFT JOIN products_categories ON (id=product_id)
WHERE product_id IS NULL;
```
Better to go with join
sqlfiddle demo : <http://sqlfiddle.com/#!9/14ab38/1> | how to get orphans from a join table in MySQL | [
"",
"mysql",
"sql",
"myisam",
""
] |
For example, I have table:
```
ID | Value
1 hi
1 yo
2 foo
2 bar
2 hehe
3 ha
6 gaga
```
I want my query to get ID, Value; meanwhile the returned set should be in the order of frequency count of each ID.
I tried the query below but don't know how to get the ID and Value column at the same time:
```
SELECT COUNT(*) FROM TABLE group by ID order by COUNT(*) desc;
```
The count number doesn't matter to me, I just need the data to be in such order.
Desire Result:
```
ID | Value
2 foo
2 bar
2 hehe
1 hi
1 yo
3 ha
6 gaga
As you can see because ID:2 appears most times(3 times), it's first on the list,
then ID:1(2 times) etc.
``` | ```
select t.id, t.value
from TABLE t
inner join
(
SELECT id, count(*) as cnt
FROM TABLE
group by ID
)
x on x.id = t.id
order by x.cnt desc
``` | you can try this -
```
select id, value, count(*) over (partition by id) freq_count
from
(
select 2 as ID, 'foo' as value
from dual
union all
select 2, 'bar'
from dual
union all
select 2, 'hehe'
from dual
union all
select 1 , 'hi'
from dual
union all
select 1 , 'yo'
from dual
union all
select 3 , 'ha'
from dual
union all
select 6 , 'gaga'
from dual
)
order by 3 desc;
``` | How to do select count(*) group by and select * at same time? | [
"",
"sql",
"oracle",
""
] |
I have a more detailed description ready, but I thought I'd try the simple one first.
```
X Y
7 F
7 F
7 E
7 F
8 F
8 F
```
I want to do something else based on figuring out if for a value (x) of X there is a value of F in Y for all of the x's in the corresponding table. This means 7 doesn't cut it, and 8 does. How do I code this using a subquery? Do I use ALL? I wrote a query but it returns true whenever there is one match instead of all. | Try following query
```
select distinct X from temp
except
select X from temp where Y!='F' -- x,y columns, temp -> table
--Query select all distinct X which has all Y as F
```
Following is alternative query for the same
```
select distinct X from temp where not exists (select X from temp where Y='E')
``` | `Select * from mytable
where X not in ( Select X from mytable
Where Y <> 'F'
)` | SQL: Basic Query | [
"",
"sql",
"sql-server",
""
] |
I'm running a query on a MySQL database
```
SELECT * FROM t_college WHERE NAME="CEPT University"
```
Even though the entry `CEPT University` exists in column `name`, no match is found.
This is same for every other multi-word `varchar` entry in the database. If the value to be matched is a single word like `xyz`, it finds a match but not for multi word ones. | You clearly have some whitespace characters (tabs, newlines, etc) other than space characters in your data.
The best approach usually to clean it up. To help debug the problem, use `HEX()`:
```
select HEX(name)
from t_college
```
This will show each character as a two hexadecimal characters in the range `00` to `FF`.
You should be able to figure out what the unwanted characters are, and when you dr delete them by replacing them with a blank. | So maybe try to update this column to replace your current values with trimmed ones - use TRIM() function to remove trailing and leading spaces and then try to make this SELECT. | Why is SQL not matching anything? | [
"",
"mysql",
"sql",
"database",
""
] |
I have written a sql query
```
select a.unit_code unit,
a.gh_vill pl_vill,
a.gh_grow pl_grow,
(select gh_area
from w_cane_survey_2013 b
where b.croptype_code > 12 and a.gh_no = b.gh_no ) as paudha,
(select gh_area
from w_cane_survey_2013 b
where b.croptype_code < 13 and a.gh_no = b.gh_no) as pedi
from w_cane_survey_2013 a
where a.unit_code = '03' and a.gh_vill = '9991' and gh_grow = '1';
```
when I execute it I am getting an error
**ORA-01427: single-row subquery returns more than one row
01427. 00000 - "single-row subquery returns more than one row"
\*Cause:
\*Action:** | try this query i hope it be helpful:
```
select unit_code as unit,
gh_vill as pl_vill,
gh_grow as pl_grow,
case when croptype_code > 12 then gh_area end as paudha,
case when croptype_code < 13 then gh_area end as pedi
from
w_cane_survey_2013
where
unit_code = '03' and gh_vill = '9991' and gh_grow = '1'
Group by
unit_code, gh_vill , gh_grow, croptype_code, gh_area;
``` | It's because the sub-query returned more than one rows. Add one more condition of ROWNUM=1 in the sub-query and try.
```
select
a.unit_code unit,
a.gh_vill pl_vill,
a.gh_grow pl_grow,
(select gh_area from w_cane_survey_2013 b
where b.croptype_code > 12 and a.gh_no = b.gh_no and ROWNUM=1) as paudha,
(select gh_area from w_cane_survey_2013 b
where b.croptype_code < 13 and a.gh_no = b.gh_no and ROWNUM=1) as pedi
from
w_cane_survey_2013 a
where
a.unit_code = '03' and
a.gh_vill = '9991' and
gh_grow = '1';
``` | how to run such sql query. I am facing an error here ORA-01427 | [
"",
"sql",
"oracle",
""
] |
I have two tables `country` and `state`:
```
country
-----------
cid
countrycode
countryname
state
-------
sid
cid (fk)
statecode
statename
```
I am writing a join as:
```
SELECT s.sid,
s.statename,
c.countryname
FROM state s,
country c
WHERE s.cid = (+) c.cid
AND c.id = 1
```
The above query gives a syntax error. Does MySQL not accept '+' symbol? | No, MySQL does not accept the `+` symbol. Aside from a few exceptions, MySQL uses ANSI standard `JOIN` syntax:
```
SELECT s.sid,
s.statename,
c.countryname
FROM state s
LEFT JOIN country c
ON c.id = s.cid
WHERE c.id = 1
``` | Try this::
```
select
s.sid,
s.statename,
c.countryName
from country c
LEFT JOIN state s on s.cid = c.cid
WHERE c.id=1
``` | sql outer join shows the error in mysql workbench | [
"",
"mysql",
"sql",
"join",
""
] |
Anyone have any ideas? I get this error message in bash...
```
insert_code_sam.rb:31: syntax error, unexpected tIDENTIFIER, expecting ')'
"INSERT INTO index1 (name) VALUES ("test1");"
^
insert_code_sam.rb:32: syntax error, unexpected ')', expecting end-of-input
```
In a single file insert\_code\_sam.rb, I'm trying to create a new db, create two tables, and insert a test row. The SQlite table gets created without a problem, but I can't seem to insert rows.
```
require "sqlite3"
db = SQLite3::Database.new( "new_database.db" )
db.execute(
"CREATE TABLE index1 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
tagline TEXT,
blurb TEXT,
photo_url TEXT);"
)
db.execute(
"CREATE TABLE student_profile (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name_id INTEGER,
thumbnail_url TEXT,
background_url TEXT,
quote TEXT,
bio TEXT,
education TEXT,
work TEXT,
github TEXT,
treehouse TEXT,
codeschool TEXT,
coderwall TEXT);"
)
db.execute(
"INSERT INTO index1 (name) VALUES ("test1");"
)
``` | You are prematurely ending the string – your code is not valid Ruby syntax. [SQLite expects single quoted strings, anyway](http://www.sqlite.org/lang_expr.html). The solution is to use single quotes for the `VALUES`:
```
db.execute(
"INSERT INTO index1 (name) VALUES ('test1');"
)
``` | ```
db.execute(
"INSERT INTO index1 (name) VALUES ('test1');"
)
``` | Getting "syntax error, unexpected tIDENTIFIER..." when trying to insert rows into SQLite via Ruby | [
"",
"sql",
"ruby",
"sqlite",
""
] |
While writing a C# program I am trying to do a batch retrieval from a SQL database instead of getting each record one at a time. This way I get all the records in one DataSet and can just hit the server once. I have found that this method can be significantly faster. However I need to maintain the order. Does anyone have any idea on how to accomplish this?
```
SELECT [UserID], [LastName], [FirstName]
FROM [users]
WHERE [UserID] = '2024443' OR [UserID] = '2205659' OR [UserID] = '2025493';
```
**Edit:**
I need to obtain the data ordered in this way:
```
2024443
2205659
2025493
``` | The appropriate query to run would be:
```
SELECT [UserID], [LastName], [FirstName]
FROM [users]
WHERE [UserID] IN ('2024443', '2205659', '2025493')
ORDER BY [UserID]
```
Provided that you want to keep the order in the results for the `[UserID]` column.
**Edit after clarification on a very weird order the OP is looking for:**
So the expected output will have the selected rows in this order:
```
'2024443'
'2205659'
'2025493'
```
So a simple `ORDER BY` that will order as a character field won't be enough. You should clarify what order it is because clearly you just want to sort based on those 3 rows only (eg: you haven't clarified where you would like to have number `2100000` and it is unpredictable).
For these kind of sorting you could go for an awful solution that will only work on those rows but as I said before, that's all you've provided. So you can do something like this:
```
SELECT [UserID], [LastName], [FirstName]
FROM [users]
WHERE [UserID] IN ('2024443', '2205659', '2025493')
ORDER BY
CASE [UserID]
WHEN '2024443' THEN 0
WHEN '2205659' THEN 1
ELSE 2
END
```
You should be able to build the rest of the queries with that custom sorting. Just follow this as a template. | Does ORDER BY not work?
```
SELECT [UserID]
,[LastName]
,[FirstName]
FROM [users]
WHERE [UserID] = '2024443' OR [UserID] = '2205659' OR [UserID] = '2025493'
ORDER BY [UserID];
```
This will return the records you requested, sorted by UserID. | MySQL custom sorting | [
"",
"sql",
""
] |
I have two tables
**EVENTS**
```
EventCode EventDate
1 2013-07-22 04:00:00.000
2 2013-07-21 11:00:00.000
3 2013-07-21 10:00:00.000
```
**DeviceSignal** which is transaction table
```
TimeStamp DeviceID Value
2013-07-22 03:10:00.000 Dev1 33
2013-07-22 03:00:00.000 Dev2 22
2013-07-21 11:00:00.000 Dev3 23
2013-07-21 10:50:00.000 Dev4 45
2013-07-21 10:40:00.000 Dev5 23
2013-07-21 10:30:00.000 Dev1 54
2013-07-21 10:20:00.000 Dev2 22
2013-07-21 09:50:00.000 Dev1 11
2013-07-21 09:40:00.000 Dev2 23
```
Base on the EventDate , i would like to get timestamp , deviceID and Value, TimeStamp is in the EventDate Hierarchy , how can i get below output ?
```
EventCode EventDate TimeStamp DeviceID Value
1 2013-07-22 04:00:00.000 2013-07-22 03:10:00.000 Dev1 33
1 2013-07-22 04:00:00.000 2013-07-22 03:00:00.000 Dev2 22
2 2013-07-21 11:00:00.000 2013-07-21 10:50:00.000 Dev4 45
2 2013-07-21 11:00:00.000 2013-07-21 10:40:00.000 Dev5 23
2 2013-07-21 11:00:00.000 2013-07-21 10:30:00.000 Dev1 54
2 2013-07-21 11:00:00.000 2013-07-21 10:20:00.000 Dev2 22
3 2013-07-21 10:00:00.000 2013-07-21 09:50:00.000 Dev1 11
3 2013-07-21 10:00:00.000 2013-07-21 09:40:00.000 Dev2 23
``` | ```
SELECT
e.EventCode, e.EventDate,
d.TimeStamp, d.DeviceID, d.Value
FROM
DeviceSignal AS d
OUTER APPLY
( SELECT TOP (1) e.EventCode, e.EventDate
FROM Events AS e
WHERE d.TimeStamp <= e.EventDate
ORDER BY e.EventDate
) AS e ;
``` | I think this is what you're looking for:
```
SELECT
EV.EventCode,
EV.EventDate,
DS.Timestamp,
DS.DeviceID,
DS.Value
FROM
Events EV JOIN DeviceSignal DS
ON CAST(EV.EventDate AS DATE) = CAST(DS.TimeStamp AS DATE)
``` | SQL how can i select data between dates? | [
"",
"sql",
"t-sql",
""
] |
**My Query:**
```
SELECT source.name, file_info.*
from FILE_INFO
JOIN source
ON source.id = file_info.source_ID
where file_info.source_ID in
(select ID from Source where name like 'Donatello.%');
```
**My Tables:**
```
FILE_INFO
FILE_NAME | FILE_ID | SOURCE_ID | DATE_SEEN | CURRENT_STATUS
SOURCE
NAME | ID | CATEGORY
```
**Background:**
In my database, files are associated with the sources who provided them. Each file is given a FILE\_ID and each source has a ID (same as SOURCE\_ID in table FILE\_INFO). However, the table FILE\_INFO doesn't hold the name associated with the SOURCE\_ID.
I'm trying to print all lines where from the table FILE\_INFO along with the respective SOURCE name furthermore, i only want lines where the source providing that file starts with "DONATELLO".
This query works for me, however it runs very slow. Is there a better approach on my code? It works fine until I add that last 'where' clause. When that's included, it runs quite slow.
I appreciate your input. | What about the following ?
```
SELECT source.name, file_info.*
from FILE_INFO
JOIN source
ON source.id = file_info.source_ID and source.name like 'Donatello.%';
``` | Would this not be the same?
```
SELECT source.name, file_info.*
FROM FILE_INFO
JOIN source
ON source.id = file_info.source_ID
WHERE source.name like 'Donatello.%'
``` | WHERE claus after JOIN is slowing down my query | [
"",
"sql",
"oracle",
"join",
"where-clause",
""
] |
I need to display all fixtures(who plays 'against' who) for a current user so I wrote SQL query
```
SELECT
fixture.*
FROM
sport_team_player AS team_player, sport_team AS team
INNER JOIN sport_fixture AS fixture
ON (`team_player`.`team_id` = fixture.`team1_id` OR `team_player`.`team_id` = fixture.`team2_id`)
WHERE
team_player.`team_id` = team.`team_id` AND team_player.`player_id` = '16'
```
And this doesn't work and tells me that team\_player.team\_id does not exist
but if I join the second table instead of selecting from multiple tables it works just fine.
PS. This is not the best way to write such query but it's generated by ORM module..
EDIT:
Result would be list of fixture data like
```
------------------------------
|fixture_id|team1_id|team2_id|
------------------------------
|1 | 2 | 3 |
------------------------------
``` | Precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN. That's why when you mix comma with other join table operators [Unknown column 'col\_name' in 'on clause'] error occur. Same query will work if you specify the cross join ( to get a Cartesian product of the first two tables) instead of commas, because then in the from clause the table operators will be evaluated from left to right:
```
SELECT
fixture.*
FROM
sport_team_player AS team_player
cross join sport_team AS team
INNER JOIN sport_fixture AS fixture
ON (team_player.team_id = fixture.team1_id OR team_player.team_id = fixture.team2_id)
WHERE
team_player.team_id = team.team_id AND team_player.player_id = '16'
``` | Try this one. Should result to the same query as yours;
```
SELECT fixture.*
FROM sport_team_player AS team_player
JOIN sport_team AS team
ON team_player.`team_id` = team.`team_id` AND team_player.`player_id` = '16'
INNER JOIN sport_fixture AS fixture
ON (`team_player`.`team_id` = fixture.`team1_id`
OR `team_player`.`team_id` = fixture.`team2_id`)
```
You shouldn't mix up both notations when building up joins. The comma you are using to join team\_player and team , and the subsequent calls to inner join, will most probably trigger unknown column error. | selecting from multiple tables vs JOIN | [
"",
"mysql",
"sql",
""
] |
I know that there are other questions with the exact title as the one I posted but each of them are very specific to the query or procedure they are referencing.
I manage a Blackboard Learn system here for a college and have direct database access. In short there is a stored procedure that is causing system headaches. Sometimes when changes to the system get committed errors are thrown into logs in the back end, identifying a stored procedure known as `bbgs_cc_setStmtStatus` and erroring out with `The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.`
Here is the code for the SP, however, I did not write it, as it is a stock piece of "equipment" installed by Blackboard when it populates and creates the tables for the application.
```
USE [BBLEARN]
GO
/****** Object: StoredProcedure [dbo].[bbgs_cc_setStmtStatus] Script Date: 09/27/2013 09:19:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[bbgs_cc_setStmtStatus](
@registryKey nvarchar(255),
@registryVal nvarchar(255),
@registryDesc varchar(255),
@overwrite BIT
)
AS
BEGIN
DECLARE @message varchar(200);
IF (0 < (SELECT count(*) FROM bbgs_cc_stmt_status WHERE registry_key = @registryKey) ) BEGIN
IF( @overwrite=1 ) BEGIN
UPDATE bbgs_cc_stmt_status SET
registry_value = @registryVal,
description = @registryDesc,
dtmodified = getDate()
WHERE registry_key = @registryKey;
END
END
ELSE BEGIN
INSERT INTO bbgs_cc_stmt_status
(registry_key, registry_value, description) VALUES
(@registryKey, @registryVal, @registryDesc);
END
SET @message = 'bbgs_cc_setStmtStatus: Saved registry key [' + @registryKey + '] as status [' + @registryVal + '].';
EXEC dbo.bbgs_cc_log @message, 'INFORMATIONAL';
END
```
I'm not expecting Blackboard specific support, but I want to know if there is anything I can check as far as SQL Server 2008 is concerned to see if there is a system setting causing this. I do have a ticket open with Blackboard but have not heard anything yet.
Here are some things I have checked:
tempdb system database:
I made the templog have an initial size of 100MB and have it auto grow by 100MB, unrestricted to see if this was causing the issue. It didn't seem to help. Our actual tempdb starts at 4GB and auto grows by a gig each time it needs it. Is it normal for the space available in the tempdb to be 95-985 of the actual size of the tempdb? For example, right now tempdb has a size of 12388.00 MB and the space available is 12286.37MB.
Also, the log file for the main `BBLEARN` table had stopped growing because it reached its maximum auto grwoth. I set its initial size to 3GB to increase its size. | I see a couple of potential errors that could be preventing the commit but without knowing more about the structure these are just guesses:
1. The update clause in the nested if is trying to update a column (or set of columns) that must be unique. Because the check only verifies that at least one item exists but does not limit that check to making sure only one item exists
```
IF (0 < (SELECT ...) ) BEGIN
```
vs.
```
IF (1 = (SELECT ...) ) BEGIN
```
you could be inserting non-unique values into rows that must be unique. Check to make sure there are no constraints on the attributes the update runs on (specifically look for primary key, identity, and unique constraints). Likelyhood of this being the issue: Low but non-zero.
2. The application is not passing values to all of the parameters causing the @message string to null out and thus causing the logging method to error as it tries to add a null string. Remember that in SQL anything + null = null so, while you're fine to insert and update values to null you can't log nulls in the manner the code you provided does. Rather, to account for nulls, you should change the setter for the message variable to the following:
```
SET @message = 'bbgs_cc_setStmtStatus: Saved registry key [' + COALESCE(@registryKey, '') + '] as status [' + COALESCE(@registryVal,'') + '].';
```
This is far more likely to be your problem based on the reported error but again, without the app code (which might be preventing null parameters from being passed) there isn't any way to know.
Also, I would note that instead of doing a
```
IF (0 < (SELECT count(*) ...) ) BEGIN
```
I would use
```
IF (EXISTS (SELECT 1 ...) ) BEGIN
```
because it is more efficient. You don't have to return every row of the sub-query because the execution plan will run the FROM statement first and see that rows exist rather than having to actually evaluate the select, count those rows, and then compare that with 0.
Start with those suggestions and, if you can come back with more information, I can help you troubleshoot more. | Maybe you could use a MERGE statement :
<http://msdn.microsoft.com/fr-fr/library/bb510625%28v=sql.100%29.aspx>
I think it will be more efficient. | Current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am currently working on a DataImport script, which is intended to move data from one database to another. The main problem I have come across is that the table in question contains a lot of duplicate records, with the duplicate fields being Product Code, Language, Legislation, Brand Name, Formula and Version, i.e we might have the following in the database:
> My Test Product, English, UK, Test Brand, Test Formula, 1 (ID 1 - not included in group by)
> My Test Product, English, UK, Test Brand, Test Formula, 1 (ID 2 - not included in group by)
> My Test Product, English, UK, Test Brand, Test Formula, 1 (ID 3 - not included in group by)
> My Test Product, English, UK, Test Brand, Test Formula, 1 (ID 4 - not included in group by)
As you can see these records are identical in every way. My problem is, that as part of the data load script I wish to delete records with IDs of 1, 2 and 3 whilst retaining the record with the ID of 4 as this will be the most up-to-date record and hence the one I wish to keep. To do this, I have written a T-SQL script as follows:
```
-- get the list of items where there is at least one duplicate
DECLARE cDuplicateList CURSOR FOR
SELECT productcode, languageid, legislationid, brandName, versionnumber, formulaid
FROM allproducts
GROUP BY productcode, languageid, legislationid, brandName, versionnumber, formulaid
HAVING COUNT (*) > 1
OPEN cDuplicateList
FETCH cDuplicateList INTO @productCode, @languageId, @legislationId, @brandName, @versionNumber, @formulaId
-- while there are still duplicates
WHILE @@FETCH_STATUS=0
BEGIN
-- delete from the table where the product ID is in the sub-query, which contains all
-- of the records apart from the last one
DELETE FROM AllProducts
WHERE productId IN
(
SELECT productId
FROM allProducts
WHERE productCode = @productCode
AND (languageId = @languageId OR @languageId IS NULL)
AND (legislationId = @legislationId OR @legislationId IS NULL)
AND (brandName = @brandName OR @brandName IS NULL)
AND (versionNumber = @versionNumber OR @versionNumber IS NULL)
AND (formulaId = @formulaId OR @formulaId IS NULL)
EXCEPT
SELECT TOP 1 productId
FROM allProducts
WHERE productCode = @productCode
AND (languageId = @languageId OR @languageId IS NULL)
AND (legislationId = @legislationId OR @legislationId IS NULL)
AND (brandName = @brandName OR @brandName IS NULL)
AND (versionNumber = @versionNumber OR @versionNumber IS NULL)
AND (formulaId = @formulaId OR @formulaId IS NULL)
)
FETCH cDuplicateList INTO @productCode, @languageId, @legislationId, @brandName, @versionNumber, @formulaId
END
```
Now, this does work - its just incredibly slow and I can't think of any easy way to make it faster. Does anyone have any ideas how I can maintain the same functionality but make it run faster? | You can already use a `common-table-expression` and `ROW_NUMBER` in SQL\_Server 2005:
```
WITH CTE AS
(
SELECT ProductCode, Language, Legislation, BrandName, Formula, Version,
RN = ROW_NUMBER()
OVER (
PARTITION BY productcode, language, legislation, brandname, formula, version
ORDER BY id DESC)
FROM dbo.Students
)
DELETE FROM CTE WHERE RN > 1
```
Change `DELETE` to `SELECT *` if you want to see what you'll delete. | You could use row\_number() over (partition by productcode, languageid, legislationid, brandName, versionnumber, formulaid order by productId desc )
and delete all producitids with row\_number > 1 | SQL Server 2005 - deleting duplicate records whilst maintaining the first one | [
"",
"sql",
"t-sql",
"sql-server-2005",
""
] |
How to get the "max" range of dates from multiple dateBegin and dateEnd ? My question is not well explained (cause im not english) but the example below will show you what I expect.
My database :

The output I'd like :
```
id_master beginDate endDate
13 26/07/2014 30/08/2014
280 28/09/2013 01/10/2013
280 01/04/2014 11/04/2014
```
Explain : for distinct id\_master, i would like to have the diferrent periods of dates composed of the minimum beginDate and the maximum endDate with all the days between those dates having a product (row in the table)
Current query :
```
SELECT DISTINCT campings.id_master, CAST(campings.dateBegin AS DATETIME) AS beginDate, CAST(campings.dateEnd AS DATETIME) AS endDate
FROM campings
ORDER BY id_master, beginDate, endDate
```
PS: date format is dd/mm/yyyy | This is probably a lot more contrived than it has to be, and someone else can come up with a simpler answer, but you can try something like the following:
```
WITH ordered AS (
SELECT a.id_master, a.beginDate, a.endDate,
ROW_NUMBER() OVER(PARTITION BY id_master ORDER BY beginDate, endDate) AS rn
FROM Table1 a
), Adjacent AS (
SELECT a.id_master, a.beginDate, a.endDate, a.rn
FROM ordered a
UNION ALL
SELECT a.id_master, a.beginDate, b.endDate, b.rn
FROM Adjacent a
INNER JOIN ordered b ON a.id_master = b.id_master AND b.rn > a.rn
AND a.endDate >= b.beginDate
), resolvedEnd AS (
SELECT a.id_master, a.beginDate, MAX(a.endDate) AS endDate
FROM Adjacent a
GROUP BY a.id_master, a.beginDate
)
SELECT a.id_master, MIN(beginDate) AS beginDate, endDate
FROM resolvedEnd a
GROUP BY a.id_master, a.endDate
```
[SQL Fiddle example](http://www.sqlfiddle.com/#!3/f5b30/27)
What this does is first attach an ascending row number to each row to make sure we recurse only in the forward direction. Then it sets up a recursive CTE to associate overlapping rows (and overlapping rows of overlapping rows). It then resolves the largest end date for each begin date, and then resolves the earliest begin date for each end date. | For others, here is the result of my current needs. On ***Informix 11.70*** and above has the same results this construction :
```
SELECT id_master , MIN(beginDate) AS beginDate, endDate FROM
LATERAL (
SELECT id_master, beginDate, MAX(endDate) AS endDate FROM
LATERAL (
SELECT id_master, beginDate, CONNECT_BY_ROOT endDate FROM
LATERAL (
SELECT id_master, beginDate, endDate, ROW_NUMBER() OVER(PARTITION BY id_master ORDER BY beginDate, endDate) AS row_num FROM campings
) AS ordered
CONNECT BY
PRIOR id_master = id_master AND
PRIOR row_num > row_num AND
PRIOR endDate + 1 >= beginDate AND
PRIOR beginDate - 1 <= endDate
) AS Adjacent
GROUP BY id_master, beginDate
) AS resolvedEnd
GROUP BY id_master, endDate
``` | SQL : Get range date from multiple begin and end date | [
"",
"sql",
"sql-server",
""
] |
Imagine I have a table (Mysql myISAM) with a child->parent relationship (categories and multiple levels of subcategories)
```
+--------+---------+
| id |parent_id|
+--------+---------+
| 1 | null |
| 2 | 1 |
| 3 | 2 |
| 4 | 7 |
| 5 | 1 |
| 6 | 5 |
+--------+---------+
```
How would you find all children of some ID, like querying for id 1 would output :
2,5,3,6 ? (order has no importance)
So in other words, how to do a reverted children lookup on this parent\_link ?
At the moment, I cycle in php and query for the parent\_id, then again and concatenate all the results in a string while there are results, but this is so slow... | ```
create table my_table(
id int,
parent_id int
);
insert into my_table values
(1,null),
(2,1),
(3,2),
(4,7),
(5,1),
(6,5);
```
This stored procedure will get you all the children of any given id
```
DELIMITER $$
DROP PROCEDURE IF EXISTS get_children$$
CREATE PROCEDURE get_children(IN V_KEY INT)
proc:
BEGIN
DECLARE vid text;
declare oid text;
DECLARE count int;
CREATE TEMPORARY TABLE temp_child_nodes(
id int
);
SET vid = V_KEY;
INSERT INTO temp_child_nodes(id) SELECT id from my_table where parent_id = vid;
SELECT GROUP_CONCAT(concat("'",id,"'")) INTO oid from my_table where parent_id = vid;
SET vid = oid;
SET count = 0;
SET @val = '';
WHILE (vid is NOT NULL) DO
SET @sql = CONCAT("INSERT INTO temp_child_nodes(id) SELECT id from my_table where parent_id IN (",vid,")");
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET @tsql = CONCAT("SELECT GROUP_CONCAT(id) INTO @val from my_table where parent_id IN (", vid, ")");
PREPARE stmt2 FROM @tsql;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
SET vid = @val;
SET count = count + 1;
END WHILE;
#SELECT count;
SELECT * from temp_child_nodes;
#SELECT oid;
END
$$
DELIMITER ;
```
CALL get\_children(1);
```
mysql> CALL get_children(1);
+------+
| id |
+------+
| 2 |
| 5 |
| 3 |
| 6 |
+------+
4 rows in set (0.22 sec)
Query OK, 0 rows affected (0.22 sec)
``` | Ok, so thanks to Deepak code, I managed to write this, a bit shorter readable, it accepts a table as parameter and returns also the depth of the element.
```
DELIMITER $$
CREATE PROCEDURE get_children(IN V_KEY INT,IN SOURCETABLE VARCHAR(255))
proc:
BEGIN
DECLARE vid text;
DECLARE count int;
DROP TABLE IF EXISTS `temp_child_nodes`;
CREATE TEMPORARY TABLE temp_child_nodes(id int, depth int);
SET vid = V_KEY;
SET @val = '';
SET count = 0;
WHILE (vid is NOT NULL) DO
SET @sql = CONCAT("INSERT INTO temp_child_nodes(id,depth) SELECT id,'",count,"' from ",SOURCETABLE," where parent_id IN (",vid,")");
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET @tsql = CONCAT("SELECT GROUP_CONCAT(id) INTO @val from ",SOURCETABLE," where parent_id IN (", vid, ")");
PREPARE stmt2 FROM @tsql;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
SET vid = @val;
SET count = count + 1;
END WHILE;
#output data
SELECT * from temp_child_nodes;
END
$$
DELIMITER ;
``` | find out list of inverted hierarchy in mysql | [
"",
"mysql",
"sql",
"myisam",
""
] |
I have the followings tables on my database

There are several *project statuses* (waiting, working, finished, paid) and a project have to pass through all the status from waiting to paid.
In order to keep complete track of the project, each status are kept, so we know when a project changed its status.
I would like to create a *search filter* with the **current status** (the one with the more recent "created\_at").
I tried few queries in order to get the correct result, but I'm stuck with this one.
The not-working query I have is
```
select p.* from projects p
left join projects_status_projects psp on psp.project_id = p.id
where p.id in (select project_id from projects_status_projects
where project_status_id = XX group by project_id order by created_at desc)
```
Ofc, this query does not work and return me each projects with a record for project\_status\_id XX without taking in account the order.
Any hint would be very appreciated !
Thanks,
Benjamin | ```
select p.* from projects p
left join projects_status_projects psp on (psp.project_id = p.id)
where created_at = (select max(created_at)
from projects_status_projects where
project_id = p.id)
```
sqlfiddle with some example here: <http://sqlfiddle.com/#!2/725fcc/7/0> | If you just need the current status of the project
Try this::
```
Select DITINCT(p.id),p.*
from projects p
left join projects_status_projects psp on psp.project_id = p.id
where project_status_id = XX
order by created_at desc
``` | Join query by date and primary | [
"",
"mysql",
"sql",
""
] |
I have a booking table with 6 columns called booked\_start, booked\_stop, used\_start, used\_stop, invoice\_start, invoice\_stop. The values are floats. I want to get a sum of the rows that has values above 0 but i also want it to calculate say used\_stop - used\_start.
Currently im working with this:
```
SELECT
room,
IF( booked_stop_time > 0, sum(booked_stop_time - booked_start_time), 0 ) as booked,
IF( used_stop_time > 0, sum(used_stop_time - used_start_time), 0 ) as used,
IF( invoice_stop_time > 0, sum(invoice_stop_time - invoice_start_time), 0 ) as invoice
FROM bookings
```
The problem is that if expr1 returns false it'll reset the sum. I only want to add the rows value to the sum if its above 0.
I also tried using a case but that didnt really work. Maybe i should do the calculation in php instead? | This should work:
```
SELECT
room,
SUM(
CASE WHEN booked_stop_time - booked_start_time > 0
THEN booked_stop_time - booked_start_time
END
) AS booked,
SUM(
CASE WHEN used_stop_time - used_start_time > 0
THEN used_stop_time - used_start_time
END
) AS used,
SUM(
CASE WHEN invoice_stop_time - invoice_start_time > 0
THEN invoice_stop_time - invoice_start_time
END
) AS invoice
FROM bookings
```
Focusing on the `booked` value:
* If `booked_stop_time - booked_start_time` is greater than zero the `CASE` returns `booked_stop_time - booked_start_time`, so it's included in the sum.
* The `CASE` doesn't have any other conditions, so if `booked_stop_time - booked_start_time` is *not* greater than zero, the `CASE` returns NULL, which means the row is not included in the sum. | You can do it like this:
```
SELECT
room,
SUM(IF( booked_stop_time > 0, booked_stop_time - booked_start_time, 0 )) as booked,
SUM(IF( used_stop_time > 0, used_stop_time - used_start_time, 0 )) as used,
SUM(IF( invoice_stop_time > 0, invoice_stop_time - invoice_start_time, 0 )) as invoice
FROM bookings
```
It return 0 because when your `IF` condition not satisfy then it set to `0` as final value, so just wrap the `IF` with `SUM`. | Calculate multiple values with sql with if expression | [
"",
"mysql",
"sql",
"math",
""
] |
Good Day Every one
i have this code
```
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,4,AE.LOAN)) as [Month]
,COUNT(ISNULL(PIT.ID,0))'COUNT'
,SUM(ISNULL(PIT.KGRAM,0))'GRAMS'
,SUM(ISNULL(PH.AMOUNT,0))'PRINCIPAL'
FROM #AllExpired AE
INNER JOIN Transactions.ITEM PIT
ON AE.MAINID=PIT.MAINID
INNER JOIN Transactions.HISTO PH
ON AE.MAINID=PH.MAINID
GROUP BY DATENAME(MM,(DATEADD(MM,4,AE.LOAN)))
UNION ALL
/*SELECT EXPIRED AFTER 5 MONTHS*/
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,5,AE.LOAN)) as [Month]
,COUNT(ISNULL(PIT.ID,0))'COUNT'
,SUM(ISNULL(PIT.KGRAM,0))'GRAMS'
,SUM(ISNULL(PH.AMOUNT,0))'PRINCIPAL'
FROM #ExpAfterFiveMonths E5
INNER JOIN Transactions.ITEM PIT
ON E5.MAINID=PIT.MAINID
INNER JOIN Transactions.HISTO PH
ON E5.MAINID=PH.MAINID
INNER JOIN #AllExpired AE
ON AE.MAINID=E5.MAINID
GROUP BY DATENAME(MM,(DATEADD(MM,5,AE.LOAN)))
UNION ALL
/*SELECT EXPIRED AFTER 6 MONTHS*/
SELECT
'Expired Item -'+ DateName(mm,DATEADD(MM,6,AE.LOAN)) as [Month]
,COUNT(ISNULL(PIT.ID,0))'COUNT'
,SUM(ISNULL(PIT.KGRAM,0))'GRAMS'
,SUM(ISNULL(PH.AMOUNT,0))'PRINCIPAL'
FROM #ExpAfterSixMonths E6
INNER JOIN Transactions.ITEM PIT
ON E6.MAINID=PIT.MAINID
INNER JOIN Transactions.HISTO PH
ON E6.MAINID=PH.MAINID
INNER JOIN #AllExpired AE
ON AE.MAINID=E6.MAINID
GROUP BY DATENAME(MM,(DATEADD(MM,6,AE.LOAN)))
```
and it works fine, the problem is that when the Select statements retrieved no rows they become empty instead of replacing zeroes
instead of Generating the word month with 0 0 0 it just pops out empty in which i dont like,,
can you help me achive that? the result should be something like this
```
------------------------------------------------------------------
MONTH | Count | Grams | Principal |
October |123123 | 123123 | 123123213 |
November | 0 | 0 | 0 | // this should appear if no rows where selected instead of blank
```
here is my code to generate the items inside temptables
```
SELECT TE.MAINID
,TE.EXPIRY
,TE.LOAN
,PM.STORAGE
into #AllExpiredAfterFiveAndSix
FROM #ExpiredAfterFiveandSixMon TE
inner join Transactions.TABLEMAIN PM
on TE.MAINID = PM.MAINID
inner join #AllExpired E4
on E4.MAINID=TE.MAINID
WHERE ((cast(TE.EXPIRY as date) < cast(TE.newloandate as date))
OR(TE.NewLoanDate is null and ((cast(TE.EXPIRY as date) < cast(PM.DATERED as date)) or PM.STATUS = 7 or PM.STATUS = 5)) )
AND (PM.STORAGE BETWEEN 3 AND 14 OR PM.STORAGE=17)
/*EXPIRED AFTER 5 MONTHS*/
select AE.MAINID
,AE.LOAN
,AE.STORAGE
,ae.EXPIRY
into #ExpAfterFiveMonths
from #AllExpiredAfterFiveAndSix AE
inner join #AllExpired E4
on E4.MAINID=AE.MAINID
where MONTH(AE.EXPIRY)= MONTH(dateadd(mm,1,E4.EXPIRY))
/*EXPIRED AFTER 6 MONTHS*/
select AE.MAINID
,AE.LOAN
,AE.STORAGE
,ae.EXPIRY
into #ExpAfterSixMonths
from #AllExpiredAfterFiveAndSix AE
inner join #AllExpired E4
on E4.MAINID=AE.MAINID
where MONTH(AE.EXPIRY)= MONTH(dateadd(mm,2,E4.EXPIRY))
CREATE NONCLUSTERED INDEX IDX_ExpAfterFiveMonths ON #ExpAfterFiveMonths(MAINID)
CREATE NONCLUSTERED INDEX IDX_ExpAfterSixMonths ON #ExpAfterSixMonths(MAINID)
```
i hope you can help me because im just a starter in sql
i have tried using is NULL as what you have seen above but i do not know if i implement it correctly
Hoping for your Kindness and consideration thank you :)
\*\*\*\*EDIT\*\*
The temp tables contains no values to start with, i just want it to output 0 instead of blank. | Edited: Added a months table to handle empty temp tables.
Change inner joins to left joins.
```
DECLARE @months TABLE (ReportMonth VARCHAR(20) NOT NULL)
INSERT INTO @months VALUES
('January'),('February'),('March'),('April'),
('May'),('June'),('July'),('August'),
('September'),('October'),('November'),('December')
SELECT
'Expired Item -'+ COALESCE(DateName(mm,DATEADD(MM,4,AE.fld_LoanDate)), M.ReportMonth) as [Month]
,COUNT(ISNULL(PIT.fld_PawnItemID,0))'COUNT'
,SUM(ISNULL(PIT.fld_KaratGram,0))'GRAMS'
,SUM(ISNULL(PH.fld_PrincipalAmt,0))'PRINCIPAL'
FROM
@months M
LEFT JOIN #AllExpired AE
ON M.ReportMonth = DateName(mm,DATEADD(MM,4,AE.fld_LoanDate))
LEFT JOIN Transactions.tbl_PawnItem PIT
ON AE.fld_PawnMainID=PIT.fld_PawnMainID
LEFT JOIN Transactions.tbl_PawnHisto PH
ON AE.fld_PawnMainID=PH.fld_PawnMainID
GROUP BY M.ReportMonth
UNION ALL
/*SELECT EXPIRED AFTER 5 MONTHS*/
SELECT
'Expired Item -'+ 'Expired Item -'+ COALESCE(DateName(mm,DATEADD(MM,5,AE.fld_LoanDate)), M.ReportMonth) as [Month]
,COUNT(ISNULL(PIT.fld_PawnItemID,0))'COUNT'
,SUM(ISNULL(PIT.fld_KaratGram,0))'GRAMS'
,SUM(ISNULL(PH.fld_PrincipalAmt,0))'PRINCIPAL'
FROM
@months M
LEFT JOIN #AllExpired AE
ON M.ReportMonth = DateName(mm,DATEADD(MM,5,AE.fld_LoanDate))
LEFT JOIN #ExpAfterFiveMonths E5
ON AE.fld_PawnMainID=E5.fld_PawnMainID
LEFT JOIN Transactions.tbl_PawnItem PIT
ON E5.fld_PawnMainID=PIT.fld_PawnMainID
LEFT JOIN Transactions.tbl_PawnHisto PH
ON E5.fld_PawnMainID=PH.fld_PawnMainID
GROUP BY M.ReportMonth
UNION ALL
/*SELECT EXPIRED AFTER 6 MONTHS*/
SELECT
'Expired Item -'+ COALESCE(DateName(mm,DATEADD(MM,6,AE.fld_LoanDate)), M.ReportMonth) as [Month]
,COUNT(ISNULL(PIT.fld_PawnItemID,0))'COUNT'
,SUM(ISNULL(PIT.fld_KaratGram,0))'GRAMS'
,SUM(ISNULL(PH.fld_PrincipalAmt,0))'PRINCIPAL'
FROM
@months M
LEFT JOIN #AllExpired AE
ON M.ReportMonth = DateName(mm,DATEADD(MM,6,AE.fld_LoanDate))
LEFT JOIN #ExpAfterSixMonths E6
ON AE.fld_PawnMainID=E6.fld_PawnMainID
LEFT JOIN Transactions.tbl_PawnItem PIT
ON E6.fld_PawnMainID=PIT.fld_PawnMainID
LEFT JOIN Transactions.tbl_PawnHisto PH
ON E6.fld_PawnMainID=PH.fld_PawnMainID
GROUP BY M.ReportMonth
``` | Try this in your select
```
SELECT (CASE WHEN (AE.fld_LoanDate IS null) THEN 0 ELSE AE.fld_LoanDate END) as fld_LoanDate
``` | Generate Zeroes when no rows where selected | [
"",
"sql",
"t-sql",
"reporting-services",
"sql-server-2008-r2",
"isnull",
""
] |
I've following table **stuinfo**
```
+------------+-------+-----------+
| Roll_no | Name | Lastname |
+------------+-------+-----------+
| 37032 | johny | bravo |
| 37034 | sam | smith |
+------------+-------+-----------+
```
and second one **stu\_attendace**
```
+------------+-------+-----------+
| Roll_no | Name | month |
+------------+-------+-----------+
| -1 | total | 26 |
| 37032 | johny | 19 |
| 37034 | sam | 25 |
+------------+-------+-----------+
```
Total days are 26 , so johny's attendance is 73.03% and Sam's attendance is 95.03% .
So how can I show their Attendance with percentage by calculating at run-time and showing those values in new column 'per\_attendace' which is actually not in database. like shown in below
```
+----------+--------+-----------+---------------+
| roll_no | name | last_name | per_attendace |
+----------+--------+-----------+---------------+
| 37032 | johny | bravo | xx % |
| 37034 | sam | smith | xx % |
+----------+--------+-----------+---------------+
``` | You can easily do what you want, in the `SELECT` clause you can select a literal value, or a column name, or any valid expression.
Just `JOIN` the two tables, and then calculate the percent like this:
```
SELECT
i.roll_no,
i.name,
i.Lastname,
((a.month / 26) * 100) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendance AS a ON i.Roll_no = a.Roll_no;
```
**Note that:**
* There is no need to duplicate the column name in both the two tables, just remove it from the other table, and keep your tables [***normalized***](http://en.wikipedia.org/wiki/Database_normalization).
* Don't store the total value like this as a value in the column.
---
**Update:**
If you want to select the value of the total from the database, you can do this:
```
SELECT
i.roll_no,
i.name,
i.Lastname,
((a.month / (SELECT month
FROM stu_attendace
WHERE name = 'total')) * 100) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendance AS a ON i.Roll_no = a.Roll_no;
```
* [**SQL Fiddle Demo**](https://www.google.com.eg/#btnK=%D8%A8%D8%AD%D8%AB+Google%E2%80%8F&q=mysql+round+number)
---
You can also set that total value as a variable instead of the correlated subquery, like this:
```
SET @total = 0;
SELECT month
FROM stu_attendace
WHERE name = 'total'
INTO @total;
```
Then:
```
SELECT
i.roll_no,
i.name,
i.Lastname,
ROUND(((a.month / @total) * 100), 2) AS percent
FROM stuinfo AS i
INNER JOIN stu_attendace AS a ON i.Roll_no = a.Roll_no;
```
I used the `ROUND` function to round the number to only two decimal values.
* [**Updated SQL Fiddle Demo**](http://www.sqlfiddle.com/#!2/7e4e7/7) | Try this
```
select a.roll_no , a.name ,a.last_name,(b.month/26)*100 as per_attendace
from stuinfo as a join
stu_attendace as b on a.roll_no=b.roll_no
``` | how to show virtual column with calculated runtime values(i.e not in database) in mysql? | [
"",
"mysql",
"sql",
""
] |
Is there any way to optionally update any of a number of fields in an SQL statement? I can only get so far as something like:
```
UPDATE Customer SET
ContactName = ? <=== what to do here if ? is null???
, CompanyName = ? <=== what to do here if ? is null???
, AddressId = ? <=== what to do here if ? is null???
, ...
WHERE CustomerId = ?
```
It must be a single statement due to a limitation of the wrapper layer and MySQL.
To clarify, I want to create one statement which will be run with one or more non-null values for the fields listed and will update only those fields where the value is not null, leaving the others alone.
This is for a RESTful update API where I don't want a separate statement for every possible combination of fields and I don't want to demand that the API caller supply every single field on the record, which would be unwieldy and would not be future-proof (adding a field breaks existing API calls). And because it's a REST API I am looking to map `POST /customer/xxx?ContactName=...&CompanyName=...` to update the record. | Not entirely clear on your goal, but I think you're looking for the [coalesce](https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) feature; it will return the first non-null value:
> mysql> SELECT COALESCE(NULL,1); -> 1
>
> mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL
So you can set a 'default' to use in case the value is null:
```
UPDATE Customer SET
ContactName = COALESCE(?, <Some default>)
...
```
If you don't want to change the field, just use the current value:
```
UPDATE Customer SET
ContactName = COALESCE(?, ContactName)
``` | Usually you would want to use the existing value if the parameter is null in an update:
```
UPDATE Customer SET
ContactName = COALESCE(?,ContactName)
``` | Update any of a number of fields in an SQL statement | [
"",
"mysql",
"sql",
""
] |
A salary table is given and we need to write a single query which prints the cumulative salary of employees.
For Example:
```
Emp Sal
A 10
B 15
C 20
D 5
OutPut:
Emp Sal Cum_Sal
A 10 10
B 15 25
C 20 45
D 5 50
``` | in some RDBMS (like PostgreSQL or SQL Server 2012 or Oracle) it's possible to use window function:
```
select
Emp, Sal, sum(Sal) over(order by Emp) as Cum_Sal
from employees
```
if it's not possible, you can use self-join
```
select
e1.Emp, e1.Sal, sum(e2.Sal) as Cum_Sal
from employees e1
inner join employees e2 on e2.Emp <= e1.Emp
group by e1.Emp, e1.Sal
```
**`sql fiddle demo`**
Note that in both cases you have to define order for rolling sum (in queries above, it's ordered by `Emp` column). | For MS SQL please try this:
```
select NAME,SAL,sum(SAL)
over(order by SAL rows between unbounded preceding and current row) as cum_sal
from employee
``` | What query should I write to calculate the cumulative salary of employees from the salary table | [
"",
"sql",
"oracle",
"oracle9i",
""
] |
While reading data of sql server from gridview ,the date column adds an extra 12:00:00 AM to the end of the date.
eg:9/29/2013 12:00:00 AM
In the gridview it shows this way, but i only have a **date** type date saved in the sql table.
I need that to be only 9/29/2013.
same thing happened while reading and displaying that in a textbox , but it could be solved this way
```
DateTime date =Convert.ToDateTime(VoucherDetails["voucher_date"]);
TextBox3.Text = date.ToString("MM/dd/yyyy");
```
any solutions for the gridview ? | Here's an example of a bound field.
```
<asp:BoundField DataField="TheDateField" HeaderText="HeaderText"
DataFormatString="{0:MM-dd-yyyy}" />
```
All you should have to do is add DataFormatString="{0:MM-dd-yyyy}" to your bound field. | To format a DATETIME value in a GridView, you can do it like this:
DataFormatString="{0:MM-dd-yyyy}". | Reading date from sql date format adds extra 12:00:00 AM? | [
"",
"asp.net",
"sql",
"sql-server",
"gridview",
""
] |
Im trying to write a select query in pgSQL that shows items that are priced at more than `100,000` and less than or equal to `200,000`. I realise there is a `BETWEEN` function but that isn't exactly what I want.
What I have so far:
```
SELECT id FROM Item WHERE (Price = >100000 AND Price = <=200000);
```
Apologies for this being so basic just trying to learn `SQL` from the ground up..
Thanks in advance. | You have problems with your `<=` and `>=` conditions. the `=` is always last and only occurs once.
```
SELECT id FROM Item WHERE Price >=100000 AND Price <=200000;
``` | You have two choices:
```
SELECT id
FROM Item
WHERE Price > 100000
AND Price <= 200000
```
Or use the inclusive BETWEEN with an adjusted lower bound:
```
SELECT id
FROM Item
WHERE Price BETWEEN 100001 AND 200000
``` | BASIC SQL How To Select Greater than 100000 and less than 200000 | [
"",
"sql",
"postgresql",
""
] |
I am trying to create a high score board for a video game.
There is a `users` table:

And a `scores` table:

I have tried using this query:
```
SELECT MAX(`scores`.`score`) AS max_score,
`scores`.`team`,
`users`.`name`
FROM `scores`
LEFT JOIN `users`
ON `users`.`id` = `scores`.`user_id`
GROUP BY `scores`.`user_id`
ORDER BY max_score DESC
LIMIT 50
```
Which returns this result (sample):

As you can see, user `FUNTIMES`'s score of `210` is being attributed to the `eagles` when it should be attributed to the `vikings` according to the `scores` table (`FUNTIMES`'s `user_id` is 11).
How would I go about fixing this? Something like this would work beautifully:
```
SELECT `scores`.`score`, `scores`.`team`, `users`.`name`
FROM `scores`
LEFT JOIN `users`
ON `users`.`id` = `scores`.`user_id`
WHERE `scores`.`id` IN (
SELECT MAX(`scores`.`score`)
FROM `scores`
GROUP BY `scores`.`user_id`
)
ORDER BY `scores`.`score` DESC
LIMIT 50
```
but, of course, I can't select WHERE `id` is IN `score`. I'm completely lost.
Thanks in advance for any help.
EDIT: Sorry, I forgot to mention: Each user can only be displayed once in the high scores table. (This is why I have the GROUP BY `user_id` stipulation in my query.) | ```
SELECT scores.score, scores.team, users.name
FROM users
JOIN scores
ON users.id = scores.user_id
WHERE NOT EXISTS
(SELECT *
FROM scores scores2
WHERE scores2.score > scores.score
AND scores2.user_id = users.id)
``` | [SQL Fiddle](http://sqlfiddle.com/#!2/1b5efe/8)
**MySQL 5.5.32 Schema Setup**:
```
CREATE TABLE users
(`id` int, `name` varchar(8), `pass` varchar(4))
;
INSERT INTO users
(`id`, `name`, `pass`)
VALUES
(2, 'JAKE', 'jake'),
(3, NULL, NULL),
(4, 'AWNO', 'ffff'),
(5, 'FFF', 'ffff'),
(6, 'ASDF', 'asdf'),
(7, 'KKK', 'kkkk'),
(8, 'AW YEAH', 'good'),
(9, 'FFFF', 'ffff'),
(10, 'FUNTIME', 'llll'),
(11, 'FUNTIMES', 'llll'),
(12, 'GOOD', 'good')
;
CREATE TABLE scores
(`id` int, `user_id` int, `team` varchar(7), `score` int)
;
INSERT INTO scores
(`id`, `user_id`, `team`, `score`)
VALUES
(32, 9, 'vikings', 610),
(33, 10, 'eagles', 290),
(34, 11, 'eagles', 0),
(35, 11, 'vikings', 40),
(36, 11, 'vikings', 210),
(37, 12, 'eagles', 170),
(38, 12, 'eagles', 30)
;
```
**Query 1**:
```
SELECT m.`max_score`,
s.`team`,
u.`name`
FROM `scores` s
LEFT JOIN `users` u
ON u.`id` = s.`user_id`
INNER JOIN (SELECT `user_id`, MAX(`score`) as max_score
FROM `scores`
GROUP BY `user_id`) m ON m.`user_id` = s.`user_id` AND
m.`max_score` = s.`score`
ORDER BY max_score DESC
LIMIT 50
```
**[Results](http://sqlfiddle.com/#!2/1b5efe/8/0)**:
```
| MAX_SCORE | TEAM | NAME |
|-----------|---------|----------|
| 610 | vikings | FFFF |
| 290 | eagles | FUNTIME |
| 210 | vikings | FUNTIMES |
| 170 | eagles | GOOD |
```
FOR DISCUSSION PURPOSE :
**Query 1**:
```
SELECT `user_id`, MAX(`score`) as max_score
FROM `scores`
GROUP BY `user_id`
```
**[Results](http://sqlfiddle.com/#!2/1b5efe/7/0)**:
```
| USER_ID | MAX_SCORE |
|---------|-----------|
| 9 | 610 |
| 10 | 290 |
| 11 | 210 |
| 12 | 170 |
``` | Selecting Rows Based on Max Column in Group By | [
"",
"mysql",
"sql",
""
] |
I have this code in my select statement
```
ISNULL(a.PolicySignedDateTime,aq.Amount) AS 'Signed Premium',
```
But I want to see if "a.PolicySignedDateTime" is not null.
Is there a easy function to do this which does not involve using a "if" statement?
Cheers guys | You have to use `CASE`
```
SELECT CASE WHEN Field IS NOT NULL
THEN 'something'
ELSE 'something else'
END
``` | I know is late but just in case someone else viewing this and using MSSQL 2012 or above you could use 'IIF' statement.
I guess OP don't want to use 'IF' clausule cause is "too much code syntax" to acomplish simple stuff.
An alternative also cleaner than 'IF' statement is 'IIF'. Is just an inline 'IF' simplification.
```
SELECT IIF(X IS NULL, 'Is null', 'Not null') 'Column Name'
```
Regarding OP
```
SELECT IIF(a.PolicySignedDateTime IS NULL, NULL, aq.Amount) AS 'Signed Premium'
```
<https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-iif-transact-sql?view=sql-server-ver15> | Is there a opposite function to ISNULL in sql server? To do Is not null? | [
"",
"sql",
"sql-server",
"isnull",
""
] |
Is there a value or command like DATETIME that I can use in a manual query to insert the current date and time?
```
INSERT INTO servers (
server_name, online_status, exchange, disk_space, network_shares
) VALUES(
'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE' 'DATETIME'
)
```
The quoted DATETIME value at the end is where I want to add the current date and time. | You can use `NOW()`:
```
INSERT INTO servers (server_name, online_status, exchange, disk_space, network_shares, c_time)
VALUES('m1', 'ONLINE', 'exchange', 'disk_space', 'network_shares', NOW())
``` | Use **CURRENT\_TIMESTAMP()** or **now()**
Like
```
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUES('m1','ONLINE','ONLINE','100GB','ONLINE',now() )
```
or
```
INSERT INTO servers (server_name, online_status, exchange, disk_space,
network_shares,date_time) VALUES('m1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE'
,CURRENT_TIMESTAMP() )
```
Replace date\_time with the column name you want to use to insert the time. | How to get current date & time in MySQL? | [
"",
"mysql",
"sql",
"datetime",
""
] |
I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
```
where datetime_column > DATEADD(m, -6, current_timestamp)
```
But how to extend this option if I want to return latest month beginning with first day of the month? E.g. I run this condition in the middle of month `(14/6/2000)`, the latest row is set to `14/1/2000`, but i would like to return it as `1/1/2000`. Any advice?
I tried some subqueries (max function of datetime including month function) but with no success. | For MS SQL Server, you can use:
```
where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)
``` | ## In SQL Server
```
where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)
```
### [SQLFiddle demo](http://sqlfiddle.com/#!3/d41d8/22330)
## In MySQL
```
where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month
```
### [SQLFiddle demo](http://sqlfiddle.com/#!2/d41d8/22117) | SQL Last 6 Months | [
"",
"sql",
"sql-server",
""
] |
I want a query that returns the number of sequential match of words in two strings
example:
Table
```
Id column1 column2 result
1 'foo bar live' 'foo bar' 2
2 'foo live tele' 'foo tele' 1
3 'bar foo live' 'foo bar live' 0
```
to get total number of occurrence I am using:
```
select id, column1,column2,
extractvalue(dbms_xmlgen.getxmltype('select cardinality (
sys.dbms_debug_vc2coll(''' || replace(lower(column1), ' ', ''',''' ) || ''') multiset intersect
sys.dbms_debug_vc2coll('''||replace(lower(column2), ' ', ''',''' )||''')) x from dual'), '//text()') cnt
from table.
```
Can anyone please suggest a query on similar lines for sequential match also as I want number of sequential matches and number of occurrences shown together. | Personally, in this situation, I would choose PL/SQL code over plain SQL. Something like:
Package specification:
```
create or replace package PKG is
function NumOfSeqWords(
p_str1 in varchar2,
p_str2 in varchar2
) return number;
end;
```
Package body:
```
create or replace package body PKG is
function NumOfSeqWords(
p_str1 in varchar2,
p_str2 in varchar2
) return number
is
l_str1 varchar2(4000) := p_str1;
l_str2 varchar2(4000) := p_str2;
l_res number default 0;
l_del_pos1 number;
l_del_pos2 number;
l_word1 varchar2(1000);
l_word2 varchar2(1000);
begin
loop
l_del_pos1 := instr(l_str1, ' ');
l_del_pos2 := instr(l_str2, ' ');
case l_del_pos1
when 0
then l_word1 := l_str1;
l_str1 := '';
else l_word1 := substr(l_str1, 1, l_del_pos1 - 1);
end case;
case l_del_pos2
when 0
then l_word2 := l_str2;
l_str2 := '';
else l_word2 := substr(l_str2, 1, l_del_pos2 - 1);
end case;
exit when (l_word1 <> l_word2) or
((l_word1 is null) or (l_word2 is null));
l_res := l_res + 1;
l_str1 := substr(l_str1, l_del_pos1 + 1);
l_str2 := substr(l_str2, l_del_pos2 + 1);
end loop;
return l_res;
end;
end;
```
Test case:
```
with t1(Id1, col1, col2) as(
select 1, 'foo bar live' ,'foo bar' from dual union all
select 2, 'foo live tele' ,'foo tele' from dual union all
select 3, 'bar foo live' ,'foo bar live'from dual
)
select id1
, col1
, col2
, pkg.NumOfSeqWords(col1, col2) as res
from t1
;
```
Result:
```
ID1 COL1 COL2 RES
---------- ------------- ------------ ----------
1 foo bar live foo bar 2
2 foo live tele foo tele 1
3 bar foo live foo bar live 0
``` | Why to give up on the query approach. I know it's a bit complicated and I hope someone can work on it to improve it, but working on this during my spare time I was able to survive a an afternoon of calls...
Here on [SQLFidlle](http://sqlfiddle.com/#!4/2c047/61)
```
SELECT Table1.id,
Table1.column1,
Table1.column2,
max(nvl(t.l,0)) RESULT
FROM (
SELECT id,
column1,
column2,
LEVEL l,
decode(LEVEL,
1,
substr(column1, 1, instr(column1,' ', 1, LEVEL) -1),
substr(column1, 1, (instr(column1,' ', 1, LEVEL )))
) sub1,
decode(LEVEL,
1,
substr(column2, 1, instr(column2,' ', 1, LEVEL) -1),
substr(column2, 1, (instr(column2,' ', 1, LEVEL )))
) sub2
FROM (SELECT id,
column1 || ' ' column1,
column2 || ' ' column2
FROM Table1)
WHERE decode(LEVEL,
1,
substr(column1, 1, instr(column1,' ', 1, LEVEL) -1),
substr(column1, 1, (instr(column1,' ', 1, LEVEL )))
) =
decode(LEVEL,
1,
substr(column2, 1, instr(column2,' ', 1, LEVEL) -1),
substr(column2, 1, (instr(column2,' ', 1, LEVEL )))
)
START WITH column1 IS NOT NULL
CONNECT BY instr(column1,' ', 1, LEVEL) > 0
) t
RIGHT OUTER JOIN Table1 ON trim(t.column1) = Table1.column1
AND trim(t.column2) = Table1.column2
AND t.id = Table1.id
GROUP BY Table1.id,
Table1.column1,
Table1.column2
ORDER BY max(nvl(t.l,0)) DESC
``` | Count sequential matching words in two strings oracle | [
"",
"sql",
"oracle",
"stored-procedures",
""
] |
I've written the below query :
```
SELECT DateTime, configId, rowId
FROM linkedTableDefinition a,
INNER JOIN tableDefinition b,
ON a.Target = b.Id
INNER JOIN ViewWithInfo c,
ON a.Target = c.Id
```
This gives the following output:
```
DateTime configId rowId
12-09-2013 11:00 4 12
12-09-2013 12:00 4 12
12-09-2013 13:00 3 11
12-09-2013 12:00 3 11
12-09-2013 11:00 4 11
```
What I need of this output is the following: per rowId and configId combination I need the highest value from the datetime column. So from above example I want the following output:
```
DateTime configId rowId
12-09-2013 12:00 4 12
12-09-2013 13:00 3 11
12-09-2013 11:00 4 11
```
Does anyone know the answer? I would like to avoid GROUP BY because the select statement will be extended with a lot more columns.
Thanks in advance
**EDIT**
The current query:
```
SELECT testResults.ResultDate, testResults.ConfigurationId, TestResultsTestCaseId
FROM dbo.FactWorkItemLinkHistory workItemLink
INNER JOIN dbo.DimWorkItem workItem
ON workItem.System_Id = workItemLink.TargetWorkItemID
INNER JOIN dbo.TestResultView testResults
ON testResults.TestCaseId = workItemLink.TargetWorkItemID
WHERE
RemovedDate = convert(datetime, '9999-01-01 00:00:00.000')
AND workItemLink.SourceWorkItemID = 7
AND workItem.System_WorkItemType = 'Test Case'
``` | ```
SELECT *
FROM
(
SELECT DateTime, configId, rowId,
ROW_NUMBER() OVER(PARTITION BY configId, rowId ORDER BY DateTime DESC) AS RowNum
FROM linkedTableDefinition a
INNER JOIN tableDefinition b ON a.Target = b.Id
INNER JOIN ViewWithInfo c ON a.Target = c.Id
) src
WHERE src.RowNum = 1
``` | You could do this, substituting proper joining fields as appropriate:
```
SELECT testResults.ResultDate, testResults.ConfigurationId, testResults.TestCaseId,
(SELECT MAX(ResultDate) FROM dbo.TestResultView WHERE TestCaseId = testResults.TestCaseId AND ConfigurationId = testResults.ConfigurationId) AS MaxDate
FROM dbo.FactWorkItemLinkHistory workItemLink
INNER JOIN dbo.DimWorkItem workItem
ON workItem.System_Id = workItemLink.TargetWorkItemID AND workItemLink.TeamProjectCollectionSK = workItem.TeamProjectCollectionSK
INNER JOIN dbo.TestResultView testResults
ON testResults.TestCaseId = workItemLink.TargetWorkItemID
WHERE
RemovedDate = convert(datetime, '9999-01-01 00:00:00.000')
AND workItemLink.SourceWorkItemID = 7
AND workItem.System_WorkItemType = 'Test Case'
AND workItem.System_RevisedDate = convert(datetime, '9999-01-01 00:00:00.000')
``` | SQL max(DateTime) and category filter without group by | [
"",
"sql",
"sql-server",
""
] |
I have the following SQL code in a stored procedure:
```
CREATE PROCEDURE sp_createAColDiffTable (@table_name nvarchar(128))
AS
CREATE TABLE @table_name (
[table_name] VARCHAR (128) NOT NULL,
[column_name] VARCHAR (128) NULL,
[what_changed] VARCHAR (128) NULL,
[sr_data_type] VARCHAR (128) NOT NULL,
[tr_data_type] VARCHAR (128) NOT NULL,
[sr_max_length] SMALLINT NOT NULL,
[tr_max_length] SMALLINT NOT NULL,
[sr_is_nullable] CHAR NULL,
[tr_is_nullable] CHAR NULL,
[sr_precision] SMALLINT NULL,
[tr_precision] SMALLINT NULL,
[sr_scale] SMALLINT NULL,
[tr_scale] SMALLINT NULL )
ON [PRIMARY]
WITH (DATA_COMPRESSION = NONE)
```
I call the stored procedure like this:
```
EXEC [sp_createAColDiffTable] 'hq193.dbo.arch_con_col_s193_s202'
```
When I run the code I get the error:
> Incorrect syntax near '@table\_name'.
When I substitute the actual table name for `@table_name` it works fine.
Can someone point out the problem with my syntax? | You would need to use dynamic SQL for this, as `CREATE TABLE` doesn't take a variable name.
e.g.
```
CREATE PROCEDURE sp_createAColDiffTable (@table_name nvarchar(128))
AS
DECLARE @sql nvarchar(MAX)
SET @sql = 'CREATE TABLE ' + @table_name + ' (
[table_name] VARCHAR (128) NOT NULL,
[column_name] VARCHAR (128) NULL,
[what_changed] VARCHAR (128) NULL,
[sr_data_type] VARCHAR (128) NOT NULL,
[tr_data_type] VARCHAR (128) NOT NULL,
[sr_max_length] SMALLINT NOT NULL,
[tr_max_length] SMALLINT NOT NULL,
[sr_is_nullable] CHAR NULL,
[tr_is_nullable] CHAR NULL,
[sr_precision] SMALLINT NULL,
[tr_precision] SMALLINT NULL,
[sr_scale] SMALLINT NULL,
[tr_scale] SMALLINT NULL )
ON [PRIMARY] WITH (DATA_COMPRESSION = NONE)';
EXEC(@sql);
```
Be aware that using dynamic SQL can lead to SQL injection though, so make sure you never pass any user input to `@table_name`. | `@table_name` is used when declaring table variables, whereas `table_name` or `#table_name` or `##table_name` is used to create tables/temp tables.
So you would have
```
DECLARE @table TABLE (
ID INT,
....
```
and
```
CREATE TABLE #table_name (
ID INT,
....
```
If you wish to create a table dynamically, you would have to use dynamic sql for that.
For declaring a table variable have a look at [DECLARE @local\_variable (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms188927.aspx)
For creating tables/temp tables have a look at [CREATE TABLE (Transact-SQL)](http://technet.microsoft.com/en-us/library/ms174979.aspx)
Further to that, also have a look at [The Curse and Blessings of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html) | using parameter values in stored procedures | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am working in SQL Server 2012. My date column in a data set looks like this: `41547`. The column is in `nvarchar (255)`. I want to convert it to something like this: `yyyy-mm-dd hh:mm:ss` (Example: `2013-09-14 12:23:23.98933090`). But I can not do this. I am using following code:
```
select convert(datetime, date_column, 6)
```
But this is giving following error:
```
Msg 241, Level 16, State 1, Line 1 Conversion failed when converting
date and/or time from character string.
```
What am I doing wrong? | I have just found the way to do this.
First I have to covert the nvarchar to int then I have to convert it to date time. I have used following code:
```
Select convert(datetime, (convert (int, [date_column])), 6) as 'convertedDateTime' from mytable
``` | Your date is actually a numeric value (float or integer), stored in a char column. So, you need to convert it to a numerical value (in this case, to `float`) first, like:
```
select convert(datetime, CONVERT(float,date_column))
```
A value of `41547.5` will result in:
```
`2013-10-02 12:00:00`
```
The style argument, in your case `6` is only necessary when converting from or to char-types. In this case it is not needed and will be ignored.
---
NB: The float value is the number of days since `1900-01-01`.
e.g. `select convert(datetime, CONVERT(float,9.0))` => `1900-01-10 00:00:00`; the same as `select dateadd(day,9.0,'1900-01-01')` would.
The decimal part of the number also equates to days; so `0.5` is half a day / 12 hours.
e.g. `select convert(datetime, CONVERT(float,.5))` => `1900-01-01 12:00:00`. (Here our comparison to dateadd doesn't make sense, since that only deals with integers rather than floats). | Converting a numeric value to date time | [
"",
"sql",
"sql-server",
"date",
"sql-server-2012",
"type-conversion",
""
] |
I currently have the following results:
```
ID Location
1 NYC
1 LA
2 NYC
3 PIT
```
and I'd like the following:
```
ID Location
1 Multiple
2 NYC
3 PIT
```
Does anyone know an easy way to accomplish this? | Here's one way to do it using `case` with `count` and `distinct`:
```
select distinct id,
case when count(location) over (partition by id ) > 1
then 'Multiple' else location end Location
from yourtable
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/bdc51/1) | With `sub-query`, `COUNT`, `CASE`, `GROUP BY`:
```
SELECT mm.id, CASE WHEN mm.count > 1 THEN 'Multiple' ELSE loc END As Location
FROM
(SELECT COUNT(id) As count, id, MAX(location) As loc
FROM myTable
GROUP BY id) As mm;
```
[**SQL Fiddle**](http://sqlfiddle.com/#!3/63c6a/14) | Select From Table with Multiple Rows for some ID's, with an identifier value | [
"",
"sql",
"sql-server",
""
] |
How can i query a column with `Names` of people to get only the names those contain **exactly 2** `“a”` ?
I am familiar with `%` symbol that's used with `LIKE` but that finds all names even with 1 `a` , when i write `%a` , but i need to find only those have **exactly** 2 characters.
Please explain - Thanks in advance
> Table Name: "People"
>
> Column Names: "Names, Age, Gender" | Use `'_a'`. `'_'` is a single character wildcard where `'%'` matches 0 or more characters.
If you need more advanced matches, use regular expressions, using `REGEXP_LIKE`. See [Using Regular Expressions With Oracle Database](http://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_re.htm).
And of course you can use other tricks as well. For instance, you can compare the length of the string with the length of the same string but with 'a's removed from it. If the difference is 2 then the string contained two 'a's. But as you can see things get ugly real soon, since length returns 'null' when a string is empty, so you have to make an exception for that, if you want to check for names that are exactly 'aa'.
```
select * from People
where
length(Names) - 2 = nvl(length(replace(Names, 'a', '')), 0)
``` | Assuming you're asking for two `a` characters search for a string with two a's but not with three.
```
select *
from people
where names like '%a%a%'
and name not like '%a%a%a%'
``` | Matching exactly 2 characters in string - SQL | [
"",
"sql",
"oracle",
""
] |
This sql is valid:
```
WITH A AS
(SELECT TOP 1000 *
FROM dbo.SomeTable)
SELECT * FROM A
```
While this one gives an error(*Incorrect syntax near the keyword 'DECLARE'*):
```
WITH A AS
(SELECT TOP 1000 *
FROM dbo.SomeTable)
DECLARE @dt DATETIME
SET @dt = GETDATE()
SELECT * FROM A
PRINT DATEDIFF(SS,GETDATE(),@dt)
```
Why? | Just do
```
DECLARE @dt DATETIME;
SET @dt = GETDATE();
WITH A
AS (SELECT TOP 1000 *
FROM dbo.SomeTable)
SELECT *
FROM A;
PRINT DATEDIFF(SS, GETDATE(), @dt);
```
The only valid thing following a CTE definition is a single statement using it | A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view.
<http://msdn.microsoft.com/en-us/library/ms175972.aspx> | Cant define SQL variable when using WITH statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
"common-table-expression",
""
] |
Is it posible to use *case* in *where in* clause?
Something like this:
```
DECLARE @Status VARCHAR(50);
SET @Status='published';
SELECT * FROM Product P
WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3)
WHEN @Status='standby' THEN (2,5,9,6)
WHEN @Status='deleted' THEN (4,5,8,10)
ELSE (1,3)
END)
```
This code gives the error : *Incorrect syntax near ','.* | No you can't use `case` and `in` like this. But you can do
```
SELECT * FROM Product P
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
```
BTW you can reduce that to
```
SELECT * FROM Product P
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)
```
since `or P.Status IN (1,3)` gives you also all records of `@Status='published' and P.Status IN (1,3)` | I realize this has been answered, but there is a slight issue with the accepted solution. It will return false positives. Easy to fix:
```
SELECT * FROM Products P
WHERE (@Status='published' and P.Status IN (1,3))
or (@Status='standby' and P.Status IN (2,5,9,6))
or (@Status='deleted' and P.Status IN (4,5,8,10))
or (@Status not in ('published','standby','deleted') and P.Status IN (1,2))
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!3/9aef0/8)
Parentheses aren't needed (although perhaps easier to read hence why I included them). | SQL use CASE statement in WHERE IN clause | [
"",
"sql",
"select",
"switch-statement",
"case",
"where-in",
""
] |
I have a problem when I need range from 10 to 20 (LIMIT 10, 20) it is returns everything from 1 to 20. I don't have any idea why it's works so.
Here is a query:
```
SELECT *
FROM table
LIMIT 10, 20
```
This table has 5 foreign keys, can it be a reason? | The limit syntax is `LIMIT offset, rowcount`. So you're asking for 20 rows, starting with the 10th. You probably want `LIMIT 10, 10`. | The limit command works as follows:
<http://php.about.com/od/mysqlcommands/g/Limit_sql.htm>
Your query should be:
`SELECT *
FROM table
LIMIT 10,10`
the first number indicates which record to start from, and the second indicates the amount of records to limit to. | LIMIT does not work correctly | [
"",
"mysql",
"sql",
"limit",
""
] |
It's Tuesday today.
How come when I run this SQL statement, it says it's not Tuesday?
```
SELECT
CASE
WHEN TO_CHAR(sysdate, 'Day') = 'Tuesday' THEN 'Its Tuesday'
ELSE 'Its Not Tuesday'
END AS case_result,
TO_CHAR(sysdate, 'Day') AS day
FROM DUAL
```
Returns:
```
CASE_RESULT DAY
It's Not Tuesday Tuesday
``` | Try like this,
```
SELECT CASE
WHEN trim(TO_CHAR(SYSDATE, 'Day')) = 'Tuesday' THEN 'Its Tuesday'
ELSE 'Its Not Tuesday'
END AS case_result,
TO_CHAR(SYSDATE, 'Day') AS DAY
FROM DUAL;
```
OR as ajmalmhd04 suggested, you can try with `FmDay` like,
```
SELECT CASE
WHEN TO_CHAR(SYSDATE, 'FmDay') = 'Tuesday' THEN 'Its Tuesday'
ELSE 'Its Not Tuesday'
END AS case_result,
TO_CHAR(SYSDATE, 'Day') AS DAY
FROM DUAL;
``` | The value of to\_char(sysdate,'day') is actually 'tuesday ', with two space after tuesday. Oracle pads the value to the length of the longest day, which is wednesday, which is nine characters.
try
```
RTRIM(to_char(sysdate,'day'))
``` | Oracle - get day of week | [
"",
"sql",
"oracle",
""
] |
Hi I have a query that i want to return one value. If i run the query in two parts and add them together it is fine but when i try and the OR operator the value greatly increases.
Here is the first query:
```
select count (*) from tablename where DATE_TRE='2013-10-06' and SECTOR= '1'
```
This returns 3867
Here is the second:
```
select count (*) from tablename where DATE_TRE='2013-10-06' and SECTOR= '01'
```
This returns 9
When i run it using a Or like this
```
select count (*) from tablename where DATE_TRE='2013-10-06' and SECTOR= '1' OR SECTOR = '01'
```
I get the value of 4066, anyone any ideas im wanting the figure of 3876 | I think it because it evaluates it like this
```
select count (*)
from tablename
where (DATE_TRE='2013-10-06' and SECTOR= '1') OR SECTOR = '01'
```
When you are looking for this(Try this one)
```
select count (*)
from tablename
where DATE_TRE='2013-10-06' and (SECTOR= '1' OR SECTOR = '01')
``` | `and` binds stronger than `or`. use parentheses
```
select count (*)
from tablename
where DATE_TRE = '2013-10-06'
and (SECTOR= '1' OR SECTOR = '01')
```
or
```
select count (*)
from tablename
where DATE_TRE = '2013-10-06'
and SECTOR in ('1', '01')
``` | Using Count and OR giving too high a value | [
"",
"sql",
"count",
"sybase",
""
] |
Hi im working on a query to get 1row for each product but the problem is that there are multiple records with propertys of 1 product.
**TABLE PRODUCTS\_DATA**
```
NAME : DESC. | ID|FIELD1|FIELD2|FIELD3|FIELD4|
Row 1:PRODUCT1 | 1 | 200 | high | | |
Row 2:PRODUCT1 | 2 | 10 | | low | |
Row 3:PRODUCT1 | 3 | | | | 10 |
```
now i would like the get a query which displays only one record with all those properties.
Row 1: `PRODUCT1|200|10|HIGH|LOW|10`
because
```
row 1 | id1 | field 1 contains length data
row 2 | id2 | field 1 contains amount data
```
how in the world is is possible to get an result like this? | I think you will get your solution now dear...
```
SELECT
SS.[DESC],
(SELECT '|' + US.FIELD1
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD1],
(SELECT '|' + US.FIELD2
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD2],
(SELECT '|' + US.FIELD3
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD3],
(SELECT '|' + US.FIELD4
FROM XYZ US
WHERE US.[DESC] = SS.[DESC]
FOR XML PATH('')) [FIELD4]
FROM XYZ SS
GROUP BY SS.[DESC]
ORDER BY 1
``` | You need to be careful about the semantics of the two "field1" columns. You are showing both coming out in your example result. Presumably you could end up with data in each of the four fields for each row and therefore a very variable length result with duplicate column names, which seems broken to me. (Or you need to fix whatever is inserting the data to use a real primary key!) | sql query to get multiple records in one row | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
```
SELECT dbo.Team.ID, dbo.Team.Comment, dbo.Team.Date, dbo.TeamName.Name, dbo.Contacts.ContactName
FROM dbo.Team
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID
WHERE dbo.TeamName.idstatus = 'Active'
```
I am trying to query it in a way that it only gives me records with most recent date but it is getting little confusing because I am already pulling data from 3 tables and not sure how to use `MAX(date)` here. | ```
SELECT dbo.Team.ID, dbo.Team.Comment, MAX(dbo.Team.Date) LatestDate, dbo.TeamName.Name, dbo.Contacts.ContactName
FROM dbo.Team
INNER JOIN dbo.TeamName ON dbo.Team.ID = dbo.TeamName.id
INNER JOIN dbo.Contacts ON dbo.Team.ContactID = dbo.Contacts.ContactID
WHERE dbo.TeamName.idstatus = 'Active'
GROUP BY dbo.Team.ID, dbo.Team.Comment, dbo.TeamName.Name, dbo.Contacts.ContactName
```
ADDING MAX() Function to your date column and group by all the columns with you the Latest date for the combination of values in all other columns. | I'm assuming you want to filter by `dbo.Team.Date`.
Change your `WHERE` clause to:
```
WHERE (dbo.TeamName.idstatus = 'Active')
and (dbo.Team.Date=(select max(Date) from dbo.Team))
``` | Select Most Recent date | [
"",
"sql",
"sql-server",
""
] |
I am having an issue writing an SQL Update statement, where I need to update a not null field with an empty string.
```
UPDATE channel_mgmt.channels
SET registered_address_id=p_address_id
,vendor_id=p_spc_code
WHERE id=v_channel_id;
```
In this case, p\_spc\_code, can be set to '', and I am running into a SQL error when I run this:
```
Error report:
ORA-01407: cannot update ("CHANNEL_MGMT"."CHANNELS"."VENDOR_ID") to NULL
ORA-06512: at line 8973
01407. 00000 - "cannot update (%s) to NULL"
*Cause:
*Action:
```
Any ideas how I can get around this? I need to use the empty string some cases, but I am unsure why oracle is complaining about a null value.
```
desc channel_mgmt.channels
Name Null Type
--------------------- -------- ------------------
ID NOT NULL NUMBER(16)
CHANNEL_STATUS_KEY NOT NULL VARCHAR2(64 CHAR)
REGISTERED_ADDRESS_ID NOT NULL NUMBER(16)
VENDOR_ID NOT NULL VARCHAR2(64 CHAR)
``` | Have you tried using `' '` (string with one space in it)? If varchar, than I believe comparisons (for most cases, i.e. you're not specifying to compare white chars) work as expected.
What I mean that `' ' = ' '` (single and double whitespace) should evaluate to `true` for `varchar` fields.
(I don't have an instance of Oracle so I can't be sure...) | If there is a `NOT NULL` constraint defined on a column you cannot update the table by specifying `null` or zero length string(`''`) as a new value for a column. Oracle treats zero length string(`''` when assigned to a `varchar2` column or variable) as `NULL`, so from the *oracle's point of view*, these two statements are the same `set col_name = null` and `set col_name = ''`. If you want to allow for a column to accept `NULL`s you need to remove not null constraint from that column if it won do any harm:
```
alter table <<table_name>> modify (<<column_name>> [<<data type>>] null)
``` | Oracle SQL Updating a NOT NULL column with an empty string | [
"",
"sql",
"oracle",
""
] |
I need to create a SQL script to determine if a sequence exists in a SQL Server 2012 database. I am familiar with process for determine if a stored procedure exist but not sequence. Thank you. | The script to determine whether or not a Sequence exists in SQL Server 2012 is very similar to checking for Stored Procedures. Consider the following code that checks to see if a Stored Procedure exists:
```
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[SProc_Name]') AND type IN (N'P', N'PC')
```
The values of 'P' and 'PC' for the type specify the type of the sys.object is a SQL Stored Procedure or a Assembly (CLR) stored-procedure. To check for a sequence, you just need to change it to 'SO' which indicates it is a Sequence Object:
```
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Sequence_Name]') AND type = 'SO'
```
For example, if you want to create a Sequence if it doesn't exist, you could use the following code:
```
IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sequence_Name]') AND type = 'SO')
CREATE SEQUENCE [dbo].[Sequence_Name]
AS [bigint]
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 3
GO
```
I hope this helps! | By checking data in [sys.sequences](http://technet.microsoft.com/ru-ru/library/ff877934.aspx) table:
```
select *
from sys.sequences
where object_id = object_id('schema_name.sequence_name')
```
actually that if you're sure that there's no object other than sequence with name equals `'schema_name.sequence_name'`, you could just check `object_id('schema_name.sequence_name') is not null`
**`sql fiddle demo`** | How can I determine if a Sequence exist in SQL Server 2012? | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have the data in table EMP\_DETAILS
```
EMPLOYEE_NUMBER ROLE
NSA5421 CONTRACTOR
NSA390 CONTRACTOR
E8923 EMPLOYEE
E2390 EMPLOYEE
```
I would like to have zero displayed even there are no records, I tried the following but it didn't get the desired result
```
SELECT CASE WHEN cnt IS NULL THEN 0 ELSE cnt END cnt,
CASE WHEN role IS NULL THEN '0' ELSE role END role
FROM
(SELECT COUNT (*) cnt, role
FROM emp_details
WHERE employee_number = 'E3400'
GROUP BY role)
``` | Please try:
```
select
NVL(y."ROLE", '0') "ROLE",
case when y."ROLE" is null then 0 else COUNT(*) end cnt
from(
SELECT 'E3400' employee_number from dual
)x left join emp_details y on x.employee_number=y.employee_number
group by "ROLE"
``` | Your inner query is returning nothing rather than null values.
```
SELECT COUNT (*) cnt, role
FROM emp_details
WHERE employee_number = 'E3400'
GROUP BY role
```
Use EXISTS clause | Fetch zero if even there are no matching records | [
"",
"sql",
"oracle",
"oracle10g",
""
] |
We have one 'master' table and three other tables with some kind of details like below.
```
+----------+
| TAB_A |
+----------+
*|PK ID_A |
+----------+ / |FK ID_MAIN|
|TableMain |/ | DATA_A |
------------ ============
|PK ID_MAIN| +----------+
| Main_data|--*| TAB_B |
| | +----------+
============ |PK ID_B |
| |FK ID_MAIN|
| | DATA_B |
* ============
+-----------+
| TAB_C |
+-----------+
| PK ID_C |
| FK ID_MAIN|
| DATA_C |
=============
```
Example values:
```
TableMain:
ID_MAIN Main_data
1 main1
2 main2
3 main3
TAB_A | TAB_B | TAB_C
ID_A ID_MAIN DATA_A | ID_B ID_MAIN DATA_B | ID_C ID_MAIN DATA_C
1 2 A2 | 1 1 B3 | 1 3 C3
2 1 A1 | 2 1 B3_1 |
3 1 A1_1
4 3 A3
5 1 A1_2
```
and I want all details from TAB\_A,TAB\_B and TAB\_C for each rekord from TableMain.
The output should look like that
```
ID_MAIN | Main_data | DATA_A | DATA_B | DATA_C |
-------------------------------------------------
1 | main1 | | B3 | |
| main1 | | B3_1 | |
2 | main2 | A2 | | |
3 | main3 | A3 | | C3 |
``` | Since you want to put values from different tables on the same row, you need to relate them to one another somehow. In the absence of an actual relationship, you probably have to make one up. One suggestion would be to assign row numbers per `ID_MAIN` in the three subordinate tables and use those numbers for matching.
If you are on SQL Server 2005 or later version, you could add row numbers using the [`ROW_NUMBER`](http://msdn.microsoft.com/en-us/library/ms186734.aspx "ROW_NUMBER (Transact-SQL)") analytic function, and the entire query might look like this:
```
WITH A_ranked AS (
SELECT *, ROW_NUM = ROW_NUMBER() OVER (PARTITION BY ID_MAIN ORDER BY ID_A)
FROM TAB_A
),
B_ranked AS (
SELECT *, ROW_NUM = ROW_NUMBER() OVER (PARTITION BY ID_MAIN ORDER BY ID_B)
FROM TAB_B
),
C_ranked AS (
SELECT *, ROW_NUM = ROW_NUMBER() OVER (PARTITION BY ID_MAIN ORDER BY ID_C)
FROM TAB_C
)
SELECT
ID_MAIN = COALESCE(a.ID_MAIN, b.ID_MAIN, c.ID_MAIN),
m.Main_data,
ROW_NUM = COALESCE(a.ROW_NUM, b.ROW_NUM, c.ROW_NUM),
a.DATA_A,
b.DATA_B,
c.DATA_C
FROM
A_ranked AS a
FULL JOIN
B_ranked AS b ON b.ID_MAIN = a.ID_MAIN
AND b.ROW_NUM = a.ROW_NUM
FULL JOIN
C_ranked AS c ON c.ID_MAIN = COALESCE(a.ID_MAIN, b.ID_MAIN)
AND c.ROW_NUM = COALESCE(a.ROW_NUM, b.ROW_NUM)
RIGHT JOIN
TableMain AS m ON m.ID_MAIN = COALESCE(a.ID_MAIN, b.ID_MAIN, c.ID_MAIN)
;
```
You can take a look at a live demonstration of this query [at SQL Fiddle](http://sqlfiddle.com/#!3/2d687/1). | Hi Please try this hope this helps you thanks
```
SELECT dbo.TableMail.ID_MAIN, dbo.TableMail.Main_Data,
CASE WHEN DATA_A IS NULL THEN '' ELSE DATA_A END AS DATA_A,
CASE WHEN DATA_B IS NULL THEN '' ELSE DATA_B END AS DATA_B,
CASE WHEN DATA_C IS NULL THEN '' ELSE DATA_C END AS DATA_C
FROM dbo.TableMail LEFT OUTER JOIN
dbo.Table_C ON dbo.TableMain.ID_MAIN = dbo.Table_C.ID_MAIN LEFT OUTER JOIN
dbo.Table_A ON dbo.TableMain.ID_MAIN = dbo.Table_A.ID_MAIN LEFT OUTER JOIN
dbo.Table_B ON dbo.TableMain.ID_MAIN = dbo.Table_B.ID_MAIN
GROUP BY dbo.TableMain.ID_MAIN, dbo.TableMain.Main_Data, CASE WHEN DATA_A IS NULL THEN '' ELSE DATA_A END, CASE WHEN DATA_B IS NULL
THEN '' ELSE DATA_B END, CASE WHEN DATA_C IS NULL THEN '' ELSE DATA_C END
``` | How can I merge three tables by id from 4th table? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Here is the database description:
> Company(ID\_comp, name)
>
> Trip(trip\_no, id\_comp, plane, town\_from, town\_to, time\_out, time\_in)
>
> Passenger(ID\_psg, name)
>
> Pass\_in\_trip(trip\_no, date, ID\_psg, place)
* Company table has ID and name of the company, which transports passengers.
* Trip table has information about trips: trip number, company ID, plane type, departure city, arrival city, departure time, and arrival time.
* The passenger table has passenger's ID and passenger's name.
* Pass\_in\_trip table has information about the flights: trip number, departure date (day), passenger's ID and his place during the flight.
We should note that,
* Any trip is being accomplished every day; duration of a flight is less than a calendar-day (24 hours);
* Time and date are considered comparatively one time zone;
* The departure time and the arrival time are given to within a minute;
* There can be the passengers bearing the same names (for example, Bruce Willis);
* The place during the flight is a number followed by a letter; the number defines the row number, the letter (a - d) – the place in the row (from the left to the right) in the alphabetical order;
* Relationships and restrictions are shown in the data schema.
Here is the Question:
Find the names of the different passengers, which flew more than once in the same seat.
I've tried this query
```
select name from (
select id_psg, count(name) as total from (
select a.id_psg, name, date,place from passenger a join
pass_in_trip b on a.id_psg=b.id_psg order by a.id_psg, place
) as t1
group by t1.id_psg
) as a join passenger b on a.id_psg = b.id_psg
join pass_in_trip c on a.id_psg=c.id_psg
where total > 1
group by name,place
having count(place) >=2
order by name,place;
```
But it says:
```
Wrong
Your query produced correct result set on main database, but it failed test on second, checking database
* Wrong number of records (more by 8)
```
* This is an exercise from [SQL-RU](http://sql-ex.ru/) btw. | ```
SELECT
p.name
FROM
passenger AS p
JOIN
pass_in_trip AS pt
ON p.id_psg = pt.id_psg
GROUP BY
p.id_psg, p.pame
HAVING
COUNT(DISTINCT pt.place) < COUNT(*) ;
``` | ```
select name, place, COUNT(name)as "no of trips"
from Passenger p
join Pass_in_trip pt
on p.ID_psg=pt.ID_psg join Trip t
on pt.trip_no=t.trip_no
group by name, place
having count(name) > 1
``` | Tricky SQL Exercise | [
"",
"sql",
"postgresql",
"subquery",
""
] |
Is there any concept in mysql to localize the Date time function. I need Date time to be in Ethiopian format. Or atleast a mysql conversion function that displays datetime with respect to Ethiopian Date time. | No, you can not. In MySQL, [proleptic Gregorian calendar](http://dev.mysql.com/doc/refman/5.0/en/mysql-calendar.html) is used - and there are no other formats. That means there are no *native* ways to produce such conversions.
However, you can create your own output conversion. To do this, you will need to know both calendars. There are good [on-line convertors](http://www.gebeya.net/dateconverter.aspx) which you can use to get some examples. So you will store your dates in Gregorian (i.e. MySQL internal) format, but convert them in your application like you need. | MySQL does not a conversion function for ethiopic calendar.
The most straightforward approach would be to create a date table that contains gregorian date on one column and ethiopian on the next, allowing you to easily join it on a standard date to get your ethiopian date. | Does Mysql support Ethiopian calendar/ Ethiopian date time | [
"",
"mysql",
"sql",
""
] |
I have a sql query that joins a few tables by `user_id`, the problem is is that I would like to see all the data from these tables.
At the moment I am querying the user table and the payment table and joining them based on the `user_id`.
I seem to only getting one result per user\_id, now I know this it what is meant to happen but how (if possible), would I be able to show all the data from the payment table (ie I want to see multiple user ids that show the various payments that user has made).
I am currently using a left join, I'm thinking this may be the issue but switching it still isn't showing the results I am looking for.
This i my current join:
```
from user u
left join u_subscription us
on u.user_id = us.user_id
left join u_detail ud
on u.user_id = ud.user_id
```
Any help would be hugely appreciated.
Thanks in advance
Nad
Full sql query:
```
select u.user_id as 'prop:User id', u.user_username as 'prop:username', u.user_email as 'Identity',u.user_created as 'Timestamp', us.user_subscription_expires as 'prop:Expires on', us.user_subscription_payment_provider as 'prop:Payment provider', us.user_subscription_modified, ud.user_detail_signup_country_iso3 as 'prop:Country'
from user u
left outer join user_subscription us
on u.user_id = us.user_subscription_user_id
left outer join user_detail ud
on u.user_id = ud.user_detail_user_id
``` | I find no flaws in your query. It should be working as expected.
I'm suspecting there is no more than one row *per user* in the `subscription` and `detail` tables. That's why your `left join` produces exactly one row per user (if it was an inner join, it would produce *at most* one row per user). | I suggest using another method:
```
select
'your selected columns'
from
user u,
u_subscription us,
u_detail ud
where
u.user_id = us.user_id and
u.user_id = ud.user_id
```
this works just like the join method but for me, this method makes the query cleaner and easier to understand.. hope it helped! | Having SQL Query not group results | [
"",
"mysql",
"sql",
"join",
""
] |
Please check fiddle: [myFiddle](http://sqlfiddle.com/#!3/184dc/1)
Query:
```
create table Emp(empId int primary key, EmpName varchar(50),MngrID int)
insert into Emp(empId,EmpName,MngrID)values(1,'A',2)
insert into Emp(empId,EmpName,MngrID)values(2,'B',null)
```
A has mngr B but A has no mngr, so while fetching the record from query it shows me:
```
EmpId EmpName MngrName(alias MngrName)
1 A B
2 B null
```
How to fetch the above data using a query? | For some reason it doesn't work in SQLFiddle, but i ran it in my own instance of SQL Server to verify it does work:
```
SELECT e1.EmpID, e1.EmpName, e2.EmpName
FROM emp e1 LEFT OUTER JOIN emp e2
ON e1.MngrID = e2.EmpID
```
Basically, you're doing a 'self join' by declaring two instances of the table (e1 and e2), and then joining the first instance's MngrID to the second instance's EmpID. | You need to LEFT JOIN table to itself:
```
select A.empID, A.empName, b.empName as mgrName
from emp A left join emp B on A.mngrID = b.empID
```
<http://sqlfiddle.com/#!3/184dc/8> | SQL Server fetch alias name for query | [
"",
"sql",
"sql-server-2008",
""
] |
I'm trying to show rows in which one field occurs a certain number of times. Assuming the following table: `Campaign`
```
+------------+-------------+--------------+---------------+
| account_id | campaign_id | account_name | account_users |
+------------+-------------+--------------+---------------+
| 85 | 21 | A | 36 |
| 45 | 69 | B | 82 |
| 78 | 78 | C | 28 |
| 69 | 65 | D | 25 |
| 85 | 87 | E | 96 |
| 78 | 12 | F | 63 |
| 78 | 78 | G | 96 |
+------------+-------------+--------------+---------------+
```
And the table `Account`
```
+------------+--------------+
| account_id | account_code |
+------------+--------------+
| 85 | AAA |
| 45 | ABC |
| 78 | RTY |
| 69 | WER |
| 85 | AAA |
| 78 | RTY |
| 78 | RTY |
+------------+--------------+
```
I need to show all `Campaign` table columns with (`join`) `account_code` from the table `account` for only those accounts that have `account_id` occurs two or more times at the table `campaign`. Therefore, the result should be:
```
+------------+-------------+--------------+---------------+--------------+
| account_id | campaign_id | account_name | account_users | account_code |
+------------+-------------+--------------+---------------+--------------+
| 85 | 21 | A | 36 | AAA |
| 78 | 78 | C | 28 | RTY |
| 85 | 87 | E | 96 | AAA |
| 78 | 12 | F | 63 | RTY |
| 78 | 78 | G | 96 | RTY |
+------------+-------------+--------------+---------------+--------------+
```
I tried to use `GROUP BY` and `HAVING` clause but it seems not working:
```
SELECT c.account_id ,c.campaign_id ,c.account_name ,c.account_users ,a.account_code
FROM campaign c
INNER JOIN account a
GROUP BY c.account_id, c.campaign_id, c.account_name, c.account_users, a.account_code
HAVING count(*) >= 2;
```
Am I missing something here? | Give this a try:
```
SELECT DISTINCT c.*, a.account_code FROM campaign c
JOIN account a ON c.account_id = a.account_id
WHERE c.account_id IN (
SELECT account_id FROM campaign
GROUP BY account_id
HAVING count(*) >= 2
)
``` | You are using COUNT as aggregate function. Try using it as analytical function.
```
select account_id ,campaign_id ,account_name ,account_users ,account_code,
from
(SELECT c.account_id ,c.campaign_id ,c.account_name ,c.account_users ,a.account_code,
count(1) over (partition by c.account_id) as c
FROM campaign c
INNER JOIN account a on c.account_id = a.account_id)
where c >= 2;
``` | Show rows that have values occur a certain number of times | [
"",
"sql",
"oracle",
""
] |
I am updating the table with values from multiple tables.
```
UPDATE pv SET
pv.[TotalDInTCG] = Dr.TCGDCnt
,pv.[AvgHbA1cImprovement] = hsd.AvgHbA1cCnt
,pv.[TotalCHDInTCG] = cpc.CHdCnt
,pv.[TotalCHDNTCG] = cpd1.CHdWithCholBPCnt
,pv.[PercentageOfCHDWithBPChol] = icp.CHFElligPopul
,pv.[TotalCOPDInTCG] = copd.TcgCOPDcount
,pv.[TotalCOPDMRCPOxySatuLevel] = copdmrc.TotalCOLevel
,pv.[PercentOferTCG] = copdOxSatu.oxySatligPopu
FROM #tmpeTabel AS pv
INNER JOIN #DRegistered AS Dr
ON Dr.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND Dr.Years = pv.[ReportYear]
AND Dr.Months = pv.[ReportMonth]
INNER JOIN #HbA1cScoreDetails AS hsd
ON hsd.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND hsd.Years = pv.[ReportYear]
AND hsd.Months = pv.[ReportMonth]
INNER JOIN #CHDCount as cpc
ON cpc.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND cpc.Years = pv.[ReportYear]
AND cpc.Months = pv.[ReportMonth]
INNER JOIN #CHDBPCholPatientsDetails as cpd1
ON cpd1.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND cpd1.Years = pv.[ReportYear]
AND cpd1.Months = pv.[ReportMonth]
INNER JOIN #ImprovementCHFPerPractice as icp
ON icp.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND icp.Years = pv.[ReportYear]
AND icp.Months = pv.[ReportMonth]
INNER JOIN #COPDCount as copd
ON copd.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copd.Years = pv.[ReportYear]
AND copd.Months = pv.[ReportMonth]
INNER JOIN #COPDDetailsMRCOxygenSatuLevel as copdmrc
ON copdmrc.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copdmrc.Years = pv.[ReportYear]
AND copdmrc.Months = pv.[ReportMonth]
INNER JOIN #ImprovPerElligPopula as copdOxSatu
ON copdOxSatu.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copdOxSatu.Years = pv.[ReportYear]
AND copdOxSatu.Months = pv.[ReportMonth]
```
The issue here is , some tables have many rows and some have less rows. But i am getting the less rows for all every table after update
Should i use update separably for each select table.. | Assuming that the columns you are updating in `pv` are all nullable this should ensure you capture all the relevant data:
```
UPDATE pv SET
pv.[TotalDInTCG] = Dr.TCGDCnt
,pv.[AvgHbA1cImprovement] = hsd.AvgHbA1cCnt
,pv.[TotalCHDInTCG] = cpc.CHdCnt
,pv.[TotalCHDNTCG] = cpd1.CHdWithCholBPCnt
,pv.[PercentageOfCHDWithBPChol] = icp.CHFElligPopul
,pv.[TotalCOPDInTCG] = copd.TcgCOPDcount
,pv.[TotalCOPDMRCPOxySatuLevel] = copdmrc.TotalCOLevel
,pv.[PercentOferTCG] = copdOxSatu.oxySatligPopu
FROM #tmpeTabel AS pv
LEFT JOIN #DRegistered AS Dr
ON Dr.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND Dr.Years = pv.[ReportYear]
AND Dr.Months = pv.[ReportMonth]
LEFT JOIN #HbA1cScoreDetails AS hsd
ON hsd.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND hsd.Years = pv.[ReportYear]
AND hsd.Months = pv.[ReportMonth]
LEFT JOIN #CHDCount as cpc
ON cpc.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND cpc.Years = pv.[ReportYear]
AND cpc.Months = pv.[ReportMonth]
LEFT JOIN #CHDBPCholPatientsDetails as cpd1
ON cpd1.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND cpd1.Years = pv.[ReportYear]
AND cpd1.Months = pv.[ReportMonth]
LEFT JOIN #ImprovementCHFPerPractice as icp
ON icp.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND icp.Years = pv.[ReportYear]
AND icp.Months = pv.[ReportMonth]
LEFT JOIN #COPDCount as copd
ON copd.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copd.Years = pv.[ReportYear]
AND copd.Months = pv.[ReportMonth]
LEFT JOIN #COPDDetailsMRCOxygenSatuLevel as copdmrc
ON copdmrc.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copdmrc.Years = pv.[ReportYear]
AND copdmrc.Months = pv.[ReportMonth]
LEFT JOIN #ImprovPerElligPopula as copdOxSatu
ON copdOxSatu.SK_ServiceProviderID = pv.SK_ServiceProviderID
AND copdOxSatu.Years = pv.[ReportYear]
AND copdOxSatu.Months = pv.[ReportMonth]
``` | Left outer join worked.. The main issue was due to normal behavior of INNER JOIN | Update table by selecting values from multiple tables sql | [
"",
"sql",
""
] |
I need to calculate the averages of a couple of columns which range from 0 to 5. However I want to exclude the zero's from the AVG calculation.
So I have something like
```
SELECT AVG(column1), AVG(column2), AVG(column3) FROM table1
WHERE ???
``` | AVG() only counts records that are non-null.
NULLIF() will return null, when the value matches the 2nd parameter.
```
SELECT AVG(NULLIF(column1,0)), AVG(NULLIF(column2,0)), AVG(NULLIF(column3,0)) FROM table
WHERE ????
```
You could create a more complex AVG() by using IF(column1 IN (x,y,z), column1, NULL) within.
NOTE: If your column's data is a REAL or FLOAT, then you should ROUND() or TRUNCATE() your value within the NULLIF(). EX:
```
AVG( NULLIF( ROUND(column1,3), 0.000 )) AS column1
```
-- JJ -- | You can do something like this, where you sum the colummn and divide by the count of rows where the value is not equal to zero:
```
SELECT SUM(Column1) / SUM (IF(Column1 = 0, 0, 1)),
SUM(Column2) / SUM (IF(Column2 = 0, 0, 1)),
SUM(Column3) / SUM (IF(Column3 = 0, 0, 1))
FROM table1
```
Not you will also have to trap divide by zero in the denominator (which i haven't done above)... | Aggregate queries remove zeros | [
"",
"mysql",
"sql",
"average",
""
] |
I have following DB structure:

I wanted it in single column like:
```
Param
-
-
AccountNo
AccountNo DueDate
```
For this i written case when query:
```
select
case when Param1 <>'' then 'Param1'+Param1
+case when Param2 <>'' then 'Param2'+Param2
+case when Param3 <>'' then 'Param3'+Param3
+case when Param4 <>'' then 'Param4'+Param4
+case when Param5 <>'' then 'Param5'+Param5
end
end
end
end
end
'param'
from IVR_PPMaster
```
But this query is returning me all NULL values.
Please help me to obtain result. | If you indent it some you get (I've kept the first only the first three params)
```
select case when Param1 <>''
then 'Param1'+Param1 + case when Param2 <>''
then 'Param2'+Param2 +case when Param3 <>''
then 'Param3'+Param3
end
end
end
as 'param'
from IVR_PPMaster
```
It's obvious that if `Param1` is empty, this code will return NULL, since that is what `case` returns if none of the conditions are met.
Basically this code will only return a string if none of the params are empty. You'll need non-nested cases to get the correct result
```
select case when Param1 <>'' then 'Param1'+Param1
else '' -- this is needed because adding a null to a string yields null
end
+ case when Param2 <>'' then 'Param2'+Param2
else ''
end
+ case when Param3 <>'' then 'Param3'+Param3
else ''
end
as 'param'
from IVR_PPMaster
``` | You can use `NullIf()` function with `IsNull()/Coalesce()` like below:
```
Select coalesce(nullif(param1,''),'') + coalesce(nullif(param2,''),'') + ... +
coalesce(nullif(param5,''),'') newColName
From yourTable
```
For *your case* just a null check like below may be enough:
```
Select coalesce(param1,'') + coalesce(param2 + ' ','') + ... +
coalesce(param5 + ' ','') newColName
From yourTable
``` | case when blank check returning null | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I have a query, that should return all records in T1 that not linked to records in T2:
```
SELECT DISTINCT fldID, fldValue FROM T1
WHERE NOT EXISTS
(
SELECT T1.fldID, T1.fldValue
FROM T2
JOIN T1 ON T2.fldID = T1.fldPtr
)
```
But it returns empty set -- should be one record.
If I use query like this (clause on one field):
```
SELECT DISTINCT fldID FROM T1
WHERE fldID NOT IN
(
SELECT T1.fldID
FROM T2
JOIN T1 ON T2.fldID = T1.fldPtr
)
```
It returns correct result.
But the SQL Server do not support syntax
```
WHERE ( fldID, flrValue ) NOT IN ....
```
Help me please to figure out how to compose query that will check several columns?
Thanks! | You can also use [`EXCEPT`](http://technet.microsoft.com/en-us/library/ms188055.aspx) for this:
```
SELECT DISTINCT fldID, fldValue FROM T1
EXCEPT
SELECT T1.fldID, T1.fldValue
FROM T2
JOIN T1 ON T2.fldID = T1.fldPtr
``` | A more efficient and elegant query that will work with every database is:
```
SELECT T1.*
FROM T1
LEFT JOIN T2
ON T2.fldID = T1.fldPtr
AND T2.flrValue = T1.flrValue
WHERE T2.fldID IS NULL
```
The LEFT JOIN attempts to match using both criteria, then the WHERE clause filters the joins, and only non-joins have NULL values for the LEFT JOINed table.
This approach is IMHO pretty much the industry standard for finding non-matches. It is usually more efficient than a NOT EXIstS(), although several databases optimize a NOT EXISTS() to this query anyway. | WHERE + NOT EXIST + 2 Columns | [
"",
"sql",
"sql-server",
""
] |
```
492953BI -2284424
492953BI -2014941
492953BI -1916038
492953BI -1908036
```
I need to split the first coloumn (ID) into two coloumns. (ie. Have the numbers in first coloumn, and BI in the second.) Am battling to do this on SQL Server. Am also new to SQL so battling to work with older questions, thank you | Using `Left()` and `Right()` functions:
```
--If the number part is always 6 digits
Select left(yourColumn,6) Col1, right(yourColumn,2) Col2
From yourTable
--For any number of front digits (bit more generic)
Select left(yourCol, charIndex('B',yourCol)-1) Col1,
right(yourCol, len(yourCol) - charIndex('B',yourCol)+ 1) Col2
From yourTable
``` | ```
select substring(col1, 1, 6) as new_col1,
substring(col1, 7, 2) as new_col2
from your_table
``` | Remove values that net each other out to zero, leaving only one positive 2472320 in this case | [
"",
"sql",
"sql-server-2008",
""
] |
Which Oracle SQL-technique is possible to use for concatenate this rows:
```
id | from | to
--------------
a | 20 | 25
a | 26 | 30
a | 32 | 40
b | 1 | 5
b | 7 | 10
b | 11 | 20
```
for such result:
```
a | 20 | 30
a | 32 | 40
b | 1 | 5
b | 7 | 20
```
? Assumed that `from` and `to` is start and end of an integer period, and necessary to choose an non-breaking periods for `id`'s
Just looking for right direction and example, can this be done using `group by` or `connect by` or something else?
DB is `Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production` | Maybe something similar:
```
select
field_id,
min(field_from),
max(field_to)
from (
select
field_from,
field_to,
field_id,
sum(willSum) over(partition by field_id order by field_from) as GID
from (
select
field_from,
field_to,
field_id,
case when field_from
= Lag(field_to) over(partition by field_id order by field_from)
then 0 else 1 end as willSum + 1
from
rj_mytest
)
)
group by
field_id,
GID
order by
field_id,
min(field_from);
```
There are a few similar example: <https://forums.oracle.com/thread/969005> | Another approach, which uses `model` clause to assign a group number to a consecutive pairs of values:
```
select id1
, min(from1) as from1
, max(to1) as to1
from (select *
from t1
model
partition by (id1)
dimension by (row_number() over(partition by id1 order by from1) as rn)
measures(from1, to1, 1 as grp)
rules(
grp[rn] = case
when from1[cv()] = nvl(to1[cv()-1] + 1, from1[cv()])
then nvl(grp[cv() - 1], 1)
else grp[cv() - 1] + 1
end
)
)
group by id1
, grp
order by id1
, from1
```
Result:
```
ID1 FROM1 TO1
--- ---------- ----------
a 20 30
a 32 40
b 1 5
b 7 20
```
[**SQLFiddle Demo**](http://www.sqlfiddle.com/#!4/89f87/1) | Group by calculating the non-breaking periods from two (from and to) values | [
"",
"sql",
"oracle",
"oracle11g",
"group-by",
"connect-by",
""
] |
Lets assume I have 2 tables:
```
Order -< OrderItem
```
I have another table with 2 FKs:
```
Feature
- Id
- FkOrderId
- FkOrderItemId
- Text
```
UPDATE
---
This table is linked to another called FeatureReason which is common to both types of record, be they OrderFeatures or OrderItem features.
Feature -< FeatureReason
If I had 2 feature tables to account for both types of records, would this then require 2 FeatureReason tables. Same issue here with the FeatureReason table needing to have 2 FKs, each pointing to a different master table.
---
An Order can have a Feature record, as can an OrderItem. Therefore either "FkOrderId" OR FkOrderItemId would be populated. Is this fine to do?
I would also seriously think about using Views to to insert/edit and read either OrderFeatures or OrderItemFeatures.
Thoughts appreciated. | I would recommend using following structure, because if you have 2 foreign keys which either of them can be null, you can have rows with both columns being null or having value.
Added the FeatureReason table too
 | You can do this, but why? What is your reasoning for collating these two distinct items in a single table?
I would suggest having two separate tables, `OrderFeatures` and `OrderItemFeatures`, and on those occasions that you need to query both, collate them with a `union` query. | Is it OK to have 2 FKs on a table, which point to different tables, and one of which will only be used? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have the following code:
```
select O.ONO
from Customers C, Odetails Od, Orders O, Parts P
where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
group by O.ONO
order by sum(Od.QTY*P.PRICE)desc;
```
However, instead of selecting the `O.ONO` column, I need to select the `C.CNAME` from a different table. How would I go about doing that? | If what you want is a list of Customer Names ordered by the sum of their orders then just change your query from
```
select O.ONO
...
group by O.ONO
```
to
```
select C.CName
...
group by C.CName
```
This will display the customer name and the order number. NOTE: This will repeat the customer name as many times as there are orders for that customer
Also, my preferred style of SQL queries is
```
select C.CName
from Customers C
INNER JOIN Orders O ON C.CNO = O.CNO
INNER JOIN Odetails OD ON O.ONO = OD.ONO
INNER JOIN Parts P ON OID.PNO = P.PNO
where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
group by C.CName
order by sum(Od.QTY*P.PRICE)desc;
```
An additional suggestion to clarify your code. *(please note: I'm not an oracle person)*, in my company (SqlServer) generally you would have the table named after the entity, with the primary key being just `Id`, and then any property named without a prefix. For instance does `OID` refer to `OrderId` or `OfficeId`?
**EG:**
Customer:
* Id
* Name
Order:
* Id
* CustomerId
Then your queries are much more readable:
```
SELECT Name
FROM Customer
INNER JOIN Order ON Customer.Id = Order.CustomerId
WHERE ...
ORDER BY Customer.Name
``` | Please do like this,
```
select C.CNAME from Customers C, Odetails Od, Orders O, Parts P where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO group by C.CNAME order by sum(Od.QTY*P.PRICE) desc;
``` | SQL: How to display a column not in group by expression? | [
"",
"sql",
"oracle",
""
] |
I am trying to pick the top 1 result from a select statement inside the set statement of an Update. I can pick the top 1 but the order by clause does not work. Is there a way to make it work or a workaround please?
```
UPDATE a1
SET a1.ServiceLength = ( SELECT TOP 1
a3.START_DATE
ORDER BY a3.START_DATE DESC
)
FROM #t a1
JOIN #TempService a2 ON a1.EmployeeNo = a2.EMPLOYEE_NO
JOIN #TempService a3 ON a3.EMPLOYEE_NO = a2.Employee_No
WHERE a2.START_DATE = a3.END_DATE + 1
AND @specifiedDate > a2.START_DATE
``` | Try to do this using a CTE:
```
WITH TopDate
AS
(
SELECT TOP 1 a3.START_DATE, a3.employee_no
FROM #t a1
JOIN #tempservice a2 ON a1.employeeno = a2.employee_no
JOIN #tempservice a3 ON a3.employee_no = a2.employee_no
WHERE a2.start_date = a3.end_date + 1
AND @specifiedDate > a2.start_date
ORDER BY a3.START_DATE DESC
)
UPDATE a1
SET a1.ServiceLength = t.START_DATE
FROM #t a1
INNER JOIN TopDate AS t ON a1.employeeno = t.employee_no
``` | You can use MAX(START\_DATE) to get the latest START\_DATE for each employee
```
update A set A.ServiceLength= (select MAX(B.Start_Date) from #tbl1 B where B.EmployeeNo=A.EmployeeNo)
from #tbl1 A
```
Please add necessary where clause for your query. | Order by clause within the Set of an Update Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to read tutorials and find question on syntax on sql subqueries for a specific purpose but I can't seem to find the right choice of words to describe my problem.
Table - Part Descriptions
```
+------------+------------+------------+
| ID | Part # | Type |
+------------+------------+------------+
| 1 | 123 | 1 |
| 2 | 456 | 2 |
| 3 | 123 | 3 |
| 4 | 789 | 4 |
| 5 | 123 | 4 |
| 6 | 789 | 2 |
| 7 | 123 | 2 |
+------------+------------+------------+
```
I basically need to find any part number that has the Type Value of both '2' and '4', not one or the other.
I feel like it should be incredibly simple, but I can't seem to get correct results | You can use a combination of WHERE, GROUP BY and a HAVING clause to get the result. The key in the HAVING clause is to count the distinct items that are included in your WHERE filter:
```
select [part #]
from partDescriptions
where type in (2, 4)
group by [part #]
having count(distinct type) = 2;
```
See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/15a29/1)
If you want to return only the parts that have just type 2 and 4 nothing else, then you could expand on this:
```
select PartNum
from yourtable
where type in (2, 4)
and partnum not in (select partnum
from yourtable
where type not in (2, 4))
group by PartNum
having count(distinct type) = 2
```
See [Demo](http://sqlfiddle.com/#!3/15a29/2) | ```
SELECT *
FROM PartDesciption P
WHERE EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 2) AND
EXISTS (SELECT * FROM PartDesciption WHERE ID = P.ID AND Type = 4)
``` | Sql - How to search for distinct rows that have two specific variables | [
"",
"sql",
"sql-server",
""
] |

This query gives all the templateId that are assigned to product id less than 5 and that's the expected output. But we wanted to achieve that without using the sub query in the where clause (Highlighted in red).
If I just remove the subquery then the output will be all the templateId from templateproduct table. we don't wnat that. what we want is the template id that's only assigned from product 1 to 5. so our expected output is:
100
102
today we are acheiving this using additional subquery, we wanted to acheive the same result without using the subquery.
we are using sql 2008 | You can do this using a LEFT JOIN in place of a subquery, and check for NULL.
```
SELECT DISTINCT tp.template_id
FROM templateproduct tp
LEFT JOIN templateproduct tp2
ON tp.template_id = tp2.template_id AND tp2.prod_id IN (6, 7, 8, 9, 10)
WHERE tp.prod_id < 5
AND tp2.template_id IS NULL
```
You can do a similar thing using GROUP BY and check that there are 0 matching templates linking to the excluded product ids:
```
SELECT tp.template_id
FROM templateproduct tp
LEFT JOIN templateproduct tp2
ON tp.template_id = tp2.template_id AND tp2.prod_id IN (6, 7, 8, 9, 10)
WHERE tp.prod_id < 5
GROUP BY tp.template_id
HAVING COUNT(tp2.template_id) = 0
```
Depending on your data and indexing, this may or may not be more efficient than a subquery - I suggest you try it out. In any event, there is no reason to have any INNER JOINs at all to get the results you are seeking:
```
SELECT DISTINCT tp.template_id
FROM templateproduct tp
WHERE tp.prod_id < 5
AND tp.template_id NOT IN (
SELECT tp2.template_id FROM templateproduct tp2 WHERE tp2.prod_id IN (6, 7, 8, 9, 10)
)
```
Try these out and see which performs better for you. And of course, check the query plan to see why this is. | It's because your where clause should be **tp.prod\_id <= 5** | SQL Query Assistnace | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table in mysql like this
```
CREATE TABLE IF NOT EXISTS `connections` (
`src` int(10) unsigned NOT NULL,
`sport` smallint(5) unsigned NOT NULL,
`dst` int(10) unsigned NOT NULL,
`dport` smallint(5) unsigned NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`src`,`sport`,`dst`,`dport`,`time`),
KEY `time` (`time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
2.5 million records daily inserted in this table.
When i want to select records for a period of time like a day. it takes about 7 minutes.
how can i improve it.
i`m using ruby on rails version 4.0.0
My selection is like this
```
connections = Connection.select('src, dst, UNIX_TIMESTAMP(time) as time')
.where(time: timeFrom..timeTo)
.order('time ASC')
```
After selection from database i have a loop like this :
```
connections.each do |con|
link = getServerID(con['src'])
link = getServerID(con['dst']) if link == 0
@total[link].append [con['time'] * 1000, con['dst']]
end
```
in this loop i have a bit process on src and dst then i add it to a hash
this sections takes along and my computer crashed | First of all you should try to run the SQL query directly against the database without Rails. This helps to identify the bottleneck: Is the query itself slow or is rails slow? I guess the SQL part should not be a problem, but double check that first.
I guess your biggest problem lies in `connections.each`. This loads all matching rows into your application and creates `ActiveRecord` models of it. Let's do some math: `2.5M entries * 1KB` (just guessing, probably more) would result in `2.5GB` of data loaded into your memory. You may see an improvement in using `connection.find_each` instead, because it loads the connections in smaller batches.
What does `getServerID` method do? It is called `5M` times.
I am pretty sure that you will not be able to improve this code that much. Seems like the wrong database for the problem or a bad algorithm. Since it is unlikely that you want to display `2.5M` records on a website, it is a better idea to tell us what you want to achieve. | As already mentioned, fetching 2.5 mio entries requires loads of memory / cpu power. Try fetching the records in batches.
Rails has batch support build-in: <http://api.rubyonrails.org/classes/ActiveRecord/Batches.html>
```
connections.find_each do |con|
link = getServerID(con['src'])
link = getServerID(con['dst']) if link == 0
@total[link].append [con['time'] * 1000, con['dst']]
end
```
If that's not solving your problem, you should consider finding a better way to not loop through such an amount of records each time. | How to handle millions of records daily with mysql | [
"",
"mysql",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have an Access 2010 database which stores IP addresses of source and destination machines. If I have the following entries in my database
```
|source | destination|
|--------------------------------|
| A | B |
| B | A |
| A | B |
| C | D |
| D | D |
```
Is there any query to select unique pairs? That is, the output of the query should be
```
|source | destination|
|----------------------------------|
| A | B |
| C | D |
``` | Your question seems to imply two things:
1. When listing source/destination pairs you only want to see the pairs in one direction, e.g., (A,B) but not (B,A).
2. The list should omit pairs where the source and destnation are the same, e.g., (D,D)
In that case the query...
```
SELECT DISTINCT source, destination
FROM
(
SELECT source, destination
FROM SomeTable
UNION ALL
SELECT destination, source
FROM SomeTable
)
WHERE source < destination
```
...when run against [SomeTable] containing...
```
source destination
------ -----------
A B
B A
A B
C D
D D
E D
```
...will produce:
```
source destination
------ -----------
A B
C D
D E
``` | select unique source, destination from YourTable
or
select distinct source, destination from YourTable
or
select source, destination from YourTable
group by source, destination | selecting distinct pairs of values in SQL | [
"",
"sql",
"ms-access",
"ms-access-2010",
""
] |
I have problem in query. I use posgresql. I need to get total row but with condition "group by"
```
table qwe
----------------------------
TIPE | VAL
----------------------------
1 | 2
2 | 3
2 | 1
2 | 4
3 | 1
3 | 3
```
the result I need is
```
-------------------------
TIPE | VAL | TOTAL TIPE
-------------------------
1 | 2 | 3
2 | 8 | 3
3 | 4 | 3
```
the query I've tried so far
```
select tipe, sum(val), count(tipe) "total tipe"
from qwe group by tipe order by tipe
-------------------------
TIPE | VAL | TOTAL TIPE
-------------------------
1 | 2 | 1
2 | 8 | 3
3 | 4 | 2
``` | you can try this one:
```
select
tipe, sum(val), count(tipe) over() as "total tipe"
from qwe
group by tipe
order by tipe
```
**`sql fiddle demo`**
You see, instead of counting number of not-null `tipe` records inside each group, you can count number of not null tipe over the whole resultset - that's why you need `over()` clause. It's called [window functions](http://www.postgresql.org/docs/current/static/tutorial-window.html). | That's a strange request, however, I would suggest that you build a view that returns just the count(tipe) of the table and then join that view in? I haven't tested that but I am pretty sure that it would work. | Total row with condition "group By" | [
"",
"sql",
"postgresql",
""
] |
I have tables as follows:
**muscles**
```
id primary_synonym_id source
---------- ------------------ ----------
1 1 1
2 2 2
3 3 3
```
**muscle\_synonyms**
```
id synonym
---------- ---------------
1 Gluteus maximus
2 Soleus
3 Infraspinatus
```
**sources** *(As you can probably tell, `sources` is intended as a link table.)*
```
id type sub_id
---------- ---------- ----------
1 url 1
2 url 2
3 book 1
```
**source\_urls**
```
id url
---------- ------------------
1 http://v.gd/3NCOMC
2 http://v.gd/fWdonY
```
**source\_books**
```
id isbn
---------- ----------
1 1405006692
```
From the above, which query would you recommend, to generate the following output?
```
id synonym ref
---------- --------------- ------------------
1 Gluteus maximus http://v.gd/3NCOMC
2 Soleus http://v.gd/fWdonY
3 Infraspinatus 1405006692
```
Please mention worthwhile alternatives - if any - to such a query, that you think would promote good database practice. (For example, a different way to structure the data and the use of a simpler query.) | I was unfamiliar with the `coalesce()` function. The following query was inspired by [this](https://stackoverflow.com/a/14988043/82216), and it works:
```
select muscles.id, synonym, coalesce(url, isbn) as ref
from muscles
join muscle_synonyms on muscles.primary_synonym_id = muscle_synonyms.id
join sources on muscles.source = sources.id
left join source_urls on
sources.type = 'url' and
sources.sub_id = source_urls.id
left join source_books on
sources.type = 'book' and
sources.sub_id = source_books.id
where ref not null;
``` | i dont exactly understand what is sub\_id in sources and how its linked to source\_books
sql will almost looks like this
```
select m.id,ms.synonym,su.url from muscles m
join muscle_synonym ms on ms.id=m.primary_synonym_id
join sources s on s.id=m.source
join source_url su on s.sub_id=su.id
``` | Join in SQLite with per-row selection of join table based on value in link table | [
"",
"sql",
"sqlite",
"relational-database",
""
] |
I'm trying to write a small script to create a database if it doesn't exist, and create a table for that database if the table doesn't exist. What I have is this:
```
IF (db_id('db') is null) BEGIN
print 'Must create the database!';
CREATE DATABASE db;
END
USE db;
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
```
I'm getting a strange error with this:
```
Database 'db' does not exist. Make sure that the name is entered correctly.
```
I'm guessing that it's parsing the script before running it and finding that 'db' doesn't exist, so it can't use it.
There must be a solution to this. Any help is appreciated.
**SOLVED!**
I realised 5 minutes after posting that the GO keyword solves the problem. Here is the fixed code:
```
IF (db_id('db') is null) BEGIN
print 'Must create the database!'
CREATE DATABASE db;
END
GO
USE db
IF (object_id('test_table', 'U') is null) BEGIN
print 'Must create the table!';
CREATE TABLE test_table (
id int
);
END
```
Sorry for wasting everyone's time. | SQL statements are parsed as one batch unless you break them apart. In SQL Server, you can use GO to do this. In both MySQL and SQL Server, you can use BEGIN and END.
If you want to commit the separate blocks to the database in different instances you can use BEGIN TRANS / COMMIT TRANS and START TRANSACTION / COMMIT for SQL Server and MySQL, respectively. | Something along the lines of [Check if table exists in SQL Server](https://stackoverflow.com/questions/167576/sql-server-check-if-table-exists) would probably work (With a slight change)
```
IF (NOT EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
``` | Create Database and Table Conditionally | [
"",
"sql",
"sql-server",
""
] |
I have a query like
```
select id, item, producer from table
```
The result is like this:
```
id item producer
1 apple A
2 pear A
3 peach A
4 orange B
5 strawberry B
6 melon B
```
I want to shuffle this result (order by id DESC) and get something like this
```
item producer
strawberry B
pear A
orange B
apple A
peach A
melon B
```
I DON'T want to display like this:
ALL A ITEM
ALL B ITEM
ALL C ITEM... | Use the rand function in ORDER BY like this:
```
select id, item, producer from table order by rand();
``` | To Shuffle the selection you can use **rand()**
The Answer for the link below contains more information.
```
SELECT id, item, producer
FROM table
ORDER BY RAND()
```
[MySQL: Shuffle a limited query result?](https://stackoverflow.com/questions/4534195/mysql-shuffle-a-limited-query-result) | SQL Query group shuffle | [
"",
"mysql",
"sql",
""
] |
I have three tables that share one field with another table, so:
```
Employee_Data: EMP_ID, PHONE_EXTENSION
Outage_Data: DATE, EMP_ID
Phone_Data: DATE, PHONE_EXTENSION
```
I need to combine data where the agent data is matched with data in the other two tables. Basically, I need to combine the data from `Outage_data` and `Phone_data` (because it is all grouped by date) with `Employee_Data` as the "bridge".
I already have my SELECT and everything laid out like it needs to be; I just need help with the join.
*EDIT*
By Request, here is the full query. I tried not to do this for simplicity's sake:
```
With Epi AS
(SELECT EMP_ID, PHONE_EXTENSION, Name, Manager, EWFMDeptname, Location From Employee_Data)
,
Shrink AS
(SELECT DATE, EMP_ID, START_MOMENT, STOP_MOMENT, SEG_CODE FROM Outage_Data)
,
OutIn AS
(SELECT date, logid, login, logout From PHONE_DATA)
SELECT
ISNULL(Shrink.DATE,OutIn.DATE) AS RowDate,
ISNULL(Epi.EMP_ID,RTRIM(LTRIM(Shrink.EMP_ID))) AS Badge,
ISNULL(Epi.PHONE_EXTENSION, OutIn.logid) AS [ACD/Extension],
Epi.Name,
Epi.Manager,
Epi.EWFMDeptName,
Epi.Location,
ISNULL(Shrink.START_MOMENT, (SELECT Shrink.START_MOMENT FROM Shrink WHERE SHRINK.SEG_CODE = 'SHIFT' AND Shrink.EMP_ID = EPI.EMP_ID AND SHRINK.DATE = OutIn.DATE)) AS ShiftStart,
ISNULL(Shrink.STOP_MOMENT, (SELECT Shrink.STOP_MOMENT FROM Shrink WHERE SHRINK.SEG_CODE = 'SHIFT' AND Shrink.EMP_ID = EPI.EMP_ID AND SHRINK.DATE = OutIn.row_date)) AS ShiftStop,
OutIn.login AS Login,
OutIn.logout AS Logout,
Shrink.SEG_CODE AS OUTSEG,
IIF(Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH', Shrink.START_MOMENT, NUll) AS OutStart,
IIF(Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH', Shrink.STOP_MOMENT, NUll) AS OutStop,
IIF(DateADD(minute, 5, Shrink.START_MOMENT) < OutIn.Login, CONVERT(decimal(10,2), DATEDIFF(second ,Shrink.START_MOMENT,OutIn.Login)/60.0) ,0.00) AS Late,
ISNULL(IIF(Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0) = NULL OR Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0) > 0.00, 0.00, ABS(Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0))), 0.00) AS [Left],
IIF(OutIn.login IS NULL AND Shrink.SEG_CODE = 'SHIFT' ,DATEDIFF(minute,Shrink.START_MOMENT, Shrink.STOP_MOMENT), 0.00) AS NCNS
FROM (Epi Right JOIN Shrink on Epi.EMP_ID = Shrink.EMP_ID) INNER JOIN OutIn ON (Shrink.DATE = OutIn.DATE) JOIN (
WHERE Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH' or Shrink.SEG_CODE = 'SHIFT'
ORDER BY Badge;
```
Sorry its kind of messy. Again, Thank you
*EDIT2*
Per request, here is some of my data:
Shrink:
```
EMP_SK EMP_ID EMP_LAST_NAME EMP_FIRST_NAME EMP_SORT_NAME EMP_SHORT_NAME EMP_SENIORITY EMP_EFF_HIRE_DATE NOM_DATE SEG_CODE START_MOMENT STOP_MOMENT
-9.88181E+11 73485 BLAH BLAH BLAH BLAH 20130812000 8/12/2013 0:00:00 10/6/2013 0:00:00 SHIFT 10/6/2013 12:00:00 10/6/2013 21:00:00
-9.88181E+11 73485 BLAH BLAH BLAH BLAH 20130812000 8/12/2013 0:00:00 10/7/2013 0:00:00 SHIFT 10/7/2013 12:00:00 10/7/2013 21:00:00
-9.88768E+11 192329 BLAH BLAH BLAH BLAH 20130715000 7/15/2013 0:00:00 10/7/2013 0:00:00 SHIFT 10/7/2013 6:00:00 10/7/2013 15:00:00
-9.88741E+11 224579 BLAH BLAH BLAH BLAH 20091214000 12/14/2009 0:00:00 10/7/2013 0:00:00 SHIFT 10/7/2013 8:00:00 10/7/2013 17:00:00
-9.88741E+11 224579 BLAH BLAH BLAH BLAH 20091214000 12/14/2009 0:00:00 10/8/2013 0:00:00 SHIFT 10/8/2013 8:00:00 10/8/2013 17:00:00
-9.88181E+11 73485 BLAH BLAH BLAH BLAH 20130812000 8/12/2013 0:00:00 10/8/2013 0:00:00 SHIFT 10/8/2013 12:00:00 10/8/2013 21:00:00
-9.88768E+11 192329 BLAH BLAH BLAH BLAH 20130715000 7/15/2013 0:00:00 10/8/2013 0:00:00 SHIFT 10/8/2013 6:00:00 10/8/2013 15:00:00
```
Epi:
```
Badge Name NT Login Email MBadge Manager Vendor Business Unit Business Unit Desc Sub-Support Name Segment Location Subqueue Phone Queue Title EWFMDeptCode EWFMDeptName EWFMTeamCode EWFMTeamName ACD/Extension Switch Name DomsID DomsID2 DomsID3 Tech-ID (DPS) Tech-ID2 (DPS2) KanaUserID NetAgentID Part_Time Alias Miscellaneous Hiredate Cost Center Jack Building QueueStatus Training Class Trainer TeamCodeName TeamCodeAbbr
73485 blah blah blah 315413 blah blah blah Service Desk Delivery blah Tech Support blah blah Client Specialty Queue Phone Agent blah blah Not Assigned Not Assigned 4341776 AC03 NULL NULL NULL NULL NULL NULL NULL 0 NULL NULL 00:00.0 blah blah blah Normal Generic Class Instructor Not Assigned Not Assigned
224579 blah blah blah 626985 blah blah blah Service Desk Delivery blah Tech Support blah blah Client Specialty Queue Phone Agent blah blah Not Assigned Not Assigned 4341991 AC03 NULL NULL NULL 211212 NULL 0 0 0 NULL NULL 00:00.0 blah blah blah Normal Generic Class Instructor Not Assigned Not Assigned
192329 blah blah blah 364970 blah blah blah Service Desk Delivery blah Tech Support blah blah Client Specialty Queue Phone Agent blah blah Not Assigned Not Assigned 4341937 AC03 NULL NULL NULL NULL NULL 0 0 0 NULL NULL 00:00.0 blah blah blah Normal Generic Class Instructor Not Assigned Not Assigned
```
OutIn:
```
row_date logid login logout
10/6/2013 0:00:00 4341776 10/6/2013 12:00:15 10/6/2013 21:00:26
10/7/2013 0:00:00 4341937 10/7/2013 6:04:48 10/7/2013 15:15:22
10/7/2013 0:00:00 4341991 10/7/2013 7:54:34 10/7/2013 17:00:39
10/7/2013 0:00:00 4341776 10/7/2013 12:00:16 10/7/2013 21:20:36
10/8/2013 0:00:00 4341937 10/8/2013 5:59:47 10/8/2013 15:01:31
10/8/2013 0:00:00 4341991 10/8/2013 7:58:46 10/8/2013 17:03:26
10/8/2013 0:00:00 4341776 10/8/2013 12:00:10 10/8/2013 14:32:20
10/8/2013 0:00:00 4341776 10/8/2013 14:32:20 10/8/2013 21:00:04
```
Thank you again
*Final EDIT*
I finally figured it out. Here is the completed code:
```
SELECT
a.NOM_DATE AS RowDate,
a.EMP_ID AS Badge,
ISNULL(a.[Extension], a.logid) AS [Extension],
a.Name,
a.Manager,
a.DeptName,
a.Location,
a.START_MOMENT AS ShiftStart,
a.STOP_MOMENT AS ShiftStop,
a.login AS Login,
a.logout AS Logout,
a.SEG_CODE AS OUTSEG,
IIF(a.SEG_CODE = 'PABS' OR a.SEG_CODE = 'UABS' OR a.SEG_CODE = 'PPBA' OR a.SEG_CODE = 'UPBA' OR a.SEG_CODE = 'VACA' OR a.SEG_CODE = 'JURY' OR a.SEG_CODE = 'GOVT' OR a.SEG_CODE = 'LOA' OR a.SEG_CODE = 'BRVMNT' OR a.SEG_CODE = 'FH', a.START_MOMENT, NUll) AS OutStart,
IIF(a.SEG_CODE = 'PABS' OR a.SEG_CODE = 'UABS' OR a.SEG_CODE = 'PPBA' OR a.SEG_CODE = 'UPBA' OR a.SEG_CODE = 'VACA' OR a.SEG_CODE = 'JURY' OR a.SEG_CODE = 'GOVT' OR a.SEG_CODE = 'LOA' OR a.SEG_CODE = 'BRVMNT' OR a.SEG_CODE = 'FH', a.STOP_MOMENT, NUll) AS OutStop,
IIF(DateADD(minute, 5, a.START_MOMENT) < a.Login, CONVERT(decimal(10,2), DATEDIFF(second ,a.START_MOMENT,a.Login)/60.0) ,0.00) AS Late,
ISNULL(IIF(Convert(decimal(10,2), DATEDIFF(second, a.STOP_MOMENT, a.logout)/60.0) = NULL OR Convert(decimal(10,2), DATEDIFF(second, a.STOP_MOMENT, a.logout)/60.0) > 0.00, 0.00, ABS(Convert(decimal(10,2), DATEDIFF(second, a.STOP_MOMENT, a.logout)/60.0))), 0.00) AS [Left],
IIF(a.login IS NULL AND a.SEG_CODE = 'SHIFT' ,DATEDIFF(minute,a.START_MOMENT, a.STOP_MOMENT), 0.00) AS NCNS
FROM (SELECT l.row_date, l.logid, l.[login], l.logout, f.NOM_DATE, f.EMP_ID, f.START_MOMENT, f.STOP_MOMENT, f.SEG_CODE,
f.Badge, f.Extension, f.Name, f.Manager, f.Deptname, f.Location FROM LogInOutActual l
right Join
(SELECT NOM_DATE, RTRIM(LTRIM(EMP_ID)) as EMP_ID, START_MOMENT, STOP_MOMENT, SEG_CODE, Badge,
Extension, Name, Manager, Deptname, Location FROM Shrink_Raw
LEFT OUTER JOIN Epicenter ON Shrink_Raw.EMP_ID = Epicenter.Badge
WHERE Shrink_Raw.SEG_CODE = 'PABS' OR Shrink_Raw.SEG_CODE = 'UABS' OR Shrink_Raw.SEG_CODE = 'PPBA'
OR Shrink_Raw.SEG_CODE = 'UPBA' OR Shrink_Raw.SEG_CODE = 'VACA' OR Shrink_Raw.SEG_CODE = 'JURY'
OR Shrink_Raw.SEG_CODE = 'GOVT' OR Shrink_Raw.SEG_CODE = 'LOA' OR Shrink_Raw.SEG_CODE = 'BRVMNT'
OR Shrink_Raw.SEG_CODE = 'FH' or Shrink_Raw.SEG_CODE = 'SHIFT') as f
on l.row_date = f.NOM_DATE AND l.logid = f.[ACD/Extension]) as a
WHERE Extension IS NOT NULL AND Name IS NOT NULL AND Manager IS NOT NULL and DeptName IS NOT NULL AND Location IS NOT NULL
ORDER BY RowDate, Badge;
```
After sleeping on it, I realized what to do. I did one join in a subquery and then another join in another subquery. It was so simple I feel stupid for posting it. Thank you to everyone that help the thinking process! | Your query looks mostly fine assuming you mean the RIGHT JOIN on Shrink so you don't miss any rows that don't have a matching Employee\_Data row. There's just an extraneous `JOIN (` at the end of your `FROM` clause that I removed:
```
With Epi AS
(SELECT EMP_ID, PHONE_EXTENSION, Name, Manager, EWFMDeptname, Location From Employee_Data)
,
Shrink AS
(SELECT DATE, EMP_ID, START_MOMENT, STOP_MOMENT, SEG_CODE FROM Outage_Data)
,
OutIn AS
(SELECT date, logid, login, logout From PHONE_DATA)
SELECT
-- These fields are always the same because of the inner join,
-- no need to check for nulls
-- ISNULL(Shrink.DATE,OutIn.DATE) AS RowDate,
Shrink.DATE AS RowDate,
-- These fields are always the same because of the right join
-- unless there is no matching Epi row, then Epi.EMP_ID will
-- be null. You can just use Shrink.EMP_ID. If this field
-- really needs to be trimmed, then we should be trimming
-- this field in the RIGHT JOIN clause as well.
-- ISNULL(Epi.EMP_ID,RTRIM(LTRIM(Shrink.EMP_ID))) AS Badge,
Shrink.EMP_ID AS Badge,
ISNULL(Epi.PHONE_EXTENSION, OutIn.logid) AS [ACD/Extension],
Epi.Name,
Epi.Manager,
Epi.EWFMDeptName,
Epi.Location,
-- I've added an alias to Shrink in the subqueries
-- to help clarify what is getting filtered.
-- I also changed the where clause in the subquery
-- a bit so give this a try.
-- If these are the problem fields, try not doing the
-- subqueries so you can get the actual data in the rows,
-- and mess around with just the subquery using values
-- from the original rows until you get the right START_MOMENT/STOP_MOMENT
ISNULL(Shrink.START_MOMENT, (SELECT Shrink.START_MOMENT FROM Shrink s WHERE s.SEG_CODE = 'SHIFT' AND s.EMP_ID = Shrink.EMP_ID AND s.DATE = Shrink.DATE)) AS ShiftStart,
ISNULL(Shrink.STOP_MOMENT, (SELECT Shrink.STOP_MOMENT FROM Shrink s WHERE s.SEG_CODE = 'SHIFT' AND s.EMP_ID = Shrink.EMP_ID AND s.DATE = Shrink.DATE)) AS ShiftStop,
OutIn.login AS Login,
OutIn.logout AS Logout,
Shrink.SEG_CODE AS OUTSEG,
IIF(Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH', Shrink.START_MOMENT, NUll) AS OutStart,
IIF(Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH', Shrink.STOP_MOMENT, NUll) AS OutStop,
IIF(DateADD(minute, 5, Shrink.START_MOMENT) < OutIn.Login, CONVERT(decimal(10,2), DATEDIFF(second ,Shrink.START_MOMENT,OutIn.Login)/60.0) ,0.00) AS Late,
ISNULL(IIF(Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0) = NULL OR Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0) > 0.00, 0.00, ABS(Convert(decimal(10,2), DATEDIFF(second, Shrink.STOP_MOMENT, OutIn.logout)/60.0))), 0.00) AS [Left],
IIF(OutIn.login IS NULL AND Shrink.SEG_CODE = 'SHIFT' ,DATEDIFF(minute,Shrink.START_MOMENT, Shrink.STOP_MOMENT), 0.00) AS NCNS
FROM (Epi Right JOIN Shrink on Epi.EMP_ID = Shrink.EMP_ID) INNER JOIN OutIn ON (Shrink.DATE = OutIn.DATE)
WHERE Shrink.SEG_CODE = 'PABS' OR Shrink.SEG_CODE = 'UABS' OR Shrink.SEG_CODE = 'PPBA' OR Shrink.SEG_CODE = 'UPBA' OR Shrink.SEG_CODE = 'VACA' OR Shrink.SEG_CODE = 'JURY' OR Shrink.SEG_CODE = 'GOVT' OR Shrink.SEG_CODE = 'LOA' OR Shrink.SEG_CODE = 'BRVMNT' OR Shrink.SEG_CODE = 'FH' or Shrink.SEG_CODE = 'SHIFT'
ORDER BY Badge;
``` | ```
Select * from employee_data e
join outage_data d on e.emp_id = d.emp_id
join phone_data p on d.date = p.date
``` | Joining three tables with separate sets of identifying columns | [
"",
"sql",
"join",
""
] |
I am inserting the string into table. But there are some ambiguous, illegal text characters like 'ÔÇô' , '├®' appearing in the string. I want to replace all these invalid characters from the table and update my table. Is there any way to replace such characters in SQL. I am using SQL server 2008. | You could use one of the functions here:
[How to strip all non-alphabetic characters from string in SQL Server?](https://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string-in-sql-server)
You haven't included your insert statement, so I'm going to guess you've done it similar to
```
insert into table2
SELECT dbo.fn_StripCharacters(myfield1, 'a-z0-9'), myfield2, myfield3 from table1
``` | Like you said... "Replace".
[Replace documentation](http://technet.microsoft.com/en-us/library/ms186862.aspx)
Hint: Replace the ambigous character with an empty string. | Replace Ambigious / Invalid Text Characters from String | [
"",
"sql",
"regex",
"sql-server-2008",
""
] |
I am trying to create an SQL query that combines the results of 3 queries together.
The idea is get the top 1000 users with new messages AND/OR requests AND/OR notifications and then email them one per week.
Note: I am using MS SQL Server.
I have 3 separate complex queries (which i have simplified here) such as:
```
'Get all users with new messages:
SELECT mbrid, messageCount
FROM tblMessages
WHERE messageCount > 0
'Get all users with new notifications:
SELECT mbrid, notificationCount
FROM tblNotifications
WHERE notificationCount > 0
'Get all users with new requests:
SELECT mbrid, requestCount
FROM tblRequests
WHERE requestCount > 0
```
I want to combine all 3 together into 1 table, and select the TOP 1000 records.
## For example
If each query returns:
```
mbrID messageCount
---------------------
2 20
3 2
mbrID notificationCount
---------------------
1 1
3 2
mbrID requestCount
---------------------
3 2
```
I want to combine the 3 results to create a table like so:
```
mbrID messageCount notificationCount requestCount
----------------------------------------------------------
1 0 1 0
2 20 0 0
3 2 2 2
```
Notice that the combined results should fill in the missing rows with blanks eg: 0
Is this even possible?
If there are millions of records, I guess this would be incredibly inefficient.
Any pointers to do this a better way?
## Update
Here is what I finally chose (@Upendra Chaudhari solution),
thanks to everyone for your help.
```
SELECT TOP (1000)
mbrID,
SUM(messageCount) AS messageCount,
SUM(notificationCount) AS notificationCount,
SUM(requestCount) AS requestCount
FROM (
SELECT TOP (1000)
mbrID,
messageCount,
0 AS notificationCount,
0 AS requestCount
FROM
usrv_CommMessagesNew
ORDER BY
mbrID
UNION
SELECT TOP (1000)
mbrID,
0 AS messageCount,
notificationCount,
0 AS requestCount
FROM
usrv_CommNotificationsNew
ORDER BY
mbrID
UNION
SELECT TOP (1000)
mbrID,
0 AS messageCount,
0 AS notificationCount,
requestCount
FROM
usrv_CommRequestsNew
ORDER BY
mbrID
) AS tblTemp
GROUP BY
mbrID
```
The TOP 1000 clause limits the results to improve performance.
Due to this, messageCount takes first priority followed by notificationCount then requestCount.
This means that the data may not include all rows for notificationCount or requestCount - I am fine with that in this instance - it is optimised for performance over consistency. | Try UNION like this :
```
SELECT mbrid, SUM(messageCount), SUM(notificationCount), SUM(requestCount)
FROM (
SELECT mbrid, messageCount, 0 AS notificationCount, 0 AS requestCount
FROM tblMessages
WHERE messageCount > 0
UNION
SELECT mbrid, 0 AS messageCount, notificationCount, 0 AS requestCount
FROM tblNotifications
WHERE notificationCount > 0
UNION
SELECT mbrid, 0 AS messageCount, 0 AS notificationCount, requestCount
FROM tblRequests
WHERE requestCount > 0
) TempTable
GROUP BY mbrid
``` | Just curious, once you "union" all three tables together, how are you going to decide which records are the top 1000?
If your intention is to treat messages, notifications and requests similarly, then the following may be the answer you are looking for:
```
SELECT TOP 1000 * FROM
(SELECT mbrid, messageCount as Count
FROM tblMessages
WHERE messageCount > 0
UNION ALL
SELECT mbrid, notificationCount as Count
FROM tblNotifications
WHERE notificationCount > 0
UNION ALL
SELECT mbrid, requestCount as Count
FROM tblRequests
WHERE requestCount > 0
ORDER BY Count DESC) d
```
For more information regarding the UNION and UNION ALL operators, see [this Wikipedia page](http://en.wikipedia.org/wiki/Set_operations_%28SQL%29#UNION_operator). | Combine separate SQL queries together filling in the blanks | [
"",
"sql",
""
] |
For Oracle Database, suppose I have two tables here (Similar structure, but much larger amount of data) Definition below:
```
create table payments(
record_no INTEGER;
cust_no INTEGER;
amount NUMBER;
date_entered DATE;
);
insert into payments values(1,3,34.5,sysdate-1);
insert into payments values(2,2,34.5,sysdate-2);
insert into payments values(3,3,34.5,sysdate-18/1440);
insert into payments values(4,1,34.5,sysdate-1);
insert into payments values(5,2,34.5,sysdate-2/24);
insert into payments values(6,3,34.5,sysdate-56/1440);
insert into payments values(7,4,34.5,sysdate-2);
insert into payments values(8,2,34.5,sysdate-1);
create table customer(
cust_no INTEGER;
name VARCHAR2;
zip VARCHAR2;
);
insert into customer values(1,'Tom',90001);
insert into customer values(2,'Bob',90001);
insert into customer values(3,'Jack',90001);
insert into customer values(4,'Jay',90001);
```
Now I want to generate a report with those columns (Get the first two payment amount and date for each customer order by paydate) :
> Cust\_no | pay\_amount1 | pay\_date1 |pay\_amount2 | pay\_date2
Sample report I want
```
CUST_NO PAYMENT1 PAYDATE1 PAYMENT2 PAYDATE2
1 34.5 October, 09 2013 0 null
2 34.5 October, 08 2013 34.5 October, 09 2013
3 34.5 October, 09 2013 34.5 October, 10 2013
4 34.5 October, 08 2013 0 null
```
***Can anybody make a correct and efficient Query ?*** Thanks ahead. | First you need to get your creation script right. The `;` terminates a *statement* not a line inside a statement. Secondly the `varchar2` data types needs a length specification: `name VARCHAR2(20)` instead of `name VARCHAR2`. Also character literals need to be enclosed in single quotes. `'90001'` is a character literal, `90001` is a number. Those are two different things.
So this results in the following script:
```
create table payments(
record_no INTEGER,
cust_no INTEGER,
amount NUMBER,
date_entered DATE
);
insert into payments values(1,3,34.5,sysdate-1);
insert into payments values(2,2,34.5,sysdate-2);
insert into payments values(3,3,34.5,sysdate-18/1440);
insert into payments values(4,1,34.5,sysdate-1);
insert into payments values(5,2,34.5,sysdate-2/24);
insert into payments values(6,3,34.5,sysdate-56/1440);
insert into payments values(7,4,34.5,sysdate-2);
insert into payments values(8,2,34.5,sysdate-1);
create table customer(
cust_no INTEGER,
name VARCHAR2(20),
zip VARCHAR2(20)
);
insert into customer values(1,'Tom','90001');
insert into customer values(2,'Bob','90001');
insert into customer values(3,'Jack','90001');
insert into customer values(4,'Jay','90001');
```
Note that it's bad coding practice to not specify the columns in an `INSERT` statement. It should be `insert into customer (cust_no, name, zip) values(1,'Tom','90001');` instead of `insert into customer values(1,'Tom','90001');`
---
Now for your query, the following should do you wnat you need:
```
with numbered_payments as (
select cust_no,
amount,
date_entered,
row_number() over (partition by cust_no order by date_entered) as rn
from payments
)
select c.cust_no,
c.name,
p1.amount as pay_amount1,
p1.date_entered as pay_date1,
p2.amount as pay_amount2,
p2.date_entered as pay_date2
from customer c
left join numbered_payments p1
on p1.cust_no = c.cust_no
and p1.rn = 1
left join numbered_payments p2
on p2.cust_no = c.cust_no
and p2.rn = 2;
```
Note that I used an outer join to ensure that every customer is returned even if there is no or only a single payment for it.
Here is an SQLFiddle with all corrections and the query: <http://sqlfiddle.com/#!4/74349/3> | ```
SELECT * FROM (
SELECT
c.cust_no,
p.amount as payment,
p.date_entered as paydate,
ROW_NUMBER() OVER (PARTITION BY cust_no ORDER BY p.record_no ASC) AS rn
FROM customer c
JOIN payments p ON p.cust_no = c.cust_no
) t
WHERE
rn <= 2
ORDER BY cust_no, rn;
```
Will show the 2 records per client you need, in 2 separate lines. If you prefer having it in the same line, then use this query:
```
SELECT
cust_no,
payment1,
paydate1,
CASE WHEN nextcli <> cust_no THEN 0 ELSE payment2 END AS payment2,
CASE WHEN nextcli <> cust_no THEN SYSDATE ELSE paydate2 END AS paydate2
FROM (
SELECT
c.cust_no,
p.amount as payment1,
p.date_entered as paydate1,
ROW_NUMBER() OVER (PARTITION BY c.cust_no ORDER BY p.record_no ASC) AS rn,
LEAD(c.cust_no, 1, -1) OVER (ORDER BY c.cust_no ASC) as nextcli,
LEAD(p.amount, 1, 0) OVER (ORDER BY c.cust_no ASC) as payment2,
LEAD(p.date_entered, 1, NULL) OVER (ORDER BY c.cust_no ASC) as paydate2
FROM customer c
JOIN payments p ON p.cust_no = c.cust_no
) t
WHERE
rn <= 1
ORDER BY cust_no, rn;
``` | Oracle SQL : table Joining | [
"",
"sql",
"oracle",
""
] |
I'd like to get both the minimum value of a particular value, *and* the key of the row that has that minimum value. Currently, I do this as follows:
```
SELECT dates.date AS Date, num_apples.apples AS MinApples FROM
(
SELECT date, MIN(apples) AS MinApples, apples
FROM Table
HAVING MinApples = apples
) AS dates
JOIN
(
SELECT date, apples
FROM Table
) AS num_apples
ON (
dates.date = num_apples.date
);
```
Is there a better way to do this using only "standard" (by which I mean commonly-implemented) SQL? | Assuming that `date` is your key:
```
SELECT qryNumApples.* FROM
(
SELECT MIN(apples) AS MinApples
FROM Table
) AS qryMinApples
JOIN
(
SELECT *
FROM Table
) AS qryNumApples
ON qryMinApples.MinApples= qryNumApples.apples
);
``` | This is ANSI standard SQL:
```
select *
from (
select date,
apples,
min(apples) over () as min_apples
from the_table
) t
where apples = min_apples;
```
Window functions are available across a wide range of DBMS. | Can I get data pertaining to the aggregate in a single query? | [
"",
"sql",
""
] |
Is this statement true or false
The performance of these queries
```
SELECT * FROM table;
UPDATE table SET field = 1;
SELECT COUNT(*) FROM table;
```
Are identical
Or is there ever a case in which the performance of one will greatly differ from the other?
# UPDATE
1. I'm more interested if there's a large difference between the SELECT and the UPDATE. You can ignore the COUNT(\*) if you want
2. Assume the select performs full table scan. The update will also perform update on all rows in the table.
3. Assume the update is only updating one field - though it will update all rows (it's an indexed field)
4. I know that they'll take different time and that they do different things. What I want to know is if the difference will be significant or not. EG. If the update will take 5 times longer than the select then it's significant. Use this as the threshold. And there's no need to be precise. Just give an approximation. | There are different resource types involved:
* disk I/O (this is the most costly part of every DBMS)
* buffer pressure: fetching a row will cause fetching a page from disk, which will need buffer memory to be stored in
* work/scratch memory for intermediate tables, structures and aggregates.
* "terminal" I/O to the front-end process.
* cost of locking, serialisation and versioning and journaling
* CPU cost : this is neglectable in most cases (compared to disk I/O)
The `UPDATE` query in the question is the hardest: it will cause *all* disk pages for the table to be fetched, put into buffers, altered into *new* buffers and written back to disk. In normal circumstances, it will also cause other processes to be locked out, with contention and even more buffer pressure as a result.
The `SELECT *` query needs all the pages, too; and it needs to convert/format them *all* into frontend-format and send them back to the frontend.
The `SELECT COUNT(*)` is the cheapest, on all resources. In the worst case *all* the disk pages have to be fetched. If an index is present, fewer disk- I/O and buffers are needed. The CPU cost is still neglectable (IMHO) and the "terminal" output is marginal. | When you say "performance", do you mean "how long it takes them to execute"?
* One of them is returning all data in all rows.
* One of them (if you remove the "FROM") is writing data to the rows.
* One is counting rows and returning none of the data in the rows.
All three of those queries are doing entirely different things. Therefore, it is reasonable to conclude that all three of them will take different amounts of time to complete.
Most importantly, **why are you asking this question**? What are you trying to solve? I have a bad feeling that you're going down a wrong path by asking this. | UPDATE vs COUNT vs SELECT performance | [
"",
"mysql",
"sql",
"performance",
"select",
"sql-update",
""
] |
I have a stored procedure to insert values in to a table.Here I need to check the values for insert is already in the table .how can I check this in my stored procedure.here is my stored procedure.
```
USE [Databasse_sync]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[kt_getyoutubevideo]
@ProductID nvarchar(200),
@YoutubeUrl nvarchar(200),
@YoutubeImage nvarchar(200)
AS
INSERT INTO YoutubeVideo(ProductID,YoutubeUrl,YoutubeImage,DATASET)VALUES(@ProductID,@YoutubeUrl,@YoutubeImage,'DAT')
RETURN
```
Here I need to check the ProducId is same or not?If ProductId is same then Update otherwise Insert.>>>?? | ```
USE [Databasse_sync]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[kt_getyoutubevideo]
@ProductID nvarchar(200),
@YoutubeUrl nvarchar(200),
@YoutubeImage nvarchar(200)
AS
MERGE [YoutubeVideo] AS Y
USING (SELECT @ProductID,@YoutubeUrl, @YoutubeImage) AS SourceRow (ProductID,YoutubeUrl,YoutubeImage)
ON Y.[ProductID] = SourceRow.ProductID
WHEN MATCHED THEN
UPDATE SET
Y.[ProductID] = SourceRow.ProductID
,Y.[YoutubeUrl] = SourceRow.YoutubeUrl
,Y.[YoutubeImage] = SourceRow.YoutubeImage
WHEN NOT MATCHED THEN
INSERT (ProductID,YoutubeUrl, YoutubeImage, DATASET)
VALUES (SourceRow.ProductID,SourceRow.YoutubeUrl, SourceRow.YoutubeImage,'DAT');
RETURN
``` | try this:
```
ALTER PROCEDURE [dbo].[kt_getyoutubevideo]
@ProductID nvarchar(200),
@YoutubeUrl nvarchar(200),
@YoutubeImage nvarchar(200)
```
`AS BEGIN`
```
DECLARE @counter int
@counter = SELECT count(ProductID) FROM YoutubeVideo WHERE ProductID=@ProductID
IF(@counter = 0)
BEGIN
INSERT INTO YoutubeVideo(ProductID,YoutubeUrl,YoutubeImage,DATASET)VALUES(@ProductID,@YoutubeUrl,@YoutubeImage,'DAT')
End
ELSE
begin
UPDATE SET
ProductID = @ProductID
,YoutubeUrl = @YoutubeUrl
,YoutubeImage = @YoutubeImage
END END
``` | Storedprocedure to check the value already in the table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I am working on a project related to ticket booking.
I can store passenger data i.e. Name,Age,Sex along with Ticket ID in passenger table.
But the problem is if another ticket is booked for same passenger I will have to re-enter the same passenger data & just the Ticket ID will differ.
```
mysql> desc passenger;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Name | varchar(32) | NO | | NULL | |
| Age | int(11) | NO | | NULL | |
| sex | char(1) | NO | | NULL | |
| PNR | varchar(32) | YES | MUL | NULL | |
+-------+-------------+------+-----+---------+-------+
```
Can anyone Please tell me how can I minimize such redundancy?
Any link,reference,clue or idea will be appreciable.
Thank you | You could store a passenger entity, consisting of name/age/sex etc. (in a passenger entity table) and then your passenger booking table would simply contain the passenger entity ids (integers, GUIDs etc.). This is a form of *normalisation*.
However this may be an optimisation too far. Whether you do this really depends on how many duplicate entities etc. you have, and whether they're a real performance/management issue for you. e.g. do you expect to store more data for passengers (addresses, frequent flyer info etc.). | In a relational database like mysql, surely the passenget and ticket data should be in separate tables. So have a passenger table that contains personal details like Name, DateOfBirth, Address, Telephone etc and then have a ticket table that has ticketNumber, date etc as well as passengerId (classic many to one relationship). | Lot of redundancy in passenger table | [
"",
"mysql",
"sql",
"database",
"redundancy",
""
] |
I’m doing:
```
SELECT uid, intStatus from dbo.MYTABLE
WHERE
intStatus = 10 and uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1'
```
And I get:
```
uid | intStatus
-------------------------------------- +---------------
'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1 | 10
```
Then I need to do an update, I need the intStatus to be 18 for that uid. So I do:
```
UPDATE dbo.MYTABLE SET intStatus = 18
WHERE
intStatus = 10 and uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1'
```
And here’s where I’m getting the error:
Cannot insert duplicate key row in object 'dbo.MYTABLE' with unique index 'ixMYTABLE'.
Can anyone, please, tell me why I’m getting this error? How can I solve it?
uid is primary key for MYTABLE
intStatus is a not null int
Thanks a ton! | Probably you have already a row with intStatus 18 and uid 'a1a1...'
Try to run and see if you have already the row that you try to create with your UPDATE:
```
SELECT uid,
intStatus
FROM dbo.MYTABLE
WHERE intStatus = 18
AND uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1'
``` | If uid is your primary key then it is unique by definition, therefore the intStatus condition is irrelevant. This should work:
```
UPDATE dbo.MYTABLE SET intStatus = 18
WHERE uid = 'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1';
```
If that doesn't work, then you could have a composite key combining both columns rather than a single column key.
[Info on primary keys and composites](http://technet.microsoft.com/en-us/library/ms191236%28v=sql.105%29.aspx) | Need explanation for Cannot insert duplicate key row in object error | [
"",
"sql",
"sql-update",
"key",
"duplicates",
"uniqueidentifier",
""
] |
I have the following table ordered by Id, Year DESC
```
Id Year Valid
1 2011 1
1 2010 1
1 2009 0
1 2002 1
4 2013 1
4 2012 1
4 2011 1
etc.
```
What I would like to have is an extra rank field like:
```
Id Year Valid Rank
1 2011 1 1
1 2010 1 1
1 2009 0 2
1 2002 1 3
4 2013 1 1
4 2012 1 1
4 2011 1 1
etc.
```
Basically per Id alternating ranks for every change in the Valid field. In such a way I can query on the rank=1 field to have all Valid=1 records for each and every Id up to the first Valid=0. Or is there an easier way to select the first top number of records matching a certain condition (For Id=1 only the first two records). I already played with ROW\_NUMBER(), RANK() and PARTITION BY but I can't seem to get it to work. Must avoid nesting of queries since the actual query is run against a large database.
Anyone any ideas?
Thanks and cheers,
Nyquist | yes, using Left JOIN we can do that.
see the below code and result.
first image is actual data inserted and second image is expected result.

```
DECLARE @t TABLE
(
id INT
,_YEAR INT
,valid TINYINT
)
INSERT INTO @t( id, [_YEAR], valid )
SELECT 1,2011,1
UNION ALL SELECT 1,2010,1
UNION ALL SELECT 1,2009,0
UNION ALL SELECT 1,2002,1
UNION ALL SELECT 4,2013,1
UNION ALL SELECT 4,2012,1
UNION ALL SELECT 4,2011,1
UNION ALL SELECT 5,2013,0
UNION ALL SELECT 5,2011,1
UNION ALL SELECT 5,2010,1
UNION ALL SELECT 6,2010,1
UNION ALL SELECT 6,2011,0
UNION ALL SELECT 6,2014,1
SELECT q1.*
FROM @t q1
LEFT JOIN
(
SELECT id,MAX(_YEAR) ZeroYear
FROM @t
WHERE valid = 0
GROUP BY id
)q2
ON q1.id=q2.id
WHERE
(q2.ID IS NULL)
OR
(q2.id IS NOT NULL AND q1.id IS NOT NULL AND q1.id=q2.id AND q1.[_YEAR] > q2.ZeroYear)
```
**Edit-1:**
In above query for the column ZeroYear, previously i did MIN(\_YEAR) but as you can see in the comment from "Andriy M" instead of MIN right function is MAX. | This is somewhat similar to [@Anup Shah's suggestion](https://stackoverflow.com/a/19306054/297408) but doesn't use a join and instead uses a window aggregate function:
```
WITH derived AS (
SELECT
Id,
Year,
Valid,
LatestInvalidYear = ISNULL(
MAX(CASE Valid WHEN 0 THEN Year END) OVER (PARTITION BY Id),
0
)
FROM atable
)
SELECT
Id,
Year,
Valid
FROM derived
WHERE Year > LatestInvalidYear
;
```
Basically, the window MAX calculates the latest `Valid = 0` year per `Id`. If no such year is found, MAX results in a NULL, which is replaced with a 0 by ISNULL. So, for your example, the `derived` set would be returned as this:
```
Id Year Valid LatestInvalidYear
-- ---- ----- -----------------
1 2011 1 2009
1 2010 1 2009
1 2009 0 2009
1 2002 1 2009
4 2013 1 0
4 2012 1 0
4 2011 1 0
```
Obviously, you can now easily apply the filter `Year > LatestInvalidYear` to get the required rows, and that is exacly what the main SELECT does. | How to group/rank records based on a changing value of a column? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
```
WHERE CloseTime >= DATEADD(Month, DATEDIFF(Month, 0, DATEADD(m, - 6, CURRENT_TIMESTAMP)), 0)
```
This gets me data for the month I am starting this script + 6 last months. So e.g. if I run this script today, Ill get the data for this month + all previous months till April (04).
Now I need to modify the condition so if I run the script today, the data will be obtained only for months 03-09 only, exluding days in this month (10).
Any advice, please? | If you want to have the previous 6 months regardless of whether today is the 1st, 3rd, 9th, 29th, whatever, then just subtract 7 months. Here is one way to do that: get the first of the month into a variable, then use an open-ended range in the query.
```
DECLARE @ThisMonth DATETIME;
SET @ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
SELECT...
WHERE CloseTime >= DATEADD(MONTH, -7, @ThisMonth)
AND CloseTime < @ThisMonth;
```
You could also use `0` in place of `'19000101'` but I prefer an explicit date than implicit shorthand (it was a very tough habit to break).
If you really don't like variables, then you can make the query a lot more complex by repeating the expression to calculate the first of this month (and in the start of the range, subtract 7 from the number of months):
```
SELECT...
WHERE CloseTime >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CloseTime < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
```
Yuck. Variables make this much tidier. | When creating queries you do not want to use a function on the search column since it will result in a full table scan.
The solution works and should pick up any index on CloseTime.
```
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
CloseTime between
DATEADD(d, -1, '03-01-2013') and DATEADD(d, +1, '09-20-2013')
```
If the table is small and a full table scan is not a issue, a simple solution is to use the MONTH function.
```
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
MONTH(CloseTime) IN (3,4,5,6,7,8,9) and YEAR(CloseTime) = 2013
``` | SQL for last six "full" months | [
"",
"sql",
"sql-server",
""
] |
I have a date column that is in varchar. I need to convert it to datetime format.
> My data looks like this in varchar:29-JUL-11 02.44.29.984664000 PM
>
> I want this to be in datetime format like this: 29-JUL-11 02.44.29.984664000 PM
I am using following query:
```
select convert (datetime, (convert (float, [KYC_STATUS_CHANGED_DATE])),120) from [dbo].[KYC_Data_31122012]
```
But it is giving following error:
> Error converting data type varchar to float
What am I doing wrong? | You could go the whole hog and do a replace/substring to get your answer
```
select cast(Replace(SUBSTRING('29-JUL-11 02.44.29.984664000 PM',
0, len('29-JUL-11 02.44.29.984664000 PM') - 9),'.',':') as datetime)
```
Ugly but it works! | > I have a date column that is in varchar.
Wrong in the first place. You should use the datatype created for the data.
> I need to convert it to datetime format.
If you're using ASP.NET (I am guessing by the sql-server usage) then you can use this:
```
var time = Convert.ToDateTime("some_time");
```
However
> My data looks like this in varchar:29-JUL-11 02.44.29.984664000 PM
>
> I want this to be in datetime format like this: 29-JUL-11 02.44.29.984664000 PM
What do you think that this might be? I don't see this as a time. Its a combination of Time and some String for me.
> Error converting data type varchar to float
You are converting varchar to float, float is a datatype for decimals. Floats have a floating decimal between their numbers. So I think that you're not converting the varchar to datetime, instead you're writing a code to convert it to float.
Instead of in SqlServer select, try converting it in the page like I did.
> 29-JUL-11 02.44.29.984664000 PM
In this thing, where is ':'? Server won't guess that it has any time in it. You should try to convert the datatype to datetime in the first place!
Good luck, cheers! | Convert a varchar to datetime including hour minute and seconds | [
"",
"sql",
"sql-server",
"datetime",
""
] |
my DB has this structure:
```
ID | text | time | valid
```
This is my current code. I'm trying to find a way to do this as one query.
```
rows = select * from table where ID=x order by time desc;
n=0;
foreach rows{
if(n > 3){
update table set valid = -1 where rows[n];
}
n++
}
```
I'm checking how many rows exist for a given ID. Then I need to set valid=-1 for all rows where n >3;
Is there a way to do this with one query? | Assuming that `(id,time)` has a `UNIQUE` constraint, i.e. no two rows have the same `id` and same `time`:
```
UPDATE
tableX AS tu
JOIN
( SELECT time
FROM tableX
WHERE id = @X -- the given ID
ORDER BY time DESC
LIMIT 1 OFFSET 2
) AS t3
ON tu.id = @X -- given ID again
AND tu.time < t3.time
SET
tu.valid = -1 ;
``` | You can use a subquery in the `WHERE` clause, like this:
```
UPDATE table
SET valid=-1
WHERE (
SELECT COUNT(*)
FROM table tt
WHERE tt.time > table.time
AND tt.ID = table.ID
) > 3
```
The subquery counts the rows with the same ID and a later time. This count will be three or less for the three latest rows; the remaining ones would have a greater count, so their `valid` field would be updated. | update row if count(*) > n | [
"",
"mysql",
"sql",
"insert",
"sql-update",
""
] |
Have a problem find a query for my tables
I have 2 tables table A and table B as follow
```
table A
---------------------
| Name | addrid |
---------------------
| zlai | 1 |
| blai | 2 |
table B
---------------------
| addrid | addr |
---------------------
| 1 | AMERICA |
| 1 | SPAIN |
| 1 | MEXICO |
| 2 | TURKEY |
```
The result I need is
```
--------------------------
| Num | Name | addr |
--------------------------
| 1 | zlai | AMERICA |
| | | SPAIN |
| | | MEXICO |
| 2 | blai | TURKEY |
```
Query I have tried so far
<http://sqlfiddle.com/#!12/3ac39/12> | I try to modified the `addrid` values by 101 and 325 (for example)
```
table A
---------------------
| Name | addrid |
---------------------
| zlai | 101 |
| blai | 325 |
table B
---------------------
| addrid | addr |
---------------------
| 101 | AMERICA |
| 101 | SPAIN |
| 101 | MEXICO |
| 325 | TURKEY |
```
the query is:
```
SELECT CASE WHEN No != 1
THEN ''
ELSE CAST(row AS VARCHAR(20))
END AS Num,
CASE WHEN No != 1
THEN ''
ELSE name
END AS name,
addr
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.addrid
ORDER BY name DESC) AS No,
name,
addr,
DENSE_RANK() OVER (ORDER BY a.addrid) "row"
FROM a LEFT JOIN b ON a.addrid = b.addrid
) a
ORDER BY row
```
and the result is same as you want.
[SQL Fiddle Demo](http://sqlfiddle.com/#!12/a1b74/1/0) | ```
SELECT CASE WHEN No != 1
THEN ''
ELSE CAST(a.addrid AS VARCHAR(20))
END AS Num,
CASE WHEN No != 1
THEN ''
ELSE name
END AS name,
addr
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.addrid
ORDER BY name DESC) AS No,
name,
addr,
a.addrid
FROM a LEFT JOIN b ON a.addrid = b.addrid
) a
ORDER BY a.addrid
```
* [SQLFiddle Demo](http://sqlfiddle.com/#!12/704f5/2) | query for grouping multiple same record into 1 line | [
"",
"sql",
"postgresql",
""
] |
I am trying to create the following SQL table, using the query:
```
create table Return_indiv (Date datetime, issueid varchar(255), Return varchar(255))
```
As you see, one of the columns names is "Return". However, SQL believes it is the function `return`, and gives the following error:
```
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Return'.
Msg 195, Level 15, State 10, Line 1
'varchar' is not a recognized built-in function name.
```
Any way I could overcome this error? Thanks! | You need to add brackets around the column name since it's a keyword:
```
create table Return_indiv
(
Date datetime,
issueid varchar(255),
[Return] varchar(255)
)
```
Note that you'l also have to use brackets every time you *query* that column in the table (or update, etc.) With that in mind you need to decide if it's worth it to have a column with the same name as a reserved word.
Also note that `Date` is a keyword in SQL 2008 and above - so if you plan on upgrading it will be necessary to escape that column name as well. | Just to clarify a bit, Return is a reserved word in your database (probably a function or something). So you can't just use it as a table name, column name, etc. You can get around this by surrounding it with []. But a much better idea is to not use reserved words in any of your object names. I can't really tell what will be in that column, but maybe you can name it RETURN\_VALUE, RETURN\_ITEM, whatever. Just avoid reserved words, it makes life easier for just about everyone. | Creating SQL table with column name "Return" | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I'm having a very difficult time trying to get my result to display they i need them to display... here and example of what my query looks like and below will be the result i need...
iv been at this for a long time trying case statements and joins but have had no luck, if anybody can help i would really appreciate it.
```
table name dbo.DTLPAYMENTS
columns
PTNO
CD
AMT
DESCRIPTION
```
my query displays my result back to me like so...also there never an equal amount line for credits and debits. so a person can have more debits(>0) than credits(<0) and vice versa....
```
PTNO / CD / AMT / DESCRIPTION
10007558931 30073 688.82 PAYMENT-ME
10007558931 30073 -704.44 PAYMENT-ME
10007558931 30073 704.44 PAYMENT-ME
10007558931 30073 -688.82 PAYMENT-ME
10007558931 30073 -698.82 PAYMENT-ME
```
i need this the debit and credit in separate columns
if there any way possible i can have it result back to me like so...
```
PTNO / CD / AMT / DESCRIPTION / CD / AMT / DESCRIPTION
10007558931 30073 688.82 PAYMENT-ME 30073 -688.82 PAYMENT-ME
10007558931 30073 704.44 PAYMENT-ME 30073 -698.82 PAYMENT-ME
10007558931 30073 -704.44 PAYMENT-ME
```
and thanks you if anyone can help me | First, use CTEs to separate Credits and Debits into separate data sets, then FULL JOIN them based on PTNO, CD, and inverse value (\* -1) of AMT.
Edit: Since joining based on AMT is not a goal, I used BatchSeqID as a way to sort the data chronologically. Using a ROW\_NUMBER() to order the two data sets, I then joined then on this value.
```
;WITH
Credit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT < 0 ),
Debit AS
( SELECT PTNO,CD,AMT,DESCRIPTION,
ROW_NUMBER()OVER(PARTITION BY PTNO,CD ORDER BY BatchSeqID) AS Sort
FROM dbo.DTLPAYMENTS
WHERE AMT > 0 )
SELECT ISNULL(c.PTNO,d.PTNO) AS PTNO,
ISNULL(c.CD,d.CD) AS CD,
--Credit data
c.AMT AS CRAMT,
c.DESCRIPTION AS CRDESCRIPTION,
--Debit data
d.AMT AS DBTAMT,
d.DESCRIPTION AS DBTDESCRIPTION
FROM Credit c
FULL JOIN Debit d
ON d.PTNO = c.PTNO
AND d.CD = c.CD
AND d.Sort= c.Sort
``` | if you don't like Matt's solution and the risk of duplicated rows, you can have every transaction on a different row:
```
SELECT PTNO,
CASE WHEN AMT < 0 THEN cd ELSE null END DBTCD,
CASE WHEN AMT < 0 THEN amt ELSE null END AMTCD,
CASE WHEN AMT < 0 THEN DESCRIPTION ELSE null END DBTDESCRIPTION,
CASE WHEN AMT > 0 THEN cd ELSE null END CRCD,
CASE WHEN AMT > 0 THEN amt ELSE null END CRAMT,
CASE WHEN AMT > 0 THEN DESCRIPTION ELSE null END CRDESCRIPTION
FROM TABLE1
order by PTNO, AMT
```
[Here](http://sqlfiddle.com/#!3/c54c4/14) you can see and play wiht the result.
```
PTNO DBTCD AMTCD DBTDESCRIPTION CRCD CRAMT CRDESCRIPTION
10007558931 30073 -704 PAYMENT-ME (null) (null) (null)
10007558931 30073 -699 PAYMENT-ME (null) (null) (null)
10007558931 30073 -689 PAYMENT-ME (null) (null) (null)
10007558931 (null) (null) (null) 30073 689 PAYMENT-ME
10007558931 (null) (null) (null) 30073 704 PAYMENT-ME
``` | SQL Return different values on the same row, based on a value thats in the same table | [
"",
"sql",
"sql-server",
""
] |
I am trying to find a specific `legalStatus` for a specific date range from the following table layout.
```
CREATE TABLE dbo.LegalStatus (
LegalStatusID int IDENTITY,
CaseID int NOT NULL,
LegalStatusTypeID int NOT NULL,
LegalStatusDate smalldatetime NOT NULL
```
Example: I may have three status records.
```
LegalStatusID = 1,
CaseID =17,
LegalStatusTypeID = 52,
LegalStatusDate = 4/1/12
LegalStatusID = 2,
CaseID =17,
LegalStatusTypeID = 62,
LegalStatusDate = 10/1/12
LegalStatusID = 3,
CaseID =17,
LegalStatusTypeID = 72,
LegalStatusDate = 10/1/13
```
I am trying to report on all cases that have `LegalStatusTypeID` = 62 between 1/1/13 and 7/1/13.
This would be easy if there was an end date.
Help!
Andy | OK, if I understand your comment, for a given `CaseID`, you can have multiple records, each with with a `LegalStatusTypeID` unique to that case, each with a date, and the applicability for each `LegalStatusTypeID` is between that record's `LegalStatusDate` and *the next record entered for that case*'s `LegalStatusDate`:
```
SELECT qrySub.CaseID, qrySub.LegalStatusDate, LegalStatus.LegalStatusDate AS
NextLegalStatusDate
FROM (
SELECT LegalStatus_2.LegalStatusID, LegalStatus_2.CaseID, LegalStatus_2.
LegalStatusTypeID, LegalStatus_2.LegalStatusDate, MIN(qryNext.
LegalStatusID) AS NextLegalStatusID
FROM LegalStatus AS LegalStatus_2
LEFT JOIN (
SELECT LegalStatusID, CaseID, LegalStatusTypeID, LegalStatusDate
FROM LegalStatus AS LegalStatus_1
) AS qryNext
ON LegalStatus_2.CaseID = qryNext.CaseID AND LegalStatus_2.LegalStatusID
< qryNext.LegalStatusID
GROUP BY LegalStatus_2.LegalStatusID, LegalStatus_2.CaseID, LegalStatus_2.
LegalStatusTypeID, LegalStatus_2.LegalStatusDate
HAVING (LegalStatus_2.LegalStatusTypeID = 62)
) AS qrySub
LEFT JOIN LegalStatus
ON qrySub.NextLegalStatusID = LegalStatus.LegalStatusID
WHERE (
qrySub.LegalStatusDate BETWEEN CONVERT(DATETIME, '2013-01-01 00:00:00'
, 102) AND CONVERT(DATETIME, '2013-07-01 00:00:00', 102)
) OR (
LegalStatus.LegalStatusDate BETWEEN CONVERT(DATETIME,
'2013-01-01 00:00:00', 102) AND CONVERT(DATETIME,
'2013-01-07 00:00:00', 102)
) OR (qrySub.LegalStatusDate < CONVERT(DATETIME, '2013-01-01 00:00:00', 102)
) AND (
LegalStatus.LegalStatusDate > CONVERT(DATETIME, '2013-01-07 00:00:00',
102)
)
```
You need to join the records for `LegalStatusTypeID` = 62 to the next record for any given case, then use the ID of that next case to get the date which is the end of applicability of the `LegalStatusTypeID` = 62.
Since you are talking about cases which had a `LegalStatusTypeID` = 62 *during* your date range, you need cases where the start date is in your date range, or the end date is in your date range (or both), or your date range is between the case's `LegalStatusTypeID` = 62 start and end dates. | ```
SELECT *
FROM LegalStatus
WHERE LegalStatusTypeID = 62 AND
LegalStatusDate BETWEEN '01/01/13' and '07/01/13'
``` | How can I find a specific status within a date range | [
"",
"sql",
"t-sql",
""
] |
I have a table named accessories\_other in my database. In the table, I have column :
1) Item
2)Available
This is the illustration on how the data in the respective column.
## Item
Mouse
Keyboard
Cable
## Available
4
6
3
The thing is, I would like to select Item = 'Mouse' together with column 'Available'=4. If the available mouse is less than 5, it will send me an email for the next step. But I stuck until this stage.
This is SQL statement that I create, and it count each row for 'Available' column, and send the email if the row of Available column is less than 5, which is not I want.
```
$sql ="SELECT Item, Available FROM accessories_other WHERE Item ='Mouse'
AND Available <5";
```
How do I do so that it can retrieve mouse which is the availability less than 5. | > This is just to show how it could be done . You should be using MySQLi
> or PDO . Also if in Production environment , you should not be
> displaying MySQL errors to the user .
You could do it either way :
```
// SQL to find Available value for Item Mouse
$sql = "SELECT Item, Available FROM accessories_other
WHERE Item = 'Mouse'";
$result = mysql_query( $sql ) or die( 'Query failed.'.mysql_error() );
$row = mysql_fetch_array( $result ) ;
if( mysql_num_rows( $result ) > 0 )
{
echo $row['Item'] ,': ' ,$row['Available'];
if( $row['Available'] < 5 )
{
// Code to send email
}
else
{
// Code to what ever you would like to do here
}
}
```
or
```
// SQL to find Available value for Item Mouse if it is less than 5
$sql = "SELECT Item, Available FROM accessories_other
WHERE Item = 'Mouse' AND Available < 5";
$result = mysql_query( $sql ) or die( 'Query failed.'.mysql_error() );
if( mysql_num_rows( $result ) > 0 )
{
// Code to what ever you would like to do here
}
else
{
echo $row['Item'] ,': ' ,$row['Available'];
// Code to send email
}
``` | I think your query will not show results of mouse which is lesser than 5..
I suggest you try:
```
$sql ="SELECT Item, Available FROM accessories_other WHERE Item ='Mouse';
```
and then, try to implement your code in another language..
if I'm not mistaken, you're using php.. | How to retrieve data from 2 column in one table? | [
"",
"sql",
"sql-server",
""
] |
This is my stored procedure:
```
ALTER PROCEDURE [dbo].[procViewAdvSearchL1]
-- Add the parameters for the stored procedure here
@keyword nvarchar(800),
@CourtID int = null,
@SYear int = null,
@EYear int = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[viewTextSearchL]'))
DROP VIEW [dbo].[viewTextSearchL]
Declare @sqlquery nvarchar(1500)
Set @sqlquery ='
CREATE VIEW viewTextSearchL
AS
SELECT tblCase.judgement_id AS ID, tblCase.case_number AS Case_No, tblCase.applicant_name AS Aplicant, tblCase.respondent_name AS Respondent, tblCase.case_date AS Case_Date,
tblCourt.court_name AS Court_Name, tblCase.YearOfCase
FROM tblCase INNER JOIN
tblCourt ON tblCase.court_id = tblCourt.court_id INNER JOIN
tblJudgement ON tblCase.judgement_id = tblJudgement.judgement_id
WHERE CONTAINS(tblJudgement.judgement_desc,'+@keyword+') AND (CAST(tblCase.YearOfCase AS int) BETWEEN '+@SYear+' AND '+@EYear+')'
EXECUTE(@sqlquery)
END
```
But this gives error
> Msg 137, Level 15, State 2, Procedure viewTextSearchL, Line 9
> Must declare the scalar variable "@SYear". | ```
@CourtID int = null,
@SYear int = null,
@EYear int = null
```
All above variable should be declare in NVARCHAR Because dynamic query
give error except it.
```
It Should be
@CourtID NVARCHAR(20) = null,
@SYear NVARCHAR(20) = null,
@EYear NVARCHAR(20) = null
```
Use `exec sp_execute` to execute your query except `EXECUTE(@sqlquery)`
For more details [click here](http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure) | Based on the posted code i can only see it would get a conversion error of :
`Conversion failed when converting the varchar value '' to data type int.`
Use the following
```
CONVERT(VARCHAR(4),@SYear)
```
and
```
CONVERT(VARCHAR(4),@EYear)
``` | How to pass int parameter in dynamic sql query | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I have 2 queries
```
Select * From wp_booking_transaction
Where DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10"
And action = 1 status = 1 And type = 2 And student_id = 81569
Order by launched desc
```
and
```
Select * From wp_booking_transaction
Where (DATE(launched) >= "2013-10-10" And DATE(launched) <= "2013-11-10"
And status = 0 And type = 2 And student_id = 81569) And (action = 21 Or action = 20)
Order by launched desc
```
REQUIREMENT:
Get rows that has `action = 1` but `status = 1` and rows that has `(action = 20 or action = 21)` but `status = 0`.
Thank you! | ```
SELECT *
FROM wp_booking_transaction
WHERE /* Conditions that appeared in both original queries */
DATE(launched) >= "2013-10-10"
AND DATE(launched) <= "2013-11-10"
AND type = 2
AND student_id = 81569
AND /* Conditions that are different between the two queries */
((action = 1 AND status = 1) OR (action IN(20, 21) AND status = 0))
ORDER BY launched DESC
``` | Try using `UNION`:
```
Select
*
From
wp_booking_transaction
Where
DATE(launched) >= "2013-10-10"
And DATE(launched) <= "2013-11-10"
And action = 1
And status = 1
And type = 2
And student_id = 81569
UNION ALL
Select
*
From
wp_booking_transaction
Where (
DATE(launched) >= "2013-10-10"
And DATE(launched) <= "2013-11-10"
And status = 0
And type = 2
And student_id = 81569
)
And (
action = 21
Or action = 20
)
Order by launched desc
```
**BTW** this:
```
And (
action = 21
Or action = 20
)
```
can be written like
```
And action IN (21,20)
``` | Combining 2 queries into one query | [
"",
"mysql",
"sql",
""
] |
I have two tables Product table and Rate Table.
**Product**
```
ProductId Name
```
**Rate**
```
LevelId Cost ProductId
```
Each Product has 7 Levels and cost for each level is 100, 200.... 700.
I now need a script to take all the product Ids and Populate the Rate table , so that my end output would look like this :
**Rate**
**LevelId Cost ProductId**
```
1 100 1
2 200 1
3 300 1
4 400 1
5 500 1
6 600 1
7 700 1
1 100 2
```
and so on
Currently I insert the first 7 rows manually and then run the below query for every product id
```
INSERT INTO dbo.Rate (LevelID, Cost, ProductId)
SELECT LevelID, Cost, ProductId FROM dbo.Rate WHERE ProductId = 1
```
Can you direct me on how to fully automate my work ? | ```
INSERT INTO Rate
SELECT bs.level, bs.costs, P.productid
FROM
(SELECT 1 as level, 100 as cost
UNION ALL
SELECT 2 as level, 200 as cost
UNION ALL
SELECT 3 as level, 300 as cost
UNION ALL
SELECT 4 as level, 400 as costs
UNION ALL
SELECT 5 as level, 500 as costs
UNION ALL
SELECT 6 as level, 600 as costs
UNION ALL
SELECT 7 as level, 600 as costs) bs,
Product P
``` | Have a look at [CTEs (Common Table Expressions)](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx):
```
WITH CTE AS
(SELECT 1 as LevelID , 100 as Cost
UNION ALL
SELECT LevelID + 1 , Cost + 100
FROM CTE
WHERE LevelID < 7)
INSERT INTO Rate
SELECT CTE.LevelID, CTE.Cost, Product.ProductID
FROM CTE CROSS JOIN Product
```
A CTE can create a virtual table of data using an algorithm, so there is no need to manually create a table full of predictable data. A query using six `UNION ALL`s is not so bad, but what about hundreds or thousands or millions? If you have more than 100 recursions and not more than 32767, you'd need to add `OPTION (MAXRECURSION n)` where `n` is the number of loops you need, or if you had more than 32767 loops, you'd need to add `OPTION (MAXRECURSION 0)` and be wary of a infinite loop. | Sql script to use a column from one table and populate another table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"sql-server-2008-r2",
""
] |
I'm writing a basic `SELECT` query, something like:
```
SELECT id, pname, pnumber
FROM tableName
WHERE pnumber IS NOT NULL
```
I'd like to then perform an `INSERT` by using the result of that `SELECT` like so:
```
IF {**the above SELECT query returned 0 rows**}
BEGIN
INSERT INTO tableName (pname,pnumber) VALUES ('bob', '38499483')
END
```
My question is, how can I check for the `**the above SELECT query returned 0 rows**`? | ```
IF NOT EXISTS (SELECT ...)
BEGIN
INSERT ...
END
```
You could also do this, if you expect that the query might often return rows (especially a lot of rows), which may offer a better opportunity to short circuit:
```
IF EXISTS (SELECT ...)
BEGIN
PRINT 'Do nothing.';
END
ELSE
BEGIN
INSERT ...
END
```
...since `IF EXISTS` will return immediately after it hits the very first row that matches.
I don't recommend using `@@ROWCOUNT` only because you will have to materialize (and ignore) the full result set every time. | In MySQL you can check the number of rows returned from last SELECT query like this:
```
SELECT FOUND_ROWS();
``` | Check if SELECT Returns Any Rows in Stored Procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
Using ORACLE sql developer
I have:
Field ID 1: '006789'
Field ID 2: '026789'
Field ID 3: '126789'
I want:
Field ID 1: '6789'
Field ID 2: '26789'
Field ID 3: '126789'
This lives in table "EMPLOYEES"
I want to do something like this
```
begin
if FIELD_ID is like '00%' then
update EMPLOYEES
set FIELD_ID = %s/\%1c..//
elseif FIELD_ID is like '0%' then
update EMPLOYEES
set FIELD_ID = %s/\%1c.//
endif;
```
I'm really new to procedures and regex (obviously). | If you need to remove leading or trailing characters from a string, you don't need regex, TRIM functions wil suffice. In Oracle, there
are three functions, [TRIM](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions229.htm#SQLRF06149), [LTRIM](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions103.htm#SQLRF00664) and [RTRIM](http://docs.oracle.com/cd/E16655_01/server.121/e17209/functions169.htm#SQLRF06104).
To answer your question, either
```
ltrim(field_id,'0')
```
or
```
trim(leading '0' from field_id)
```
should work.
Also, note that there a subtle difference between TRIM and LTRIM/RTRIM. TRIM can take only one trim character, while RTRIM/LTRIM can take many. | not sure why did you go with RegExp, but if you need just removing Leading and Trailing character from string Oracle has TRIM function for that.
***TRIM(both '1' from '123Tech111') would return '23Tech'***
[example that fits your requirement](http://www.techonthenet.com/oracle/functions/trim.php)
[Oracle Documentation](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions199.htm) | pl/sql conditionally replace characters of field in a table using regex | [
"",
"sql",
"regex",
"oracle",
""
] |
I hope the title is somewhat helpful. I'm using MySQL as my database
I am building a database of products and am not sure how to handle storing prices/SKU of variations of a product. A product may have unlimited variations, and each variation combination has its own price/SKU/etc..
This is how I have my products/variations table set up at the moment:
```
PRODUCTS
+--------------------------+
| id | name | description |
+----+------+--------------+
| 1 | rug | a cool rug |
| 2 | cup | a coffee cup |
+----+------+--------------+
PRODUCT_VARIANTS
+----+------------+----------+-----------+
| id | product_id | variant | value |
+----+------------+----------+-----------+
| 1 | 1 | color | red |
| 2 | 1 | color | blue |
| 3 | 1 | color | green |
| 4 | 1 | material | wool |
| 5 | 1 | material | polyester |
| 6 | 2 | size | small |
| 7 | 2 | size | medium |
| 8 | 2 | size | large |
+----+------------+----------+-----------+
(`products.id` is a foreign key of `product_variants.product_id`)
```
I've created an SQLFiddle with this sample data: <http://sqlfiddle.com/#!2/2264d/1>
The user is allowed to enter any variation name (`product_variants.variant`) and can assign any value to it (`product_variants.value`). **There should not be a limit the amount of variations/values a user may enter.**
**This is where my problem arises: storing prices/SKU for each variation without adding a new table/column every time someone adds a product with a variant that did not exist before.**
Each variant may have the same price but the SKU is unique to each product.
For example Product `1` has 6 different combinations (3 colors \* 2 materials) and Product `2` only has 3 different combination (3 sizes \* 1).
I've thought about storing the combinations as a text, i.e:
```
+------------+-----------------+-------+------+
| product_id | combination | price | SKU |
+------------+-----------------+-------+------+
| 1 | red-wool | 50.00 | A121 |
| 1 | red-polyester | 50.00 | A122 |
| 1 | blue-wool | 50.00 | A123 |
| 1 | blue-polyester | 50.00 | A124 |
| 1 | green-wool | 50.00 | A125 |
| 1 | green-polyester | 50.00 | A125 |
| 2 | small | 4.00 | CD12 |
| 2 | medium | 4.00 | CD13 |
| 2 | large | 3.50 | CD14 |
+------------+-----------------+-------+------+
```
But there must be a better, normalized, way of representing this data. Hypothetical situation: I want to be able to search for a blue product that is less than $10. With the above database structure it is not possible to do without parsing the text and that is something I want to avoid.
Any help/suggestions are appreciated =) | Applying normalization to your problem, the solution is as given. Run and see it on [SQL Fiddle](http://sqlfiddle.com/#!2/7fd9c/1).
```
CREATE TABLE products (
product_id int AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
description varchar(30)
);
INSERT INTO products
(name, description)
VALUES
('Rug', 'A cool rug' ),
('Cup', 'A coffee cup');
-- ========================================
CREATE TABLE variants (
variant_id int AUTO_INCREMENT PRIMARY KEY,
variant varchar(50)
);
INSERT INTO variants
(variant)
VALUES
('color'),
('material'),
('size');
-- ========================================
CREATE TABLE variant_value (
value_id int AUTO_INCREMENT PRIMARY KEY,
variant_id int,
value varchar(50)
);
INSERT INTO variant_value
(variant_id, value)
VALUES
(1, 'red'),
(1, 'blue'),
(1, 'green'),
(2, 'wool'),
(2, 'polyester'),
(3, 'small'),
(3, 'medium'),
(3, 'large');
-- ========================================
CREATE TABLE product_variants (
product_variants_id int AUTO_INCREMENT PRIMARY KEY,
product_id int,
productvariantname varchar(50),
sku varchar(50),
price float
);
INSERT INTO product_variants
(product_id, productvariantname, sku, price)
VALUES
(1, 'red-wool', 'a121', 50),
(1, 'red-polyester', 'a122', 50);
-- ========================================
CREATE TABLE product_details (
product_detail_id int AUTO_INCREMENT PRIMARY KEY,
product_variants_id int,
value_id int
);
INSERT INTO product_details
(product_variants_id, value_id)
VALUES
(1, 1),
(1, 4),
(2, 1),
(2, 5);
``` | Part of your issues stem from a confusion between product and SKU.
When you sell, "XYZ pullover, size M, blue model", the latter corresponds to an SKU. It is marketed as an XYZ pullover (the product), which has a set of attributes (size and colors), each with their own set of potential values. And not all possible combinations of the latter might yield valid deliverables: you won't find absurdly thin and long jeans. SKUs, products, attributes, attribute values.
And when a user wants a $10 blue pullover, he's actually looking for an SKU within a product category.
I hope the above clears up your confusion and where your problem and question stem from.
In terms of schema, you want something like this:
---
### products
* #product\_id
* name
* description
Optionally, also add:
* price
* in\_stock
This is a **marketing** related table. Nothing else. If *anything* outside of marketing uses a product in your application, you'll end up in a world of pain down the road.
The price, if present, is a master price used to populate the field when it's null in SKUs. This makes price entry more user-friendly.
in\_stock is a hopefully self-explanationary flag, ideally maintained by a trigger. It should be true if *any* SKU related to that product is in stock.
---
### product\_attributes
* product\_id
* #attribute\_id
* name
### product\_attribute\_values
* attribute\_id
* #value\_id
* value
This just holds things like Color, Size, etc., along with their values like blue, red, S, M, L.
Note the product\_id field: **create a new set of attributes and values per product**. Sizes change depending on the product. Sometimes it's S, M, L, etc.; other times, it'll be 38, 40, 42, and what not. Sometimes, Size is enough; other times, you need Width and Length. Blue might be a valid color for this product; another might offer Navy, Royal Blue, Teal and what not. Do NOT assume that there is any relationship between one product's attributes and those of another; the similarities, when they exist, are entirely cosmetic and coincidental.
---
### SKUs
* product\_id
* #sku\_id
* price
Optionally, add:
* name
* barcode
* stock
This corresponds to the deliverables that get shipped.
It's actually the most important table underneath. *This*, rather than the product\_id, is almost certainly what should get referenced in customer orders. It's also what should get referenced to for stock-keeping and so forth. (The only exception I've ever seen to the latter two points is when you sell something really generic. But even then, the better way to deal with this in my experience is to toss in an n-m relationship between interchangeable SKUs.)
The name field, if you add it, is primarily for convenience. If left null, use app-side code to make it correspond to the generic product's name, expanded if necessary with the relevant attribute names and values. Filling it allows to rephrase the latter generic name ("Levis' 501, W: 32, L: 32, Color: Dark Blue") with something more natural ("Levis' 501, 32x32, Dark Blue").
In case it matters, stock is better maintained using a trigger in the long run, with a double-entry bookkeeping schema in the background. This allows to distinguish between in stock and available for shipment today (which is the figure that you actually want here) vs in stock but already sold, among the multitudes of real-world scenarios that you'll encounter. Oh, and... it's occasionally a numeric, rather than an integer, if you ever need to sell anything measured in kilos or liters. If so, be sure to add an extra is\_int flag, to avoid customers sending you orders for .1 laptops.
---
### product\_variants
* product\_id
* #sku\_id
* #attribute\_id
* value\_id
This links the **deliverable**'s id with the corresponding attributes and values, for the sake of generating default names.
The primary key is on (sku\_id, attribute\_id).
You might find the product\_id field an aberrance. It is, unless you add foreign keys referencing:
* SKUs (product\_id, sku\_id)
* product\_attributes (product\_id, attribute\_id)
* product\_attribute\_values (attribute\_id, value\_id)
(Don't forget the extra unique indexes on the corresponding tuples if you decide to add these foreign keys.)
---
Three additional remarks in conclusion.
Firstly, I'd like to stress once again that, in terms of flow, not all combinations of attributes and values yield a valid deliverable. Width might be 28-42 and length might be 28-42, but you probably won't see a seriously skinny 28x42 jeans. You're best off NOT automatically populating every possible variation of every product by default: add UI to enable/disable them as needed, make it checked by default, alongside name, barcode and price fields. (Name and price will usually be left blank; but one day, you'll need to organize a sale on blue pullovers only, on grounds that the color is discontinued, while you continue to sell the other options.)
Secondly, keep in mind, if you ever need to additionally manage product options, that many actually are product attributes in disguise, and that those that aren't yield new SKUs that must also be taken into account when it comes to stock-keeping. A bigger HD option for a laptop, for instance, is really a variant of the same product (Normal vs Large HD size) that is masquerading as an option due to (very valid) UI considerations. In contrast, wrapping the laptop as a christmas gift is a genuine option that has references a completely separate SKU in bookkeeping terms (e.g. .8m of gift wrap) -- and, should you ever need to come up with average marginal costs, a fraction of staff time.
Lastly, you'll need to come up with an ordering method for your attributes, their values, and the subsequent variants. For this, the easiest is to toss in an extra position field in the attributes and values tables. | Designing a SQL schema for a combination of many-to-many relationship (variations of products) | [
"",
"sql",
"schema",
"e-commerce",
"database-schema",
"entity-attribute-value",
""
] |
I have 2 tables (AllClients & AllActivities) and need to retrieve the following information:
I need a list of clients where there are no associated activities.
Here are my tables with some fake data to help explain what I'm looking for:

I basically need the sql to retrieve Sam Johnson because there are no activities for him and he has a TypeCode of 'P'. | You don't necessarily need a join
```
select *
from AllClients c
where TypeCode = 'P'
and not exists (select 1 from AllActivities a where a.LookupCode = c.LookupCode)
``` | ```
select c.*
from AllClients c
left join AllActivities a on a.LoopupCode = c.LoopupCode
where a.LoopupCode is null
and c.TypeCode = 'P'
``` | Not sure which SQL join to use | [
"",
"mysql",
"sql",
"join",
""
] |
SQL is not my best thing but I have been trying to optimize this stored procedure. It had multiple scalar-valued functions that I tried to change to table-valued functions because I read in many places that it's a more efficient way of doing it. And now I have them made but not real sure how to implement or if I maybe just didn't create them correctly.
This is the function I'm calling.
```
Alter FUNCTION [IsNotSenateActivityTableValue]
(
@ActivityCode int,
@BillId int,
@TextToDisplay varchar(max)
)
returns @T table(result varchar(max))
as
begin
DECLARE @result varchar(max);
declare @countcodes int;
declare @ishousebill int;
select @ishousebill = count(billid)
from BillMaster
where BillID = @BillID and Chamber = 'H'
If (@ishousebill = 0)
begin
SELECT @countcodes = count([ActivityCode])
FROM [HouseCoreData].[dbo].[ActivityCode]
where ActivityDescription not like '%(H)%' and ActivityType = 'S'
and [ActivityCode] = @ActivityCode
if (@countcodes = 0)
begin
set @result = 'test'
end
else
begin
set @result = 'test2'
end
end
else
begin
set @result = @TextToDisplay
end
RETURN
END
```
And this is how I was trying to call them like this. I would prefer just being able to put them in the top but really anything that works would be good.
```
SELECT distinct
ActionDates.result as ActionDate
,ActivityDescriptions.result as ActivityDescription
FROM BillWebReporting.vwBillDetailWithSubjectIndex as vw
left outer join [BillWebReporting].[HasHouseSummary] as HasSummary on vw.BillID = HasSummary.BillID
outer APPLY dbo.IsNotSenateActivityDateTableValue(ActivityCode,vw.BillID,[ActionDate]) ActionDates
OUTER APPLY dbo.IsNotSenateActivityTableValue(ActivityCode,vw.BillID,[ActivityDescription]) as ActivityDescriptions
``` | Table-valued functions return a table, in which, like any other table, rows have to be inserted.
Instead of doing `set @result = .....`, do:
```
INSERT INTO @T (result) VALUES ( ..... )
```
**EDIT**: As a side note, I don't really understand the reason for this function to be table-valued. You are essentially returning *one* value. | Getting a count just to see if at least one row exists is *very* expensive. You should use `EXISTS` instead, which can potentially short circuit without materializing the entire count.
Here is a more efficient way using an inline table-valued function instead of a multi-statement table-valued function.
```
ALTER FUNCTION dbo.[IsNotSenateActivityTableValue] -- always use schema prefix!
(
@ActivityCode int,
@BillId int,
@TextToDisplay varchar(max)
)
RETURNS TABLE
AS
RETURN (SELECT result = CASE WHEN EXISTS
(SELECT 1 FROM dbo.BillMaster
WHERE BillID = @BillID AND Chamber = 'H'
) THEN @TextToDisplay ELSE CASE WHEN EXISTS
(SELECT 1 FROM [HouseCoreData].[dbo].[ActivityCode]
where ActivityDescription not like '%(H)%'
and ActivityType = 'S'
and [ActivityCode] = @ActivityCode
) THEN 'test2' ELSE 'test' END
END);
GO
```
Of course it could also just be a scalar UDF...
```
ALTER FUNCTION dbo.[IsNotSenateActivityScalar] -- always use schema prefix!
(
@ActivityCode int,
@BillId int,
@TextToDisplay varchar(max)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @result VARCHAR(MAX);
SELECT @result = CASE WHEN EXISTS
(SELECT 1 FROM dbo.BillMaster
WHERE BillID = @BillID AND Chamber = 'H'
) THEN @TextToDisplay ELSE CASE WHEN EXISTS
(SELECT 1 FROM [HouseCoreData].[dbo].[ActivityCode]
where ActivityDescription not like '%(H)%'
and ActivityType = 'S'
and [ActivityCode] = @ActivityCode
) THEN 'test2' ELSE 'test' END
END;
RETURN (@result);
END
GO
``` | SQL Table Valued Function in Select Statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Given the following table structure:
```
CREATE TABLE [dbo].[NodeTest] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[NodeCode] NVARCHAR (50) NOT NULL,
[ParentNodeCode] NVARCHAR (50) NULL,
[NodeName] NVARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
```
And the following data:
```
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0', null, 'ROOT')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('01', '0', '01')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('02', '0', '02')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('03', '0', '03')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('011', '01', '011')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('012', '01', '012')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('021', '02', '021')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('022', '02', '022')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('023', '02', '023')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('024', '02', '024')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('025', '02', '025')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('031', '03', '031')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('032', '03', '032')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0111', '011', '0111')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0112', '011', '0112')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0311', '031', '0311')
insert into NodeTest(NodeCode, ParentNodeCode, NodeName) values('0322', '032', '0322')
```
How can I write a view to list nodes with their all descendants? For example, for node 01 I will get:
```
01 011
01 012
01 0111
01 0112
```
Use this [SQLFiddle](http://sqlfiddle.com/#!3/d7eb0), which contains the table and information presented above. | Using a common table expression (CTE)
```
declare @parentCode varchar(20) = '01'
;with cte as
(
select * from NodeTest where ParentNodeCode = @parentCode
union all
select NodeTest.*
from NodeTest
inner join cte on cte.NodeCode = nodeTest.ParentNodeCode
)
select @parentCode, nodeCode from cte;
``` | Working [SQLFiddle](http://sqlfiddle.com/#!3/7826c/4)
I think you want this
```
with cte as
(
select * from NodeTest where ParentNodeCode = '01'
union all
select NodeTest.*
from NodeTest
inner join cte on cte.NodeCode = NodeTest.ParentNodeCode
)
select * from cte;
``` | How to get all descendants of a node | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
My query causes the following error:
> Msg 512, Level 16, State 1, Procedure Item\_insupd, Line 17
> Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Query:
```
INSERT INTO [Total_Database].[dbo].[Item]
(
ItemID,
ItemNo,
ItemDescription,
Notes,
StandardCost,
SalesGLAccountID,
ItemTypeID,
Backorderable
)
(
SELECT [nr],
[nr],
[Latijn]+' '+[Subgroep]+' '+CAST([nr] as VARCHAR(255)),
[NL]+' '+[Vorm]+' '+[Kenmerk]+' '+[Hoogte],[Inkoopprijs],
(4),
(case when [Productgroep]='PB' then 1 else 5 end),
(1)
FROM [ACCESDATA].[dbo].[Planten]
);
```
I suspect this to happen because my subquery does not contain a `WHERE`, unfortunately I do not know how to construct a correct `WHERE` clause. | I suspect the problem is in this string (line 26 in your [code](http://pastebin.com/trF85RHq)):
```
IF NOT (EXISTS (SELECT G.GLAccountID FROM GLAccnt G INNER JOIN Inserted I ON G.GLAccountID = I.SalesGLAccountID))
OR ((SELECT I.COGSGLAccountID FROM Inserted I) IS NOT NULL) AND NOT (EXISTS (SELECT G.GLAccountID FROM GLAccnt G INNER JOIN Inserted I ON G.GLAccountID = I.COGSGLAccountID))
```
It looks like `(SELECT I.COGSGLAccountID FROM Inserted I)` return more than one row, so you're getting an error.
You're treating `inserted` as a one row table (for example, you're getting parameters from it like `SELECT @ItemNo = I.ItemNo, @ItemDescription = I.ItemDescription FROM Inserted I`, but `inserted` table can have more than one row. So in your case I think you have 3 options - check that there's only 1 row in inserted, rewrite trigger as set-based, or use cursor.
Here's [sql fiddle](http://sqlfiddle.com/#!3/eec6d/6) with somewhat similar example. | If you really only want to insert one row, then You just add `Where` at the end, followed by some predicate (logical statement) that will be true for only one row in the table the query is reading from.
```
INSERT INTO [Total_Database].[dbo].[Item](ItemID,
ItemNo,ItemDescription,Notes,StandardCost,SalesGLAccountID,
ItemTypeID,Backorderable)
SELECT [nr],[nr],[Latijn]+' '+[Subgroep]+' '+CAST([nr] as VARCHAR(255)),
[NL]+' '+[Vorm]+' '+[Kenmerk]+' '+[Hoogte],[Inkoopprijs],(4),
(case when [Productgroep]='PB' then 1 else 5 end),(1)
FROM [ACCESDATA].[dbo].[Planten]
Where [SomeColumnName] = [some Value];
```
... but when performing an Insert using a select to generate the rows to be inserted, you just type the Select statement instead of the `Values()` clause, without surrounding parentheses. I think that because you had the surrounding parentheses, the query processor assumed you wanted that to be a single value. Do you want to only insert one row of data? or a whole set of data rows ? | SQL Subquery returned more than 1 value | [
"",
"sql",
"sql-server",
""
] |
suppose you have a data set having 3 columns: ID, user, date.
is it possible to filter the data based on the minimum date even if some of the rows have identical IDs?
sorry if the question is a bit unclear. hopefully the image below will help clear things.
there are two records having ID=1, with different users as well as dates. what i want to retrieve is the record having an ID=1, USER=A, DATE=2013-01-20 because its date is earlier than that of the second record (ID=1, USER=A, DATE=2013-01-21)
i want to achieve the same effect for the three records having an ID=2. the desired record is ID=2,USER=C,DATE=2013-10-20
basically i want to group these records by their IDs and then from that grouping, get the one with the lowest date
 | ```
SELECT id, user, date
FROM OriginalData od
WHERE date = (SELECT MIN(date)
FROM OriginalDate od1
WHERE od.id = od1.id)
``` | ```
Select * from table_name where date in
( select MIN(date) from table_name)
``` | group rows based on ID and then return the row with the lowest date per ID grouping | [
"",
"sql",
""
] |
In Ms Access i can create a query, called "CustomerList" with following datas:
```
CustomerName, City, Revenue
```
Then i can create another query, for instance "CustomerCount" like:
```
Select count(*) as Tot
from CustomerList ( <<<- is a query name)
where CustomerList.City
```
This query is based on another Query. Is it possible to do the same in MYSQL ?
Thanks | Yes, like this
```
Select count(*) as Tot
from
(
select City from some_table
) x
where x.City = 'NYC'
```
You have to alias subqueries. | You can create a `VIEW`
A `VIEW` works like a table but really is a select on one or more tables.
<http://dev.mysql.com/doc/refman/5.0/en/create-view.html> | Nested query in MySql | [
"",
"mysql",
"sql",
"ms-access",
""
] |
I have this query in PostgreSQL
```
SELECT numeric_value, entity_id
FROM data_value
WHERE
entity_id = 16029 OR
entity_id = 16026 OR
entity_id = 33768 AND
category_id = 158
```
The important thing to me is the numeric value, but I would like to display in this format:
```
16029 | 16026 | 33768
value | value | value
value | value | value
```
Is this possible somehow? Or it's effective? Because I have to work on a very slow server and I want to optimize as well as possible. | Have you missed parenthesis in your query, should it be something like this:
```
select
numeric_value, entity_id
from data_value
where
entity_id in (16029, 16026, 33768) and
category_id = 158
```
Anyway, you can easily pivot data by hand with aggregates (you just have to specify key if you want to get more than one row, it's not clear from your question how values should be grouped together):
```
select
--<some key>,
max(case when entity_id = 16029 then numeric_value end) as 16029,
max(case when entity_id = 16026 then numeric_value end) as 16026,
max(case when entity_id = 33768 then numeric_value end) as 33768
from data_value
where
entity_id in (16029, 16026, 33768) and
category_id = 158
--group by <some key>
``` | Should be possible to create that result using the [crosstab](http://www.postgresql.org/docs/9.1/static/tablefunc.html) function.
Not the easiest part of Postgres, so be prepared to spend some time reading the docs and experimenting :)
As I think it's not immediately obvious from the doc: tablefunc is the extension containing crosstab. Extensions are not installed by default, use [`CREATE EXTENSION`](http://www.postgresql.org/docs/9.1/static/sql-createextension.html) to install them. | sql columns by field value - is it possible? | [
"",
"sql",
"postgresql",
"calculated-columns",
""
] |
I have a table like this :
```
id | user_id | param_id | param_value
1 1 44 google
2 1 45 adTest
3 1 46 Campaign
4 1 47 null
5 1 48 null
6 2 44 google
7 2 45 adAnotherTest
8 2 46 Campaign2
9 2 47 null
10 2 48 null
```
I want to fetch all the user\_ids where (param\_id = 44 AND param\_value=google) AND (param\_id= 45 AND param\_value = adTest) . So the above where clause should give only user\_id = 1 and not user\_id = 2 . They both have google at param\_id 44 but only user 1 has param\_value adTest at param\_id = 45 .
The problem is the n the future more params could be added . I need to find a dynamic query . Here what i have tryed :
```
SELECT DISTINCT up.user_id FROM user_params AS up
LEFT JOIN user_params AS upp ON up.id = upp.id
WHERE up.param_id IN (?,?)
AND upp.param_value IN (?,?)
``` | ```
SELECT DISTINCT up.user_id
FROM user_params AS up
LEFT JOIN user_params AS upp ON up.id = upp.id
group by up.user_id
having sum(param_id = 44 AND param_value = 'google') >= 1
and sum(param_id = 45 AND param_value = 'adTest') >= 1
``` | Another way:
```
SELECT -- DISTINCT
up1.user_id
FROM
user_params AS up1
JOIN
user_params AS up2
ON up1.user_id = up2.user_id
WHERE
up1.param_id = 44 AND up1.param_value = 'google'
AND
up2.param_id = 45 AND up2.param_value = 'adTest' ;
```
You do not need the `DISTINCT`, if there is a `UNIQUE` constraint on `(user_id, param_id)`
For efficiency, add an index on `(param_id, param_value, user_id)`
---
The problem you are dealing with is called "Relational Division" and there is a great answer by @Erwin Brandstetter here: **[How to filter SQL results in a has-many-through relation](https://stackoverflow.com/questions/7364969/how-to-filter-sql-results-in-a-has-many-through-relation)**, with a lot of ways to write such a query, along with performance tests.
The tests were done in Postgres so some of the queries do not even run in MySQL but at least half of them do run and efficiency would be similar in many of them. | How to select distinct rows where 2 columns should match on multiple rows? | [
"",
"mysql",
"sql",
""
] |
I have the following SQL Server 2012 table:
```
create table dbo.Packs {
Id int identity not null,
Info nvarchar (200) not null
}
```
How can I get all rows where Info starts with "File" ... I might have:
```
"File #200 View", "File #100 Delete", "Stat F#20"
```
So I would get the first two records.
Thank You,
Miguel | You can use the [`LIKE` operator](http://technet.microsoft.com/en-us/library/ms179859.aspx) with the % wildcard:
```
SELECT [Id], [Info]
FROM [dbo].[Packs]
WHERE [Info] LIKE 'File%'
```
Example
```
CREATE TABLE packs ([Info] varchar(16));
INSERT INTO packs ([Info])
VALUES ('File #200 View'), ('File #100 Delete'), ('Stat F#20');
SELECT [Info] FROM [packs] WHERE [Info] LIKE 'File%';
```
Returns
```
| INFO |
|------------------|
| File #200 View |
| File #100 Delete |
```
[See a demo](http://sqlfiddle.com/#!3/689d5/1) | ```
SELECT Id,
Info
FROM Packs
WHERE Info LIKE 'File%'
``` | Read part of column value | [
"",
"sql",
"sql-server-2012",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.