Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
For Example: I have two tables
table agent

table application

1)
```
select a.agentID, agent_nm from agent a
left join application ap on (ap.agentID=a.agentID);
```
I am using Le... | Not much of a reason, really. In fact, MySQL docs say:
> `RIGHT JOIN` works analogously to `LEFT JOIN`. To keep code portable across databases, it is recommended that you use `LEFT JOIN` instead of `RIGHT JOIN`.
It's just an option you have, one few people exploit. | It's symmetric, LEFT and RIGHT outer joins are exchangeable. Most people use LEFT OUTER join because it's easier to think "main table" left join "additional data"... | What is reason of LEFT and Right join in SQL | [
"",
"mysql",
"sql",
"sql-server",
"database",
"join",
""
] |
I am trying to get a count on the number of times a number (`start_value`) doubles until it reaches a particular value (`end_value`) in the cleanest way possible. Consider the following example:
```
id start_value end_value
1 40 130
2 100 777
3 0.20 2.1
example 1... | You want logarithms for this. Specifically, the exact number of times is the log-of-base-2 of the ratio of the two values. You want the next higher integer, so you want to round this up.
In Postgres:
```
ceiling(log(2, end_value / start_value))
``` | Divide the end value by the start value to get the factor between them. For example 130/40 = 3.25. Doubling the value once gives a factor 2, and doubling it twice gives a factor 4, and so on.
You can use the logarithm for base 2 to calculate how many times you need to double the value to get a specific factor. log2(3.... | Get the count of numbers doubling using SQL? | [
"",
"sql",
"postgresql",
"logarithm",
""
] |
I have primary key unique column ID nchar(10). I'm planning to generate in it numeric ID. Incremental order is ok, but not necessary. How to make optimal generator for this reason? Should I use stored procedure? Maybe MS SQL server have any features for this reason? | DECLARE PkStudentid as INT
```
CREATE TABLE Student
(
Studentid int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
Firstname nvarchar (200) NULL,
Lastname nvarchar (200),
Email nvarchar (100) NULL
)
insert into Student (Firstname,Lastname,Email)
Values('Vivek', 'Johari', ‘vivekjohari@abc.com');
SET @PkStudentid = SCOPE... | **For primary key column you should have to use INT column with IDENTITY insert on.**
**Alternate solution:**
Still if you don't want to use INT data type then the alternate solution is create column with default value `LEFT(NEWID(), 10)` with UNIQUE/PRIMARY KEY on it. Because `NEWID()` function generates different r... | Generate unique value in MS SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"random",
"primary-key",
""
] |
Using PostgreSQL with pgAdmin, and was wondering if there is a way to search ALL of the functions of a database for a particular text.
Is this possible? | Something like this should work:
```
select proname, prosrc from pg_proc where prosrc like '%search text%';
```
see [How to display the function, procedure, triggers source code in postgresql?](https://stackoverflow.com/questions/6898453/how-to-display-the-function-procedure-triggers-source-code-in-postgresql) | If schema info is required too (we work with many):
```
select
nspname,
proname,
prosrc
from pg_catalog.pg_proc pr
join pg_catalog.pg_namespace ns on ns.oid = pr.pronamespace
where prosrc ilike '%search text%'
``` | Search text of all functions in PGAdmin | [
"",
"sql",
"postgresql",
"pgadmin",
""
] |
Consider this query:
```
select count(*) from
(
select pickle_id,
pickle_code
from pickles
where pickle_code='DILL'
group by pickle_id,
pickle_code /* Returns 1000 rows */
minus
select pickle_id,
pickle_code
from relish inner join pickles on relish_id=pickle_id
where relish_code ='BUR... | Try this
```
select pickle_id,
pickle_code
from pickles
where pickle_code='DILL'
group by pickle_id,
pickle_code /* Returns 1000 rows */
union all
(
select pickle_id,
pickle_code
from pickles
where pickle_code='DILL'
group by pickle_id,
pickle_code /* Returns 1000 rows */
int... | Hmmm, that would be everything before the `minus`:
```
select pickle_id, pickle_code
from pickles
where pickle_code = 'DILL'
group by pickle_id, pickle_code;
```
EDIT:
The answer to the question in the comments is:
```
select count(*)
from ((select pickle_id, pickle_code
from pickles
where pickle... | How can I include the subtracted rows from this query? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I want to merge the results from the following queries:
```
Dispenser.includes(:reviews).where.not(reviews: { id: nil })
```
and
```
Dispenser.includes(:dispenser_reviews).where.not(dispenser_reviews: { id: nil })
```
I have tried simply placing a `||` in the middle of these two queries, but that does not give the ... | You can accomplish that using <https://github.com/activerecord-hackery/squeel> rather than active record. It provides the more advanced functionality that Arel does not have out of the box.
That being said, your logic is gonna be pretty nasty. If you wanted to get the result set and you didn't mind two queries instead... | Joins will do an INNER JOIN and only return dispenser objects that have reviews or dispenser\_reviews. Pipe '|' will get rid of dups.
```
Dispenser.joins(:reviews) | Dispenser.joins(:dispenser_reviews)
```
or to get ids
```
Dispenser.joins(:reviews).pluck(:id) | Dispenser.joins(:dispenser_reviews).pluck(:id)
``` | Merge the results of two active record queries | [
"",
"sql",
"ruby-on-rails",
""
] |
I have two SQL Tables EmployeeMst and EmployeeCity
```
EmployeeMst
SrNo Name
1 abc
2 xyz
3 pqr
4 def
EmployeeCity
srno City EmplSrNo
1 Delhi 1,2,3,4
2 Mumbai 2,3,1
3 New York 3,2
```
i want to get Employee Name from EmployeeMst with select query
OUTPUT LIKE BELOW:
```
srno C... | I still think that regardless of whether or not the table is old or new, you should take the time to fix poor design sooner rather than later. You are only delaying the inevitable. As such here is something to get you started on a normalised design:
```
-- CREATE CITY TABLE
CREATE TABLE dbo.City
(
SrNo INT,
Ci... | Use this. **[Fiddler Demo](http://sqlfiddle.com/#!3/43e9ce/2)**
```
CREATE FUNCTION EmployeeName(@Expr1 AS VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @res AS VARCHAR(MAX)
SET @res = (SELECT ',' + B.name AS A FROM
(SELECT
Split.a.value('.', 'VARCHAR(100)')... | Replace comma separated values in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
i am trying to replace a day part in a date value. say for example
```
select TRUNC(SYSDATE) from dual;
```
Result: 28/11/2014
I wanted to replace only the 28 with another number value(X). So i can arrive the result like X/11/2014.
Can you please help me?
Thanks in Advance,
Murugan. | ```
trunc(sysdate,'MM') + (x-1)
```
would do it. `trunc(sysdate,'MM')` returns the first of the month. Then you add however many days you want to get the date that you want. | ```
SELECT TO_DATE('01' || SUBSTR(TO_CHAR(SYSDATE, 'DD/MM/YYYY'),3))
FROM DUAL
WHERE TO_CHAR(SYSDATE, 'DD') = '25';
``` | Replacing day part in Date with another number in PLSQL | [
"",
"sql",
"oracle",
"oracle11g",
"date-formatting",
""
] |
Have no idea why this does not work, but here you go.
```
update delievery
set status = 'delivered'
where order_num = 'a563'
and order_num = 'a109';
```
if I were to run this, I get 0 rows updated.
of course I could do this individually, but if I needed to update more than two things, that would not be very efficien... | You have written your query by using `AND` it simply means both the conditions written with it **must** be true. The condition here is `order_num = 'a563'` and `order_num = 'a109'`. Now if you have a look at your table you will see no row in your whole table where the column `order_num` will be having both the values `... | You need to use `OR`. `AND` requires both conditions to be met.
```
update delievery
set status = 'delivered'
where order_num = 'a563'
or order_num = 'a109';
```
You could also use `IN` like this:
```
update delievery
set status = 'delivered'
where order_num IN ('a563', 'a109');
``` | updating two or more values in a column in sql | [
"",
"mysql",
"sql",
""
] |
Suppose we have a query
```
SELECT * FROM my_table ORDER BY id
```
which results in
```
id | title
-----------
1 | 'ABC'
2 | 'DEF'
3 | 'GHI'
```
How could I modify given select statement to have each row duplicated in the result set like this:
```
id | title
-----------
1 | 'ABC'
1 | 'ABC'
2 | 'DEF'
2 | 'DE... | You could cross join to a row generator, the numeric value indicates how many duplicates per original you want.
```
select *
from my_table
cross join
(select null
from dual
connect by level <= 2)
order by id
``` | You can use `union all`, but I like using `cross join`:
```
select *
from MyTable cross join
(select 1 from dual union all select 2 from dual) n
order by id;
```
The reason I like the `cross join` is in the case where `MyTable` is really some complicated subquery. Although the query optimizer *might* evaluate it... | How to duplicate each row in sql query? | [
"",
"sql",
"oracle11g",
""
] |
1. I want to display only the data where the `RequestStatus_hod` is `IN PROCESS`
2. But the query seems to display all of the data by ignoring the where clause
3. As you can see, I've tried to repeat `WHERE RequestStatus_hod = 'IN PROCESS'` but it just displays as `NULL`
4. I've tried to use the temporary column `Reque... | One solution is to repeat the definition for your temporary column inside the `WHERE` clause. SQL Server doesn't support using an alias inside a `WHERE` directly, but it is still smart enough (in most cases) to figure out that the expression does not need to be evaluated twice. So, instead of writing `RequestStatus_hod... | Ok first of all, let's call things with their names, RequestStatus\_hods is not a "temporary column", it's a calculation placed in a column of the resultset of the query with an alias "RequestStatus\_hods".
I don't really understand those solutions involving CROSS JOINS, so I can't assess them, but I guess that perfor... | Is it possible to use temporary column in WHERE clause | [
"",
"sql",
"sql-server",
"t-sql",
"where-clause",
""
] |
I'm dealing with a table in which a bunch of arbitrary settings are stored as `VARCHAR(255)` values. The particular one I'm tasked with dealing with is a sequence number that needs to be incremented and returned to the caller. (Again, note that the sequence "number" is stored as `VARCHAR`, which is something I don't ha... | From one of the comments, sounds like you may have already hit on this, but here's what I would recommend:
```
UPDATE TABLE
SET VALUE = CAST((CAST(VALUE AS INT) + 1) AS VARCHAR)
OUTPUT inserted.VALUE
WHERE NAME = 'SOME_NAME'
```
This will output the new value like a `SELECT` statement does. You can also cast `insert... | Maintaining a sequential number manually is by no means a solution I'd like to work with, but I can understand there might be constraints around this.
If you break it down in to 2 steps, then you can work around the issue. Note I've replaced your `WHERE` clause for this example code to work:
```
CREATE TABLE #SOME_TA... | SQL - "incrementing" a char value causes collation error | [
"",
"sql",
"sql-server",
"sql-server-2008",
"collation",
""
] |
```
sel_prod_dt = "select distinct change_app_code, change_number "
& " \<cfif NDA_check eq "
&'"Y"'
&"> FROM db.tb tb"
&"\<cfelse\>FROM db.tb2 PC\<\/cfif\>"
```
i get the following error
**Syntax error, expected something like a name or a Unicode delimited identifier between ... | Why over complicate things?
```
<cfif NDA_check eq "Y">
sel_prod_dt = "select distinct change_app_code, change_number FROM db.tb tb"
<cfelse>
sel_prod_dt = "select distinct change_app_code, change_number FROM db.tb2 PC"
</cfif>
``` | One cannot add CFML to a string and them somehow expect it to run! Strings aren't processed until runtime, and the CFML code needs to be compiled before it'll run.
Reading this should clarify "[The ColdFusion request/response process](http://blog.adamcameron.me/2012/10/the-coldfusion-requestresponse-process.html)"
So... | how do i evaluate a cfif with a select statement in a string | [
"",
"sql",
"database",
"coldfusion",
"coldfusion-9",
"cfml",
""
] |
I have table named ct\_rt and there is one field ct. The data in the filed is following :
```
100
450
-20
500
300
-50
```
Now i want to get the following result :
```
100
550
530
1030
1330
1280
```
which is the addition of each row with its succeeding row. So how can I get the desired output ? I am using Oracle Dat... | This can be done using a window function with a "cumulative sum":
```
select ct,
sum(ct) over (order by some_column) as the_sum
from ct_rt
order by some_column;
```
You *have* to supply a column to sort the result. Rows in a relation database are ***not*** sorted and come in essentially a random order unless y... | Solution using a correlated subquery (you need an id field though)
```
SELECT (
SELECT sum(ct)
FROM ct_rt AS sub
WHERE sub.id <= qry.id
)
FROM ct_rt AS qry
ORDER BY qry.id
```
Edit:
This is an alternative solution.
The solution of a\_horse\_with\_no\_name will most propably outperform this. | How to perform vertical addition of column for each two rows in SQL? | [
"",
"sql",
"oracle",
""
] |
I was wondering if someone could cast their eye over the query I am trying to execute, I can't quite think on the best way to do it.
I need the Email, Firstname and Surname from the Contact table and the HotlineID and Last Action from the Hotline Table. I want to filter on 'flag' column stored in the Hotline table to ... | `MAX()` is an aggregate function of a group of rows. Its use would convert your ordinary query into an aggregate query if it appeared in the select list, which does not appear to be what you want. Evidently SQL Server will not accept it at all in your where clause.
It seems like you want something like this instead:
... | You can try this
```
Select Email, FirstName, Surname, hotline.HotlineID, LastAction
from Hotline
left join Contact on Contact.CompanyID=Hotline.CompanyID
and Contact.ContactID=Hotline.ContactID
inner join Actions on actions.HotlineID=hotline.HotlineID
where hotline.flag=1
and CONVERT(VARCHAR(2... | Joining tables then filtering on Max Date | [
"",
"sql",
"sql-server",
"join",
"maxdate",
""
] |
I have the below sql statement which sorts an address field (address1) using the street name not the number. This seems to work fine but I want the street names to appear alphabetically. The ASC at the end of order by doesnt help
e.g Address1 field might contain
"5 Elm Close" - a normal sort and order will sort by the ... | Try this: I based it off of Gordon's code, but altered it to remove the `LEFT(AddressLine1, 1`) portion - a single-character string could never be match the pattern "*n* + *space* + %".
This works on my SQL-Server 2012 environment:
```
WITH tbladdress AS
(
SELECT AddressLine1 FROM (VALUES ('1 Kings Road'),('10... | If you assume that the street name is the first or second value in a space separated string, you could try:
```
order by (case when left(tbladdress.AddressLine1, 1) like '[0-9]% %'
then substr(tbladdress.AddressLine1, charindex(' ', tbladdress.AddressLine1) + 1), len(tbladdress.AddressLine1) )
... | sort by second string in database field | [
"",
"sql",
"sql-server",
""
] |
There is a table `job` that contains data as shown below:
```
Id Status
-----------
1 NEW
2 NEW
```
There is a table `item` that contains data as shown below:
```
Id Status JobId
---------------------
1 NEW 1
2 PROCESSED 1
3 NEW 1
4 PROCESSED 2
5 PROCESSED 2
```
I want to... | ```
SELECT * from job where Id not in (SELECT JobId from item where Status <> 'PROCESSED');
```
This will return all from job where id is not in result of all jobids which have status different from 'PROCESSED'. | ```
SELECT j.* FROM Job j
WHERE not exists (select 1 from item i where i.JobId = j.id and i.Status != 'PROCESSED')
and exists (select 1 from item i where i.JobId = j.id and i.Status = 'PROCESSED')
and j.status = 'NEW';
```
Or
```
SELECT j.* FROM Job j
WHERE j.id in
(select jobId from (
select jobId,... | SQL: find all items on left side where right side items all have specific field value | [
"",
"mysql",
"sql",
""
] |
I have the following queries:
```
select year, avg(value) as winter_avg_Miami from AP_DATA where substring(series_id, 8) ='killowatts' and substring(series_id, 3,5) = 'Miami' and period IN ('M10','M11','M12') group by year;
select year, avg(value) as winter_avg_notMiami from AP_DATA where substring(series_id, 8) = 'k... | You can use a `case` statement in your `avg` aggregate:
```
select year,
avg(case when substring(series_id, 3,5) = 'Miami' then value end) as winter_avg_Miami,
avg(case when substring(series_id, 3,5) != 'Miami' then value end) as winter_avg_notMiami
from AP_DATA
where substring(series_id, 8) ='killowatts'
... | ```
select
year,
case when CntMiami = 0 then 0 else TotMiami / CntMiami end ) as AvgMiami,
case when CntNotMiami = 0 then 0 else TotNotMiami / CntNotMiamt end ) as AvgNotMiami
from
(
select
year,
sum( case when substring(series_id, 3,5) = 'Miami' then value else 0 end ) as TotMiami,
... | How do I include info from two queries in same resulting table? | [
"",
"mysql",
"sql",
"subquery",
""
] |
I want to do a group by on a dataset with a where clause based upon a `datetime`, but I need to return a count of 0 for any users in the `Account` table that do not meet the `where date` requirement. Here is my SQL statement:
```
select a.userid, count(c.codeentryid)
from [account] a
left join codesentered c
on a.user... | When you are using a `left join`, all conditions on the *second* table should go into the `on` clause. Otherwise, the outer join becomes an inner join. So, try this:
```
select a.userid, count(c.codeentryid)
from [account] a left join
codesentered c
on a.userid = c.userid and c.entrydate > '2013-12-03 00:00:... | You can include the condition in the `join`. Since it is a `left outer join`, it will always show all records from `account`, and only those of `codesentered` which match the condition:
```
select a.userid, count(c.codeentryid)
from [account] a
left outer join codesentered c
on a.userid = c.userid
/* here */ and c.... | Group By with Where | [
"",
"sql",
"t-sql",
""
] |
I am working on online and store ordering Pizza project. In this project I have two different databases one is the server where online ordered records will insert and another one is another server database which runs only in the stores.
My requirement is whenever any order is placed in the server database, then that s... | As an alternative to using Linked Servers as suggested elsewhere, there are various other options depending on your replication requirements:
* **Log shipping** Allows you to periodically send transaction logs from the primary server to one or more secondary servers. [More info](http://msdn.microsoft.com/en-us/library... | None of the other answers seem to have mentioned this enough but a key part of what you need is a ***trigger***.
A trigger allows you to update/insert multiple tables when a condition is met on your original table, in this case the condition would be ***inserted***
Couple this will a ***linked server*** and it should... | How to insert records into one server database when records inserted in the another SQL Server database | [
"",
"sql",
"sql-server",
""
] |
Query:
```
SELECT
dbo.tblDivision.DivisionName, dbo.tblDistrict.DistrictName,
case
when Gender = 'Male'
then count(Gender)
end as male,
case
when Gender = 'female'
then count(Gender)
end as female,
UnitEName
FROM
dbo.tblDistrict
INNER JOIN
dbo.tblThana ON dbo.... | If you want both genders in one row, you should not group by gender.
Instead you should add up how many male and how many female there are using sum():
```
SELECT dbo.tblDivision.DivisionName, dbo.tblDistrict.DistrictName,
SUM(case when Gender='Male' then 1 else 0 end) as male,
SUM(case when Gender='Female' then ... | You have to leave Gender column out of the grouping clause:
```
SELECT dbo.tblDivision.DivisionName, dbo.tblDistrict.DistrictName,
COUNT(CASE Gender WHEN 'Male' THEN 1 END) AS male,
COUNT(CASE Gender WHEN 'female' THEN 1 END) AS female,
UnitEName
FROM dbo.tblDistrict
INNER JOIN dbo.tblThana ON db... | How to use group by in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I want to print prime numbers between `1 to 50`. But I don't understand what I am doing wrong in my code. After `BEGIN`, SQLDeveloper says I had an error because it expected another sign and not `=` .
```
SET SERVEROUTPUT ON
DECLARE
i NUMBER;
counter NUMBER;
n NUMBER;
k NUMBER;
BEGIN
i := 2;
co... | ```
SET SERVEROUTPUT ON
DECLARE
i NUMBER;
counter NUMBER;
n NUMBER;
k NUMBER;
BEGIN
i := 2;
counter := 0;
n := 50;
k := floor(n/2);
FOR i IN 1..k LOOP
IF (mod(n, i) = 0 ) THEN
counter := 1;
END IF;
IF (counter = 0) THEN
DBMS_OUTPUT.PUT_... | In your IF clause you are assigning the value instead of comparison. You are using := operator, where you shd be using =
It shud be like (IF counter = 0) then
......
Also I dont think n%i would work, you could do IF (trunc(n) = n) then ... or IF (mod (n,i) =0) then ... | PLSQL Printing prime numbers | [
"",
"sql",
"oracle",
"plsql",
""
] |
Got some problem after using inner join, this is my query.
```
select sum(total) as total,id
from
(
select * from midsemester union
select * from endsemester
) as vij
group by id
```
This is the table:
**Table name: midsemester**
```
ID Grade
----------
1 10
2 30
3 40
```
**Table name: endsemester**
``... | try this
```
insert into total(ID,Grade) select midsemester.ID,(midsemester.grade+endsemester.grade)as total from midsemester
inner join endsemester
on midsemester.ID=endsemster.ID
```
Use order by ID if u want data according to ID increasing order | Try this:
```
INSERT INTO total (Id, Grade)
SELECT id, SUM(grade) AS total
FROM (SELECT id, grade FROM midsemester
UNION ALL
SELECT id, grade FROM endsemester
) AS vij
GROUP BY id
``` | Records gone after inner join | [
"",
"mysql",
"sql",
"sql-server",
"join",
"sum",
""
] |
I have to find out total number of saturday and sunday between Start Date & End Date.
Example #1:
```
StartDate = Getdate(), EndDate = GetDate() + 5 -- result should be 2.
```
Example #2:
```
StartDate = Getdate(), EndDate = GetDate() + 10 -- result should be 4.
```
Can anyone suggest please. | Here it is
```
DECLARE @STARTDATE DATE='01/JAN/2014'
DECLARE @ENDDATE DATE='01/MAR/2014'
;WITH CTE as
(
SELECT CAST(@STARTDATE AS DATE) as [DAYS]
UNION ALL
SELECT DATEADD(DAY,1,[DAYS]) [DAYS]
FROM CTE
WHERE [DAYS] < CAST(@ENDDATE AS DATE)
)
SELECT DISTINCT COUNT([DAYS]) OVER(PARTITION ... | Had the same question today. And I got here.
If you don't want to use recursion (CTE) or while. You can use math plus Case When:
```
DECLARE @StartDate AS DATE
DECLARE @EndDate AS DATE
SET @StartDate = Getdate()
SET @EndDate = GetDate() + 11
SELECT
-- Full WE (*2 to get num of days Sa and So)
((... | How do I get count of weekend days from a range of dates | [
"",
"sql",
"sql-server-2008",
"date",
"select",
"dayofweek",
""
] |
I was able to change all the other SQL syntax coloring in Eclipse Preferences, but the normal (non-Sql-syntactic) text is still black and I couldn't find where to find the setting for that. Black text is kind of hard to read against an almost black background. Thank you! | If you are looking for the place to change the Text Editor color settings, go to Preferences->General->Editors->Text Editors, select "Foreground color" in "Appearance color options", uncheck "System Default", click on the color and choose the color you want.
If you want to change the SQL Editor color settings, go to P... | [Alexis Dufrenoy](https://stackoverflow.com/users/505714/alexis-dufrenoy) is absolutely right:
> If you want to change the SQL Editor color settings, go to Preferences->Sata Management->SQL Development->SQL Editor->Syntax Coloring.
>
> Edit: You need to change the "Others" item in SQL Editor's syntax coloring. It's wo... | Eclipse SQL Editor normal text color | [
"",
"sql",
"eclipse",
"editor",
"settings",
"textcolor",
""
] |
Created database in cpanel > mysql database but when I am importing sql file in phpmyadmin I am getting this error
```
Error
SQL query:
--
-- Database: `alphanationalfire`
--
-- --------------------------------------------------------
--
-- Table structure for table `access`
--
CREATE TABLE IF NOT EXISTS `... | First of all create database in phpmyadmin. Then from the left panel select the database which you create. after opening the database then import your SQL file. | In order to add data to a database from a file you need to have created the databse first. In this case create alphanationalfire then select databse in phpmyadmin and import sql file. | created databse in mysql but not showing in phpmyadmin | [
"",
"mysql",
"sql",
"phpmyadmin",
"cpanel",
""
] |
I have on table:
```
Roll_No Subject Marks Percentage
1 Maths 75 70
1 Science 70 70
1 History 65 70
2 Maths 89 90
2 Science 91 90
2 History 90 90
3 Maths 50 55
3 Science 55 55
3 History 60 55
```
I want to get 2... | Something like that:
```
select roll_no, sum(marks), max(percentage)
from table
group by roll_no
```
To the second part of your question:
```
select count(roll_no), sum(marks), max(percentage)
from (select roll_no, sum(marks) as marks, max(percentage) as percentage
from table
group by roll_no)
``` | ```
select Roll_No,Sum(Marks),Max(Percentage) from table group by Roll_No;
with cte as
(
select Roll_No,Sum(Marks) as Marks ,Max(Percentage) as Percent from table group by Roll_No
)
select count(Roll_No),Sum(Marks),Sum(Percent) from cte;
``` | SQL query to get unique values from repeating rows | [
"",
"mysql",
"sql",
""
] |
i have a delete command:
```
DELETE FROM exam WHERE excode = '2';
```
But i need it to somehow reference another table and not delete it if the excode 2 exists in that table.
i have been looking at this:
<http://www.postgresql.org/docs/8.2/static/sql-delete.html>
and this looks like something close to what i need ... | Based on my understanding this is what you want:
```
DELETE FROM exam WHERE excode = '2' and not exists (select * from table2 where excode = '2')
```
The syntax is for SQL Server but I think you could use it with no change.
If this is not what you want, explain a bit more. | Yes you could very well do it by using a query like this ,taking first table as you mentioned as "exam(excode)" and second table as "excodeTable(excode)"
```
DELETE FROM exam
WHERE excode NOT IN(SELECT excode from excodeTable where excode='2')
```
If you want to check both the tables for the values i.e. excode=2 in ... | How do i put a condition on a delete command? | [
"",
"sql",
"postgresql",
"sql-delete",
""
] |
I want to convert a number to hours.. my code is doing that, but is not 100% right.
the number 2.98 is 2 hours and 0.98\*60 = 58,8 minutes.. I want round this minutes to 59
I want my result in my code +02:59, and it without this little round is +02:58.
Anyone knows how to round a time in my code?
```
DECLARE @number_... | If you want to round to the nearest minute, you need to round your fractional number of hours to the nearest minute first, so something like:
```
DECLARE @number_hours FLOAT = 2.98
--if number is negative
IF(@number_hours) < 0
BEGIN
SET @number_hours = @number_hours*-1
PRINT '-'+ CONVERT(varchar(5), CONVERT(D... | Also you can use this one :
```
DECLARE @number_hours FLOAT = 2.98
DECLARE @HOUR NUMERIC
DECLARE @MIN NUMERIC
DECLARE @FORIF FLOAT = @number_hours
SET @number_hours = CASE WHEN @number_hours<0 THEN @number_hours*-1 ELSE @number_hours END
SET @HOUR = ROUND(@number_hours,1)
SET @MIN = (1-(@HOUR-@number_hours))*60
IF... | convert a number to hours (ROUND issue) | [
"",
"sql",
"sql-server",
""
] |
I have two tables (Table1 - master table, Table2 - detail table). How can I select (view) only those records from master table that have no records in detail table? What SQL statement can I use for this? I'm using MS SQL Server 2012.
Edit: Table definition
Table1 - ID (PK)
Table2 - ID (PK), Table1ID (FK) | Use [**`NOT IN`**](http://msdn.microsoft.com/en-us/library/ms177682.aspx) Operator
```
SELECT *
FROM Table1
WHERE ID NOT IN(SELECT Table1ID
FROM Table2 )
``` | I would use `NOT EXISTS` since it's clear, efficient and has no issues with nullable columns.
For example (`MasterID` is the PK/FK):
```
SELECT master.*
FROM dbo.Table1 master
WHERE NOT EXISTS
(
SELECT 1 FROM Table2 detail
WHERE detail.MasterID = master.MasterID
)
```
But you have other options: <http://sqlp... | SQL - How to select master records that have no detail records? | [
"",
"sql",
"sql-server",
""
] |
Please consider the below example :
```
id name
1234 maria
1235 tamas
1236 helia
1234 maria
1235 jack
1235 david
```
What I want to do is to group the distinct value on the second column based on id :
```
id name id name id name
1234 maria 1235 tamas 1236 helia
... | `Distinct` keyword should solve the purpose:
```
declare @test table ( id int, name varchar(20))
insert into @test values
(1234,'maria'),
(1235,'tamas'),
(1236,'helia'),
(1234,'maria'),
(1235,'jack'),
(1235,'david')
select distinct id,name from @test
``` | this would give them in separate table, but @Deepshika solution is fine also.
```
DECLARE @ID INT
DECLARE @getID CURSOR
SET @getID = CURSOR FOR
select distinct id
from [work].[dbo].[FORM105]
order by id
OPEN @getID
FETCH NEXT
FROM @getID INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN
select distinct id,name
from [work].[db... | group distinct value on column two based on 1st column in sql server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"select",
""
] |
Hi I am writing my own MySQL query where I need a result of records as follows.
**Word in a table** - ABC XYZ
**My string** - ABC XYZQWER
when I ran my query as below -
```
SELECT * FROM myTABLE where `column` LIKE 'ABC XYZQWER%';
```
I am getting empty result. I am aware of the fact that MySQL LIKE matches the re... | You can use the function `LOCATE()`:
```
SELECT `column`
FROM myTable
WHERE LOCATE(`column`, 'ABC XYZQWER') = 1;
```
As long as there is a value `ABC XYZ` in the column named `column`, the result of the query will be at least:
```
+---------+
| column |
+---------+
| ABC XYZ |
+---------+
```
---
**Finding an in... | Try this:
```
SELECT * FROM myTABLE a WHERE 'ABC XYZQWER' LIKE CONCAT(a.column, '%');
``` | MySQL - Need search result of maximum matching letters from a string | [
"",
"mysql",
"sql",
"regex",
"select",
"sql-like",
""
] |
I want to fetch all the records on the basis of Search string
E.G.
Column name: `FileName`
```
MasterRoomTwo.jpg
BedRoom.png
MasterbedRoom.gif
```
and in simple scenario I can use
```
Declare @FileName nvarchar(60) = NULL
set @FileName = '.jpg'
SELECT *
FROM JobAttachment
WHERE AND Tags LIKE '%' + ISNULL(@Fil... | Try this. **Split the input string** and use `charindex`
```
SELECT 'MasterRoomTwo.jpg' a INTO #temp UNION
SELECT 'BedRoom.png' UNION
SELECT 'MasterbedRoom.gif'
DECLARE @FileName NVARCHAR(60)
SET @FileName = '.jpg,.Png,gif'
SELECT *
FROM #temp
JOIN (SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)'... | Try this :
```
SELECT *
FROM JobAttachment a
JOIN (SELECT t1.nod.value('.', 'varchar(50)') tags
FROM (SELECT Cast('<N>.'
+ Replace(Replace(@FileName, '.', ''), ',', '</N><N>.')
+ '</N>' AS XML) AS format) t
CR... | How to get all records on the basis of Search String In sql | [
"",
"sql",
"sql-server",
""
] |
I need to fetch specific row from DB2.
```
select istore,row_num() over() from store where row_num()=2;
```
so here i need to fetch 2nd row from store table but above query is not fetching any data.please help me.
Thanks in advance | You need to fetch it in a outer query like
```
select * from
(
select istore,
ROW_NUMBER() OVER (PARTITION BY some_column ORDER BY some_column) AS rn
from store
) tab
where rn = 2;
``` | You didn't specify what exactly your problem is, but there are two errors in your statement:
1. The window function is named `row_number()` not, `row_num()`
2. You can't use a window function in the where clause.
Using `row_number()` without any `order by` doesn't make sense, because you wind up with a random orderin... | how to extract specific row from db2 | [
"",
"sql",
"db2",
""
] |
## Question
How could I express the following statement in my query?
```
Between 4 and 5 years old
```
## SQL Query
```
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) <=2
```
Get all Assets that are more than one year old from todays date
## What I want to say?
Get all assets between 4 and 5 years old
--- | Be very careful using `datediff(year)`. It counts the number of year boundaries between two dates. So, the difference between 2014-12-31 and 2015-01-01 is 1.
In addition, I recommend putting the functions on the `getdate()` value rather than on the column. This allows an index to still be used on the column ("sargabil... | check for SQL's BETWEEN OPERATOR here
[SQL Between](http://www.w3schools.com/sql/sql_between.asp)
```
SELECT * FROM TABLE NAME WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) BETWEEN 4 and 5
``` | Expressing age between two years | [
"",
"sql",
"sql-server",
""
] |
I realize this is probably painfully simple. Just getting late and need an explanation.
I have the table:
```
mysql> SELECT * FROM employee_expert;
+------+---------+
| enum | package |
+------+---------+
| E246 | Excel |
| E246 | MySQL |
| E246 | Python |
| E246 | Word |
| E403 | Java |
| E403 | MySQL |... | One option is the `not in` operator:
```
SELECT DISTINCT enum
FROM employee_expert
WHERE enum NOT IN (SELECT enum
FROM employee_expert
WHERE package = 'Python')
``` | A `NOT IN` will exclude a subset of data with a specific exclusion criteria:
```
SELECT DISTINCT(enum)
FROM employee_expert
WHERE enum NOT IN
(SELECT enum FROM employee_expert WHERE package = 'Python');
```
`Distinct` will exclude duplicates. [Sql Fiddle here](http://sqlfiddle.com/#!2/3c65e2/2) | SQL find single value from duplicates with certain condition | [
"",
"mysql",
"sql",
""
] |
I have 2 Tables IlRoutes and PlRoutes and they both have a common RouteID.
```
IlRoute: PlRoute:
RouteID CID RouteID PlID Division
1 3 1 2 71
2 3 1 7 29
3 3 2 1 78
4 ... | Assuming I'm understanding your question correctly, you want to return any record that matches with `cid = 3` in the `IlRoute` table, and at least one record in the PlRoute table `plId = 7`.
First `join` the tables together, and then use `exists` to see if there is at least one record with plid = 7:
```
select i.rout... | ```
select
IlRoute.*, PlRoute.*
from
IlRoute
join
PlRoute
where
IlRoute.RouteID = PlRoute.RouteID
``` | sql query to get records based on 2 ID's | [
"",
"sql",
"sql-server-2008",
""
] |
In my `PostgreSQL 9.2` database there are many tables having name with mixed cases,For example
`Tbl_Sales`,`Tbl_Purch`,`Tbl_logMnth`
What I want to do is
```
alter table "Table1" rename to table1
```
but how to rename all mixed-case tables in my database in an easy way ? | Use the following select to get the table(s) with mixed-cases in name
```
SELECT table_name ucase,lower(table_name) lcase
FROM information_schema.tables
where table_type = 'BASE TABLE' and
table_schema = 'public' and
table_name ~ E'^[[:upper:]][^[:upper:]]'
```
PostgreSQL string function... | this is the query to use
> ALTER TABLE name
> RENAME TO new\_name | Rename mixed-case tables in a single query | [
"",
"sql",
"postgresql",
"ddl",
""
] |
have a table with duplicate data, I'm able to group email by using this query
```
SELECT id, first_name, email, status FROM customers WHERE status = '0' GROUP BY email
```
However, I don't want to select customer with duplicate emails that already have the status = '1'
Table design as follows...
```
id first_name... | Try this:
Using **LEFT JOIN**
```
SELECT c.id, c.first_name, c.email, c.status
FROM customers c
LEFT OUTER JOIN customers c1 ON c.email = c1.email AND c1.cstatus = 1
WHERE c.status = 0 AND c1.id IS NULL
GROUP BY c.email;
```
Using **NOT EXISTS**
```
SELECT c.id, c.first_name, c.email, c.status
FROM customers c
... | The simplest way to do it would be using `not exists`
```
select c.* from customers c where not exists
(
select 1 from customers c1
where c1.email = c.email
and c1.status = 1
)
``` | MySQL : Don't select duplicate row item when one of them has status = 1 | [
"",
"mysql",
"sql",
"select",
"duplicates",
"exists",
""
] |
I have a table with 2 fields: TimeStamp (date & time) and Value (numeric).
I'd need an (efficient) query to find those rows where the Value field is smaller from the previous row, being them sorted by TimeStamp. I provide a small set of data as an example:
```
Timestamp Value
------------- -... | In SQL Server 2012+, you would use `lag()`:
```
insert into othertable(col1 . . . )
select t.*
from (select t.*, lag(value) over (order by timestamp) as prev_value
from table t
) t
where value < prev_value;
```
For performance, you want an index on `table(timestamp, value)`.
In earlier... | I never thought of correlated subqueries. I think this would work for me:
```
SELECT
t.TimeStamp,
t.Valor
FROM
Tabla1 AS t
WHERE
t.Valor <
(
SELECT TOP 1
t2.Valor
FROM
Tabla1 AS t2
WHERE
t2.TimeStamp < t.TimeStamp
ORDER BY
... | Compare data in consecutive rows | [
"",
"sql",
"sql-server",
""
] |
Here are my two tables:
**oasis**
```
+-----+-------+
| id | title |
+-------------+
| 234 | a |
| 235 | b |
| 236 | c |
+-----+-------+
```
**user\_collection**
```
+----+---------+----------+------+
| id | oasisid | username | data |
+--------------+----------+------+
| 1 | 234 | joe | ... | You want a `left join`, but you have to be careful about the conditions in the `where` clause. Conditions on the *second* table need to be in the `on` clause for the `left join` to work:
```
SELECT *
FROM oasis JOIN
user_collection
ON oasis.id = user_collection.oasisid and user_collection.username = 'greg'
W... | ```
SELECT s.ome
, c.olumns
FROM table1 s
LEFT
JOIN table2 c
ON c.some_id = s.some_id
AND c.some_column = 'one thing'
WHERE s.some_other_column = 'another thing'
``` | How do I always pull data from one table, but also pull data from a second table if it's there in MySQL? | [
"",
"mysql",
"sql",
""
] |
I have the following table (this is just a sample):
```
id User dateAssigned dateComment
---|-------|---------------------|---------------------|
1 | Usr1 | 2014-12-02 12:35:00 | 2014-12-03 08:13:00 |
2 | Usr1 | 2014-12-02 12:35:00 | 2014-12-02 13:06:00 |
3 | Usr2 | 2014-12-02 07:47:00 | 2014-12-02 ... | You could use a `CTE`(Common Table Expression) and [`ROW_NUMBER` function](http://msdn.microsoft.com/en-us/library/ms186734.aspx):
```
WITH CTE AS
(
SELECT id, [User], dateAssigned, dateComment,
rn = ROW_NUMBER() OVER (
PARTITION BY [User]
ORDER BY ABS(DATEDI... | Use this:
```
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Username
ORDER BY ABS(DATEDIFF(second, dateComment, dateAssigned)) ASC) AS datesOrder
FROM @T ) t
WHERE t.datesOrder = 1
```
Row number is equal to 1 for those records corresponding to the minimum difference. ... | Get Rows Where Difference Between Two Date Columns is Minimum | [
"",
"sql",
"sql-server",
""
] |
I have a table with some columns .. say A,B & C and a last column called DeletedDate. Its a nullable datetime.
I have added a unique constraint on A,B & C. Its worked fine until I discovered an issue. After adding a deleted date. I should be able to add a new records for same A,B & C values. But I cant because of the ... | Option 2: a unique constraint cannot have a `WHERE` clause. But you can use a **[filtered index](http://msdn.microsoft.com/en-gb/library/cc280372.aspx)** instead:
```
CREATE UNIQUE INDEX a_b_c_UQ_when_DeletedDate_is_null
ON TableName
(a, b, c)
WHERE DeletedDate IS NULL ;
```
---
Option 1: if you simply include th... | You could use a computed column for the unique index. This returns a static value like `1` if `DeletedDate` is available and otherwise the negative counterpart of the primary key.
```
CREATE TABLE [dbo].[Test](
[ID] [int] IDENTITY(1,1) NOT NULL,
[A] [int] NOT NULL,
[B] [int] NOT NULL,
[C] [int] NOT NUL... | Would adding a where clause be a good idea here? | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
This is my result :
```
Year matches
2005 1
2008 2
```
and this is my expected result:
```
Year matches
2005 1
2006 0
2007 0
2008 2
```
This is what I have tried:
```
SELECT DATEPART(yy,A.match_date) AS [Year], COUNT(A.match_id) AS "matches"
FROM match_record A
INNER JOIN match_record B ON... | This might do what you're looking for:
```
SELECT DATEPART(yy,A.match_date) AS [Year],
SUM(CASE WHEN score=0 or score is null THEN 1 ELSE 0 END) AS "matches"
FROM match_record A
INNER JOIN match_record B ON A.match_id = B.match_id
GROUP BY DATEPART(yy,A.match_date);
```
Assuming you have *any* data in the missin... | Consider following is your table
```
SELECT * INTO #TEMP FROM
(
SELECT 2005 [YEARS],1 [MATCHES]
UNION ALL
SELECT 2008,2
)T
```
Declare two variables to get min and max date in your table
```
DECLARE @MINYEAR int;
DECLARE @MAXYEAR int;
SELECT @MINYEAR = MIN(YEARS) FROM #TEMP
SELECT @MAXYEAR = MAX(YEARS) F... | Show 0 in count SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
How can I sort a table by a column varchar2 with characters in varying cases: upper, lower, numeric string
For example, when I do an order by the column NAME, the data of the column are:
```
ANNIE
BOB
Daniel
annie
bob
1abc
```
The expected result is:
```
1abc
ANNIE
annie
BOB
bob
Daniel
``` | This is complicated. Normal sort order is aa, aA, Aa, AA, ab, aB, Ab, AB, a1, A1, 1a, 1A. So same names are grouped together and then lower case comes first. Digits come after Z.
This is close to what you are after. You want Ben to come before BOB, because you care about BEN being before BOB in the first place and onl... | You could do something like:
```
SELECT *
FROM MyTable
ORDER BY UPPER(MyCol)
``` | How can I sort a table by a column for numeric letter first, then case sensitive for alphabet letters | [
"",
"sql",
"select",
"oracle11g",
"sql-order-by",
"nls-sort",
""
] |
I need to create a T-SQL query that will return the highest salary from the `job_positions` table and the name of the person(s) who has it.
So far, my solution is:
```
SELECT
MAX(e.salary) AS [Max salary]
, p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM
persons p
JOIN
job_positions e ON (p... | If **only one** employee who can get `Max salary` then try this.
```
SELECT TOP 1 e.salary AS [Max salary],
p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM persons p
JOIN job_positions e
ON ( p.id_person = e.id_person )
ORDER BY e.salary DESC
```
If **more ... | Finally found a solution that isn't totally ugly:
```
SELECT
MAX(e.salary) AS [Max salary]
, p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM
persons p
JOIN
job_positions e ON (p.id_person=e.id_person)
WHERE
e.salary=(SELECT max(e.salary) FROM e.job_positions)
```
But I still wonder why ... | Select MAX() causes error message | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
so I have been wrestling a perplexing issue with BULK INSERT for some time. The files come from a Linux box and when I look at them in hex edit mode/notepad ++ they appear to have just a linefeed (0A) as a row terminator. I store bulk insert statements in a table which later a job selects from and executes the statemen... | The issue you are having is actually not due to the Row Terminator. I suspect, along with the End of File error, you also saw something similar to the following:
> Msg 4864, Level 16, State 1, Line 1
> Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4... | I'd comment to ask these but my reputation is not high enough.
I believe "\l" is "linefeed", so that would mesh with you seeing 0A in the file encoding.
My first question would be, what character encoding is your data files in? And what is the datatype on your table columns?
I would guess that this is going to be a ... | Bulk Insert - Row Terminator for UNIX file + "\l" row terminator | [
"",
"sql",
"sql-server-2008-r2",
"bulkinsert",
""
] |
I want to reduce my data frame (**EDIT:** in a cpu-efficient way) to rows with unique values of the pair c3, c4, while keeping all columns. In other words I want to transform my data frame
```
> df <- data.frame(c1=seq(7), c2=seq(4, 10), c3=c("A", "B", "B", "C", "B", "A", "A"), c4=c(1, 2, 3, 3, 2, 2, 1))
c1 c2 c3 c4... | Here is a data.table solution.
```
library(data.table)
setkey(setDT(df),c3,c4) # convert df to a data.table and set the keys.
df[,.SD[1],by=list(c3,c4)]
# c3 c4 c1 c2
# 1: A 1 1 4
# 2: A 2 6 9
# 3: B 2 2 5
# 4: B 3 3 6
# 5: C 3 4 7
```
The SQL you propose seems to extract the first row having... | Drawback (maybe): All solutions sort the result by group variables.
# Using `aggregate`
Solution mentioned by Martin: `aggregate(. ~ c3 + c4, df, head, 1)`
My old solution:
```
> aggregate(df,by=list(df$c3,df$c4),FUN=head,1)
Group.1 Group.2 c1 c2 c3 c4
1 A 1 1 4 A 1
2 A 2 6 9 A 2
3... | What is the R equivalent of SQL "SELECT * FROM table GROUP BY c1, c2"? | [
"",
"sql",
"r",
"data.table",
"aggregate",
""
] |
This seems to be easy in my head but I can't figure how to write the query:
What I have:
```
user_id correct_questions
1 5
1 2
2 3
2 1
```
What I want to have:
```
user_id correct_questions(sum)
1 ... | Well only thing you have to do is SUM + group by :
```
select user_id, SUM(correct_questions) as correct_questions
from yourtable
Group by user_id
``` | ```
select sum(correct_questions) from table_name group by user_id
``` | SQL Query to count(x) and group by y | [
"",
"mysql",
"sql",
""
] |
After reading many tutorials, I found that there are many ways to bind arguments on prepared statement in Go, some of them
```
SELECT * FROM bla WHERE x = ?col1 AND y = ?col2
SELECT * FROM bla WHERE x = ? AND y = ?
SELECT * FROM bla WHERE x = :col1 AND y = :col2
SELECT * FROM bla WHERE x = $1 AND y = $2
```
**First q... | **What is the cross-database way to bind arguments?**
With database/sql, there is none. Each database has its own way to represent parameter placeholders. The Go database/sql package does not provide any normalization facility for the prepared statements. Prepared statement texts are just passed to the underlying driv... | I'm a newbie to Go but just to answer the first part:
> First question, what is the cross-database way to bind arguments? (that works on any database)
If you use [sqlx](https://godoc.org/github.com/jmoiron/sqlx), which is a superset of the built-in sql package, then you should be able to use [sqlx.DB.Rebind](https://... | Cross-database prepared statement binding (like and where in) in Golang | [
"",
"sql",
"go",
"prepared-statement",
"sql-like",
"where-in",
""
] |
I have a following stored procedure. I have variable `@PercentCleared` .
`IF @PercentCleared <= 70` then I have to subtract `PercentCleared-10` else use as it is. Can you please advise me the right way to do?
```
DECLARE @PercentCleared INT
DECLARE @TenPercent int
SET @TenPercent = 10
IF(@PercentCle... | I think you can do this by using a CASE statement in the WHERE clause
```
SELECT @I, dbo.tblV.VegTypeCode, dbo.tblV.VegTypeName FROM dbo.tblVegetationType
INNER JOIN dbo.tblVegFormationLink
ON dbo.tblV.VegTypeID = dbo.tblVegFormationLink.VegTypeID
WHERE dbo.tblVegetationType.PercentageCleared
>= @PercentCl... | You can put the logic in the `where` clause.
```
SELECT @I, dbo.tblV.VegTypeCode, vt.VegTypeName
FROM dbo.tblVegetationType vt INNER JOIN
dbo.tblVegFormationLink vfl
ON vt.VegTypeID = vlt.VegTypeID
WHERE (vt.PercentageCleared >= @PercentCleared - (CASE WHEN @PercentCleared <= 70 THEN @TenPercent ELSE 0 END)... | Any other way to avoid if else condition | [
"",
"sql",
"sql-server",
""
] |
This function is based on a Oracle PL/SQL Function:
```
create or replace FUNCTION SP_ComputeEntity (P_ENTITY NUMERIC, P_CAMPAIGN NUMERIC, P_COMPLETE_IF NUMERIC, P_COMPUTE_MODE NUMERIC ) RETURNS VOID AS $$
DECLARE
[..]
-- This is the list of the entity's subordinates
[..]
-- This is the list of the entity'... | If you don't need a result from the query, you can use [Perform](http://www.postgresql.org/docs/9.1/static/plpgsql-statements.html)
```
PERFORM SP_ComputeEntity(V_COLUMN_ID, P_CAMPAIGN, P_COMPLETE_IF, P_COMPUTE_MODE);
``` | You can also use your function just like a select and retrive results in variables.
Just for example:
```
SELECT INTO myvar myres FROM myfunction(param1, param2);
``` | How do I call a function inside a function | [
"",
"sql",
"oracle",
"postgresql",
""
] |
I normally don't do database programming so Im rusty on how to do certain stuff. But I have an issue where I'm to take an item and if this item is in the same location but in different placements, divide the value of said item among the sum count between placements.
here is my table structure:
```
LOCATION PLACEMEN... | ```
create table new as
select item,count(distinct placement) as dist_placement,count(count)as count,sum(count) as s_count
from mytable
group by item,location;
hive> select * from new;
OK
00000 1 1 5
11111 1 1 5
55555 2 2 30
Create table final as
select b.location as location,b.placement as place... | Your sample table
```
SELECT * INTO #TEMP FROM
(
SELECT 25 LOCATION,12345 PLACEMENT,100 VALUE ,10 [COUNT], 55555 ITEM
UNION ALL
SELECT 25 , 67890 , 100 , 20,55555
UNION ALL
SELECT 25 , 11111 , 50 , 5,00000
UNION ALL
SELECT 25 , ... | SQL - Function to divide value among rows | [
"",
"sql",
"hive",
"hql",
""
] |
I have a question regarding coldfusion and loops. I have this program where I ask for user input from the user. The user can enter something for each food item.
```
<cfloop query = "GET_ITEM">
<tr>
<td align="left" nowrap>
<label>#GET_ITEM.ITEM_NBR#</label>
</td>
<input type="hi... | In your first loop try this:
```
<cfloop query = "GET_ITEM">
<tr>
<td align="left" nowrap>
<label>#GET_ITEM.ITEM_NBR#</label>
</td>
<input type="hidden" name="Item_number" id="Item_number"
value="#GET_ITEM.ITEM_NBR#">
<td>
<input type="text" ... | Issue one, how to make things unique, you have most of it down pat but if you do this:
```
<cfset x = 0>
<cfloop query="GET_ITEM">
<cfset x++>
<input name="uniqueID_#x#" value="#x#" type="hidden">
<tr>
<td align="left" nowrap>
<label>#ITEM_NBR#</label>
</td>
<input type="hidden" name="Item_num... | Coldfusion Loop for insert | [
"",
"mysql",
"sql",
"coldfusion",
""
] |
My query:
```
SELECT id, pl, ka, user, users.imie, users.id, users.nazwisko, users.klasa
FROM word
LEFT JOIN users ON word.user = users.id BY word.pl ASC
```
It gives me this error:
```
#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the rig... | Missing `Order` in `Order By`
ALSO Both tables have an `id` column, so you need to call either/both `users.id` and `word.id` to avoid the ambiguous error:
```
SELECT users.id, word.id, pl, ka, user, users.imie, users.id, users.nazwisko, users.klasa
FROM word
LEFT JOIN users ON word.user = users.id
ORDER BY word.pl... | You forgot ORDER:
```
ORDER BY word.pl ASC
``` | #1064 - check the manual that corresponds to your MySQL server version for the right syntax to use near 'BY word.pl ASC LIMIT 0, 30' at line 1 | [
"",
"mysql",
"sql",
""
] |
umm I'm not sure I've made the title right but its kind of hard to express it in short words.
I have to tables
**table1:**
```
id | name
1 | alice
2 | bob
```
**table 2:**
```
user_id | date
2 | 2014-11-1
2 | 2014-11-2
1 | 2014-11-3
```
as a query, if I want to show `table... | A query along the lines of -
```
select t1.name, t2.date
from table_1 t1 inner join table_2 t2 on t1.id = t2.user_id
``` | Try:
```
SELECT t2.user_id, t1.name
FROM table1 t1 INNER JOIN table2 t2
ON t1.id = t2.user_id
``` | how to make query show the an other column of the primary key? | [
"",
"mysql",
"sql",
""
] |
I am currently trying to join on the same table twice.
I have a table that looks similar to below:
Trip:
```
arrival_loc_code
leaving_loc_code
```
There is another table with the values for those locations:
Locations:
```
location_code (pk)
location
```
I am attempting to to get the location of arrival and leavi... | You have aliased your tables but then not used the alias in the join clause, so mysql is getting confused:
```
select leavingloc.location, arrivalloc.location from trip
join locations as leavingloc on trip.departureloccode = leavingloc.locationcode
join locations as arrivalloc on trip.arrivalloccode = arriva... | This is because the name of your alisas is different to what you are using.
change
```
join locations as leavingloc on trip.departureloccode = locations.locationcode
join locations as arrivalloc on trip.arrivalloccode = locations.locationcode;
```
To
```
join locations as leavingloc on trip.departureloccod... | MySQL Join Unknown column in 'on clause' | [
"",
"mysql",
"sql",
"join",
""
] |
I have a table that has multiple duplicate records in the first column (ID records), but has varying numerical data in the second column.
I want to be able to identify which ID records have 0 for all of their numerical records.
For example the table can look like:
```
ID Value
1 2
1 2
1 0
2 0
2 0
2 0
`... | ```
SELECT DISTINCT ID FROM TABLE
WHERE ID NOT IN (SELECT DISTINCT ID FROM TABLE WHERE VALUE <> 0)
```
This will take all ID in the table where there is not a row where the value is non-zero. | You might use "NOT IN":
```
SELECT DISTINCT Id
FROM table1
WHERE Id NOT IN (SELECT Id FROM table1 WHERE Value <> 0)
``` | How to SQL Query records from Multiple that Equal 0? | [
"",
"sql",
"duplicates",
""
] |
Hi We are working on a project and i am trying to call a stored procedure. I have searched for the solution but i didn't find any way that how to call a stored procedure so can any one please tell me how to execute stored procedure. | How ever finally i am using the below code to execute the stored procedure and get the result.
```
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
{
// temporary scope for new connection and setting stored procedure, parameters, and return RecordName list ... | actually, I don't know about stored procedures, but you can call stored functions using code like examaple below. I'm new to C# and orchard, so may be my approach is not correct and good enough. At first you should get `ISessionLocator` object instance, using `IOrchardServices`, then create NHibernate `ISession` instan... | Stored Procedure in Orchard | [
"",
"sql",
"orchardcms",
""
] |
I'm trying to make an eCommerce web site. And at `ProductCategory` page I have to do a list about `Companies` that included by `Products`.
I have a `Product` table that contains:
```
ProductID
ProductName
...
MarkID
```
And I have a `Company` table that contains:
```
CompanyID
CompanyName
```
I want to mix them in... | This can be achieved without a subquery.
```
SELECT C.CompanyID, C.CompanyName, COUNT(*)
FROM Products P INNER JOIN Companies C ON P.CompanyId = C.CompanyID
GROUP BY C.CompanyID, C.CompanyName
``` | With a subquery:
```
SELECT * FROM
(
SELECT CompanyID, count(CompanyID) as CompanyCount
FROM Products
GROUP by CompanyID
) CompanyCounts
INNER JOIN Companies
on CompanyCounts.CompanyId = Companies.CompanyID
```
If you need this in more places, you may want to create a view for company count. | SQL Server inner join after Count and GroupBy | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I've got a import process that copies a table schema with the code below and then populates the table with data. However it doesn't copy over the roles granted.
```
CREATE TABLE TOTABLE (LIKE FROMTABLE INCLUDING INDEXES)
```
Is there a way I can copy privileges when the schema is copied, or I can apply the privileges... | Information about tables in postgresql are stored in the `pg_class` table. The field containing table privileges is `relacl`.
So something like the following would work:
`update pg_class set relacl = (select relacl from pg_class where relname = 'from_table') where relname='to_table';`
Note that `pg_class` has metada... | Be ***very careful*** when manipulating catalog tables directly. It's generally advisable to use DDL statements exclusively. Catalog tables are not meant to be written by users. If you mess this up, your DB cluster might be corrupted beyond repair. You have been warned.
**Update**: Turns out, the above warning is quit... | Can you copy table privileges from one table to another in PostgreSQL? | [
"",
"sql",
"postgresql",
"privileges",
""
] |
I tried like this
This is my Query
```
SELECT sloat_day, sloat_start_time
FROM time_table
WHERE sloat_day BETWEEN '2014-12-01' AND '2014-12-07'
ORDER BY sloat_day, sloat_start_time ASC
```
I got below output
```
sloat_day sloat_start_time
2014-12-01 6.30
2014-12-01 7.30
2014-12-01 18.30
2014-12-01 19.30
201... | Try this:
```
SELECT sloat_day, sloat_start_time
FROM (SELECT sloat_day, sloat_start_time,
IF(@day=@day:=sloat_day, @id:=@id+1, @id:=1) rank
FROM time_table, (SELECT @id:=0, @day:='') AS a
WHERE sloat_day BETWEEN '2014-12-01' AND '2014-12-07'
ORDER BY sloat_day, sloat_start_time
... | Change the order of the columns in the ORDER clausule, like this.
```
SELECT sloat_day, sloat_start_time
FROM time_table
WHERE sloat_day BETWEEN '2014-12-01' AND '2014-12-07'
ORDER BY sloat_start_time, sloat_day ASC
```
This way, the query will be ordered first by sloat\_start\_time. | Mysql query result date time wise | [
"",
"mysql",
"sql",
"date",
"select",
"sql-order-by",
""
] |
I have the following data:
```
tag_id | taggable_id
--------+-------------
1 | 1
2 | 1
3 | 1
4 | 1
1 | 2
2 | 2
5 | 2
6 | 2
7 | 3
8 | 3
9 | 3
... | This can be cast as a case of **[relational division](https://stackoverflow.com/tags/relational-division/info)**. We have assembled an arsenal of query techniques under this related question:
* [How to filter SQL results in a has-many-through relation](https://stackoverflow.com/questions/7364969/how-to-filter-sql-resu... | [SQL Fiddle](http://sqlfiddle.com/#!15/3cb07/1)
Your second query fails if the tuple `(8, 2)` is inserted. Here is one solution although I don't know if simpler then the `intersect` one:
```
select taggable_id
from taggings
where tag_id in (1,2,6,8)
group by taggable_id
having
array_agg(tag_id) @> array[1,2]
... | Simplify and/or optimize sql query with INTERSECT or HAVING | [
"",
"sql",
"postgresql",
"relational-division",
""
] |
I've seen this question asked in many ways all over the Internet but despite implementing the abundance of advice (and some voodoo), I'm still struggling. I have a 100GB+ database that is constantly inserting and updating records in very large transactions (200+ statements per trans). After a system restart, the perfor... | In the end, what I did was a combination of two things, putting in logic to recover when timeouts occurred, and setting the host core count to only reflect physical cores, not logical cores, so for example, the host has 2 cores that are hyper-threaded. When I set my VM to use 4 cores, it occasionally gets hung in some ... | * Depending on how large your hot set is, 5GB memory may just tax it for a 100+gb database.
* Check indices and query plans. We can not help you without them. And I bet you miss some indices - which is the standard performance issue people have.
* Otherwise, once you made your homework - head over to dba.stackexchange.... | SQL Server query performance slows over time | [
"",
"sql",
"sql-server",
"performance",
""
] |
I have in a column in SQL a field that concatenates products a given user has reviewed. It's stored in the form "SKU1,SKU2,SKU3,...". An example string would be "1,2,4,6,13,15,16".
I want to view all rows containing '6' in this column. I'd use LIKE, but then it gets 16, 26, 36, etc as well.
```
SELECT rows
FROM t... | You have made a fundamental mistake in the design of the database. The correct solution is to replace the column `column` with a separate table. This table will have two columns, the user ID and the product ID and will have one separate row for each product a user has reviewed. It then becomes quite easy to get the inf... | This where condition would give you the result you're looking for.
```
mycolumn like "%,6,%" or mycolumn like '6,%' or mycolumn like '%,6'
```
Here' I'm using the fact that commas would appear on either side of 6, except if the 6 comes at the start or end of the string. | SQL LIKE exclusive substring | [
"",
"sql",
"database",
"sql-like",
""
] |
I have a MySql table and it has following values:
table name 'results'
```
Reg.No SubjectCode Attempt Pass/Fail
112108 CMIS 1113 1 fail
112110 CMIS 1114 1 pass
112119 CMIS 1114 1 fail
112108 CMIS 1113 2 fail
112107 CMIS 1113 1 fail
112108 CMIS 1113 3 ... | I would suggest using aggregation:
```
SELECT `Reg.No`, SubjectCode, SUM(`Pass/Fail` = 'Pass')
FROM results
GROUP BY `Reg.No`, SubjectCode
HAVING SUM(`Pass/Fail` = 'Pass') = 0;
```
The `HAVING` clause counts the number of results for each student and course where the last column is `'Pass'`. In MySQL, booleans are t... | You don't need a subquery for this.
```
SELECT `Req.No`, `SubjectCode`, max(`Pass/Fail`) AS `Pass/Fail`
FROM results
GROUP BY 1, 2
HAVING max(`Pass/Fail`) = 'fail'
```
Assuming `Pass/Fail` is a string type, so `'pass'` > `'fail'`.
You only get students who tried and failed, but not those who never tried (and are... | Filter students that have not passed a subject yet | [
"",
"mysql",
"sql",
""
] |
i'm having a problem to select all in the warehouse table and get the names of the customer and user from their tables with the id's for these names to have them from the warehouse table,
**DATABASE STRUCTURE:**
```
table 1: warehouse
table 2: customer (City, FirstName, LastName)
table 3: user (FirstName, LastName)... | Change the query like this.
```
$result = mysql_query("SELECT customer.City, customer.FirstName AS customerFName, customer.LastName AS customerLName, user.FirstName AS clientFName, user.LastName AS clientLName, warehouse.* ".
"FROM warehouse".
" INNER JOIN customer".
" ON warehouse.CustomerID = customer.CustomerID".... | Try this:
```
SELECT c.City, c.FirstName AS customerFName, c.LastName AS customerLName,
u.FirstName AS clientFName, u.LastName AS clientLName,
w.*
FROM warehouse w
INNER JOIN customer c ON w.CustomerID = c.CustomerID
INNER JOIN user u ON w.UserID = u.UserID;
``` | mysql syntax error, same notice whatever i change | [
"",
"mysql",
"sql",
"select",
"join",
"inner-join",
""
] |
I am trying to create a function that shows the next half hour time.
So when the current time is 13:40, I want it to show 14:00 and not 13:30.
What I have created, gets the job done but on the nearest half hour time, not the future nearest:
```
CREATE OR REPLACE FUNCTION round_timestamp(
ts timestamptz
... | Trivially, add 1 to the rounded down epoch before scaling it back up to a timestamp:
```
CREATE OR REPLACE FUNCTION round_timestamp(ts timestamptz, round_secs int)
RETURNS timestamptz AS $$
BEGIN
RETURN timestamptz 'epoch'
+ (ROUND((EXTRACT(EPOCH FROM ts))::int / round_secs) + 1) * round_secs
... | To avoid tripping over on using epoch and floating point arithmetics, you can rely on date arithmetics, with the additional benefit of making it clearer what is going on:
```
create or replace function round_tstz(ts timestamptz)
returns timestamptz
as $$
select date_trunc('hour', $1) +
-- what hour will i... | Show the next half hour time point in Postgres function | [
"",
"sql",
"postgresql",
"postgresql-9.1",
""
] |
I don't quite get it...
Could somebody please give me a hint on why the results of queries B + C won't add-up to A?
I first thought, that the amount of underscores (should be ten) mismatch between B and C because of a typo, but after copy/pasting I am a bit helpless. The result of A is higher than the sum of B + C.
... | If mycolumn has some rows with `NULL` values, those will be excluded from both `LIKE` and `NOT LIKE` clauses.
Therefore, those 2 statements should be equal:
```
SELECT (select count(*) from mytable where mycolumn like '__________')
+ (select count(*) from mytable where mycolumn not like '__________')
+ (select count(... | Most likely your mycolumn contains NULL values.
NULL values won't compare to LIKE or NOT LIKE. | "NOT LIKE x" and "LIKE x" doesn't sum up? | [
"",
"sql",
"oracle",
"sql-like",
"oracle12c",
""
] |
I've got this table with the following:
```
part_id | feature_name | feature_value | feature_unit |
_____________________________________________________________
1 | Weight | 2 | kg |
1 | Color | Blue | |
1 | Description |... | You are converting columns to rows, you can use `case based aggregation` for this.
```
INSERT into newTable(part_id, description, color, weight)
SELECT part_id
max( case when feature_name ='Description'
then feature_value end ) as description,
max( case when feature_name ='Color'
... | One way to do this is with conditional aggregation:
```
select part_id,
max(case when feature_name = 'description' then feature_value end) as description,
max(case when feature_name = 'color' then feature_value end) as color,
max(case when feature_name = 'weight' then concat(feature_value, feature... | Insert..Select, same column different values | [
"",
"mysql",
"sql",
""
] |
I would like to create a statement that is equivalent to `(x - y == 0) ? return 0 : return 100` in MySQL. Something that might look like this:
```
SELECT id, [(integer_val - 10 == 0) ? 0 : 100] AS new_val FROM my_table
```
I want to compare an attribute in each row to a certain number, and if the difference between t... | Try this:
```
SELECT id, IF(integer_val = 10, 100, 0) AS new_val
FROM my_table;
```
**OR**
```
SELECT id, (CASE WHEN integer_val = 10 THEN 100 ELSE 0 END) AS new_val
FROM my_table;
``` | Use `case when` statement:
```
select *, (case when integer_val = 10 then 100 else 0 end) as New_Val
from yourtable
``` | SQL statement equivalent to ternary operator | [
"",
"mysql",
"sql",
"select",
"if-statement",
"case",
""
] |
Lets say I've got the following table which is a familiar example.
```
+----------------------------------+
| TAGS |
+--------+-------------+-----------+
| tag_id | tag_name | parent_id |
+--------+-------------+-----------+
| 1 | programming | NULL |
| 2 | php | ... | Try this:
```
SELECT tag_id, tag_name, parent_id
FROM tags AS child
WHERE child.tag_name = 'object'
UNION
SELECT parent.tag_id, parent.tag_name, parent.parent_id
FROM tags AS parent
INNER JOIN tags AS child ON parent.tag_id = child.parent_id AND child.tag_name = 'object';
```
Check the [**SQL FIDDLE DEMO**](http:... | Try this:
```
SELECT *
FROM tags t1, tags t2
WHERE t1.parent_id = t2.parent_id AND t1.tag_name = 'object';
``` | Use value from first select for second select in union? | [
"",
"mysql",
"sql",
"select",
"join",
"union",
""
] |
This sounds like a silly question, but I've noticed that in a lot of table designs for e-commerce related projects I almost always see decimal(19, 4) being used for currency.
Why the 4 on scale? Why not 2?
Perhaps I'm missing a potential calculation issue down the road? | First off - you are receiving some incorrect advice from other answers. Obseve the following (64-bit OS on 64-bit architecture):
```
declare @op1 decimal(18,2) = 0.01
,@op2 decimal(18,2) = 0.01;
select result = @op1 * @op2;
result
---------.---------.---------.---------
0.0001
(1 row(s) affected)
```
Note t... | In SQL the 19 is amount of integers, the 4 is amount of decimals.
If you only have 2 decimals and you store maybe a result of some calculations, which results in more than 2 decimals, theres "no way" to store those additional decimals.
Some currencies operates with more than 2 decimals.
Use the data type decimal, no... | Decimal(19,4) or Decimal(19.2) - which should I use? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-types",
""
] |
I have no clue how to Import data from one database to another with condition.
I have DB Name (Northwind) and the table Name Employee
I have following columns
ID
Name
I have another DB (Mater) and the table Name Employee.
I have the following columns
Emp.ID
Emp.Name
Now i want transfer all data from Northwind.Emp... | If I'm understanding your question correctly, you can use a `case` statement in your `insert`:
```
insert into master.schema.employee (id, name)
select case when id = 1 then 201 else id end, name
from northwind.schema.employee
``` | in order to select from diferent DB you can assist this question:
[INSERT INTO from two different server database](https://stackoverflow.com/questions/14153657/insert-into-from-two-different-server-database)
the id issue is a simple case you can see example here: [SQL Case Statement Syntax?](https://stackoverflow.com/... | Import data from one DB to another Database with condition | [
"",
"sql",
"sql-server",
""
] |
I have two tables with product numbers. They both are limited to 12 characters (`varchar(12)`). One of them (product A) has a number structure like this:
Product No:
```
2345
568
89
```
And product B has the same exact numbers but with zeros to fill the 12 characters missing. It is something like this:
Product No:
... | This should do it:
```
UPDATE tblA
SET ProductNo = REPLICATE('0', 12 - LEN(ProductNo)) + ProductNo
``` | Try this, you can use this statement
```
RIGHT('000000000000'+ISNULL(ProductNo,''),12)
``` | Add Zeros to a product number in SQL | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have a query that returns datetime format in sql:
```
SELECT time_in
FROM job_punch_card
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
```
This returns results like `2014-2-15 07:36:32.000`, however I only want the time portion, not the dates. I can get the current time from S... | Use the same `CONVERT` function on your output column:
```
SELECT CONVERT(VARCHAR(8), time_in, 108) AS time_in
FROM job_punch_card
WHERE emp_key=47 and punch_day<= DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0)
``` | Use `CAST` if you need it as a `TIME` type. If you have to do any calculations on the result set this will make things easier.
```
SELECT CAST(time_in AS TIME(0)) AS time_in
FROM job_punch_card
etc., etc.
``` | How to convert datetime to time format | [
"",
"sql",
"sql-server",
"datetime",
"sql-server-2012",
""
] |
Im trying to get this statement to work to mine some text in a freetext fields...
```
SELECT
CASE
WHEN Theme_Q1 LIKE '%Education%' THEN
INSERT INTO #tempThemeCnt(Theme1, ThemeCnt) VALUES ( 'Education', 1 )
WHEN Theme_Q1 LIKE '%Care%' THEN
INSERT INTO #tempThemeCnt(Theme1, ThemeCnt) VALUES ... | EDIT -- Updated to reflect OP's actual problem as described in comment block below.
<http://sqlfiddle.com/#!3/efd1b/5>
This *should* work on sql server 2005 -- I have no way of testing this. Earliest version I can run it on is 2008R2. Also -- you should *totally* upgrade!
If you can't see how to refactor it to your ... | Try this:
```
INSERT INTO #tempThemeCnt(Theme1, ThemeCnt)
SELECT (CASE WHEN Theme_Q1 LIKE '%Education%' THEN 'Education'
WHEN Theme_Q1 LIKE '%Care%' THEN 'Care'
ELSE ''
END) AS Theme1, 1
FROM dbo.tblWNHPSurvey;
``` | Case Select Then Insert Into Temp Table not working | [
"",
"sql",
"select",
"case",
""
] |
I have a MySQL table with around 1 million rows. The table name is `dedict` When I run a simple query like:
```
select writtenform from dedict where length(writtenform)>5
and partofspeech <> 'abbreviation' order by id asc limit 50,1
```
the query takes around 1 second.
I have as primary key the `id` column (aut... | Perhaps you can optimize the attribute length. There are 5 attributes of type varchar(255).
In any case, to get something incredibly faster, you can create a trigger on insert/update statement to store the content length in another attribute.
So each time a row is inserted or updated the trigger store the length in an... | You have to change the structure of the table
like--senseid to integer
writtenForm ---should have add indexed to this bcoz u r using this column for manipulating the data . | Slow Query on Medium MySQL Table (1 Million Rows) | [
"",
"mysql",
"sql",
"query-optimization",
"database-performance",
""
] |
I want to write Sql Query for increase item price by percentage.
Scenario is :-
In table, I have 3 coloumn : ID, Item-Name, Price
```
Example : If item-Name is T-shirt, Increase price by 10%
item-Name is Jins , Increase price by 50%
item-Name is top , Increase price by 5%
``` | If you are looking to update the table you can do conditional update.
```
update table_name
set
price =
case
when `Item-Name` = 'T-shirt' then price+( (price*10) /100 )
when `Item-Name` = 'Jins' then price+( (price*50) /100 )
when `Item-Name` = 'top' then price+( (price*5) /100 )
end ;
```
And if you are lookin... | Try this:
```
SELECT a.ID, a.ItemName, a.Price,
(CASE WHEN a.ItemName = 'T-shirt' THEN (a.price * 10 / 100)
WHEN a.ItemName = 'Jins' THEN (a.price * 50 / 100)
WHEN a.ItemName = 'top' THEN (a.price * 5 / 100)
ELSE a.price
END) AS calculatedPrice
FROM table... | Sql Query for increase item value price for multiple item | [
"",
"mysql",
"sql",
"select",
"sql-update",
"case",
""
] |
Excel Formula Grabs Date and if it is Less then 90 Days remaining States Warning, if it is today or more it is In Warranty and if it is Past Today it is Expired.
Formula:
```
=IF(J2="","",IF(TODAY()-J2>0,"Expired",IF(J2-TODAY()<=90,"Warning","In Warranty")))
```
J Column is End Date Column for Warranty... Example 03... | Just like your Excel formula, each step is evaluated and if the condition is met, that is the value printed out and the statement ends.
So if there were, for example, 0 days left, your CASE statement will evaluate
`datediff(DAY, @TODAY, d.End_date) < 90`
which is TRUE so it will print out "Warning" rather than "Expi... | I'm not sure what answer you're seeing, but from the SQL clause, it looks like 'Expired' will never occur because zero is also <90. Move the check for zero above the warning check, and it should be OK. | SQL Query - Excel Formula Conversion | [
"",
"sql",
""
] |
Lets say, I have a table:
```
+------------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-----------+------+-----+-------------------+-----------------------------+
| id | int(... | I ran both the queries on similar table on MySQL 5.5.
The table has 10634079 rows.
First one took 10.66 initially and always takes approx 10 secs on further attempts.
Seconds Query takes 1.25 mins to execute first time, on second, 3rd.... attempts its taking 22.091 secs
So in my view, if your are looking for perfor... | **DATE :** The DATE type is used for values with a date part but no time part.
**DATETIME:** The DATETIME type is used for values that contain both date and time parts.
so if you have DATETIME you can always derive DATE from it but from DATE you can not get DATETIME.
And as per your sql there will not be a major dif... | Difference between DATE and DATETIME in WHERE clause | [
"",
"mysql",
"sql",
""
] |
I have the following SQL Statement :
```
SELECT
RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
ISNULL(RTRIM(LTRIM(REPLACE(LAGKART.VARIANT1,CHAR(2),''))),'') AS Variant1,
ISNULL... | In SQL Server 2000, Only constants and @local\_variables can be passed to table-valued functions. In SQL 2005 and greater this was fixed. You could try using a scalar function to get the `SpringAvailable` column value instead, or look at upgrading to a newer SQL Server version. | You can use [APPLY](http://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) (`CROSS` or `OUTER`) to pass column(s) value(s) as arguments to a function:
```
SELECT RTRIM(LTRIM(REPLACE(LAGKART.VARENUMMER,CHAR(2),''))) AS ItemNo,
RTRIM(LTRIM(REPLACE(LAGKART.SXSON,CHAR(2),''))) AS Season,
... | SQL Select with a function | [
"",
"sql",
"sql-server",
"function",
"select",
"sql-server-2000",
""
] |
I have to get the result in a year-wise format but the following query returns an unexpected output:
```
SELECT EXTRACT (YEAR FROM Tab_1.DATE_STMP), COUNT (Tab_1.DATE_STMP),
EXTRACT (YEAR FROM Tab_2.DATE_STMP), COUNT (Tab_2.DATE_STMP) FROM
EMP_1 Tab_1 FULL OUTER JOIN EMP_2@LINK Tab_2
ON EXTRACT... | I think it's better to group every table in separate `select`:
```
SELECT TAB_1.YEAR1, TAB_1.COUNT1, TAB_2.YEAR2, TAB_2.COUNT2
FROM
(SELECT EXTRACT (YEAR FROM DATE_STMP) AS YEAR1, COUNT(DATE_STMP) AS COUNT1
FROM EMP_1
GROUP BY EXTRACT (YEAR FROM DATE_STMP)) AS TAB_1
FULL OUTER JOIN
(SELECT EXTRACT (YEAR FROM DATE_... | You full-outer-join records on DATE\_STMP. So you'll get matches and mismatches (i.e. where a date has no match in the other table). Your result shows that you don't even have a sigle match, but only mismatches. However, it seems you are not at all interested in how many dates match. Moreover I daresay you seem not eve... | Select query with join between two tables | [
"",
"sql",
"oracle",
"plsql",
""
] |
How to sum two or three columns, but if any column is NULL then it should not affect the value of SUM.
As i get NULL if columns are added all together.
Here is the example of table i am trying to work on.
```
id col1 col2 col3 total
1 2 3 5
2 10 5 NULL
3 2 NULL NULL
```
This is the ... | One way would be to use [`IFNULL`](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull) function:
```
SELECT id,col1,col2,col3, (IFNULL(col1,0)+IFNULL(col2,0)+IFNULL(col3,0)) AS Total
FROM test_table;
``` | Use coalesce to replace null values with 0. I prefer `coalesce`. In my experience it is database agnostic, where as `isnull`, `ifnull`, `nvl` and others are specific to the database.
```
SELECT col1,col2,col3, (coalesce(col1,0)+ coalesce(col2,0)+ coalesce(col3,0)) as total from test_table;
``` | sum two or more columns in mysql table but leave out the null field | [
"",
"mysql",
"sql",
"database",
""
] |
I have a field name citation that have values C12345, C23456 etc. I need to update the citation field so all citations now have a 0 after the C.
```
Update account
set citation =
where citation like 'C%'
``` | Replace should work for this:
```
Update account
set citation = replace(citation, 'C', 'C0')
where citation like 'C%'
```
I have used [sql server replace](http://msdn.microsoft.com/en-us/library/ms186862.aspx) syntax here. Other platforms may be different.
As pointed out by @sjagr in the comments
> To be safe of va... | Try following.
```
Update account
set citation = 'C0' + substring(citation, 2, len(citation))
where citation like 'C%'
``` | Update SQL value | [
"",
"sql",
""
] |
I have a query that looks like this:
```
SELECT clicks.offer_id, count(distinct clicks.transaction_id) as unique_clicks
FROM clicks
WHERE date > '2014-12-01 17:43:30' and offer_id = 1;
```
This query counts the number of unique clicks by their transaction ID for an offer.
Now, I want to add the unique number of clic... | ```
SELECT clicks.offer_id, count(distinct clicks.transaction_id) as unique_clicks,
count(DISTINCT case when clicks.mobile = 1 then clicks.transaction_id else null end) as mobile_unique_clicks,
count(DISTINCT case when clicks.mobile = 0 then clicks.transaction_id else null end) as desktop_unique_clicks
FROM... | something like this?
```
SELECT clicks.offer_id,
count(distinct clicks.transaction_id) as unique_clicks,
sub.mobile_unique_clicks,
count(distinct clicks.transaction_id) - sub.mobile_unique_clicks as desktop_unique_clicks
FROM clicks
JOIN
(
SELECT clicks.offer_id, count(distinct clicks.transac... | How to select count(distinct) with additional where clause in MySQL? | [
"",
"mysql",
"sql",
"select",
""
] |
I am trying to speed up a PHP script and I am currently pushing some PHP logic in the Mysql domain of the thing. Is there a way to make a different select query if the first Select returns no rows, or a count of zero ?
Keeping in mind that the first query needs to run first, and the second should **only** be activated... | One option would be to use `UNION ALL` with `EXISTS`:
```
SELECT *
FROM proxies
WHERE A='B'
UNION ALL
SELECT *
FROM proxies
WHERE A='C' AND NOT EXISTS (
SELECT 1
FROM proxies
WHERE A='B'
)
```
* [SQL Fiddle Demo](http://sqlfiddle.com/#!2/3fcc4/2)
This will return rows from the `proxies` table where ... | ```
SELECT *
FROM proxies
WHERE A=(CASE WHEN
(SELECT COUNT(*) FROM proxies WHERE A='B') > 0 THEN'B'
ELSE 'C' END)
```
**UPDATE**
```
SELECT *
FROM proxies
WHERE (
CASE WHEN (SELECT COUNT(*) FROM proxies WHERE A='B' LIMIT 1) > 0 THEN
(A='B')
WHEN (SELECT COUNT(*... | Second SELECT query if first SELECT returns 0 rows | [
"",
"mysql",
"sql",
""
] |
I have a table that looks similar to this:
```
images
image_id int
user_id int
datetime datetime
```
So, I need to get only one result. This result should have a specific user\_id and should only be the most recent row in the table.
I've checked out many similar questions, but wasn't a... | You can use order by clause like this:
```
SELECT *
FROM image
WHERE user_id = :user_id ORDER BY datetime DESC LIMIT 1
``` | By using limit you can get no.of required data
```
limit required_no.
``` | Select only one row from table with the highest datetime value | [
"",
"mysql",
"sql",
""
] |
I have the following table:
```
JobCode | Designation | SalaryWithIncrement
----------------------------------------------
JC001 | IT | 150,000
JC001 | IT | 155,000
JC002 | Sales | 100,000
JC003 | HR | 200,000
JC003 | HR | 210,000
JC003 | HR | 220,000
```
Required output:
```
JobCod... | You can use the aggregate [`sum`](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum) function:
```
SELECT JobCode, designation, SUM(salaryWithIncrement)
FROM table1
GROUP BY JobCode, designation
``` | In most cases when you have such requirement, Implement using GroupBY with SQL Aggregate function
Group the Fields based on what you want records, in youu case `JobCode` and `designation`
You can learn about Group BY here [MSDN](http://msdn.microsoft.com/en-us/library/ms177673.aspx)
```
SELECT JobCode,designation,SUM(... | How to get sum of records based on another column? | [
"",
"mysql",
"sql",
""
] |
Suppose I have a table for a set of Roles containing data like Business Analyst, Quality Assurance analyst etc. All are indexed by a unique Id.
I have another table for People again indexed by a unique Id.
I created a third table for people who have multiple roles called "`PersonRole`". If I want to query PersonRole f... | If you want to query for someone who has both roles, I would suggest an aggregation query with a `having` clause. Here is one way to write this:
```
select pr.PersonId
from PersonRole pr
group by pr.PersonId
having sum(case when pr.RoleId = 2 then 1 else 0 end) > 0 and
sum(case when pr.RoleId = 3 then 1 else 0 ... | You can use [OR](http://msdn.microsoft.com/en-us/library/ms188361.aspx)
```
select * from PersonRole
inner join Person on Person.Id = PersonRole.PersonId
where Person.Id = 3
and (PersonRole.RoleId = 2 OR PersonRole.RoleId = 3)
```
Alternatively [IN](http://msdn.microsoft.com/en-gb/library/ms177682.aspx)
```
select ... | How to query a table for multiple conditions | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
Hello guys i building a web app with asp.net and using sql ( MS SQL server 2000 ) and now after getting closer to finish i noticed that the sql part of my code taking huge amounts of space... and i was wondering what ways are there to make it easier to maintain? maybe even change to some other language?
Here is a simpl... | The modern way is to no use SQL directly, but rather an OR-Mapper such as Entity Framework that allows you to query using Linq.
The query you show above would the be reduced to something shorter:
```
using(new context = MyAppDbContext())
{
var workerId = Session["userId"];
var companyId = Session["companyId"];
... | A modern way to access databases from code is to use an ORM. The one that Microsoft provides with the .NET Framework is Entity Framework. This allows you to write your query like this:
```
Dim worker as Worker =
dbContext.Workers
.Where(Function (w) (w.companyId = Session("companyId") and
... | sql commands taking to much space | [
"",
"sql",
"asp.net",
"space",
""
] |
I have an SQL query that I am trying that I am sure is easy, but I am not that well versed so I can't quite figure it out. Wasn't even sure how to word the question. Anyway here is what I am looking at:
I have a table that has the following columns: Hostname, Path, Filename, Filesize
It is essentially a directory lis... | I would recommend splitting this into two parts:
1. Generate the list of all host names.
2. Generate the list of all host names that contain a path you don't want.
Then, use `MINUS` (which automatically removes duplicates) to get the unique results:
```
SELECT hostname
FROM table
MINUS
SELECT hostname
FROM table
WHE... | One way
```
SELECT HostName
FROM YourTable
GROUP BY HostName
HAVING COUNT(CASE WHEN Path IN ('C:\users\Jeff',
'C:\users\Mary') THEN 1 END) =0;
``` | SQL Conditional Query | [
"",
"sql",
""
] |
I have an `addrLines` field formatted like `[Address] [City], [State] [Zip]`, and another field with just the `[city]` data, I am trying to extract just the `[Address]` portion from the `addrLines` field. but this query returns invalid length parameter error.
```
SELECT LEFT(addrLines,(CHARINDEX(',',addrLines)-LEN(cit... | It likely means that you have an entry in `addrLines` that doesn't have a comma in it or `LEN(city)` is greater than `CHARINDEX(',',addrLines)`. In either one of those cases, you're likely going to get a negative number back for `CHARINDEX(',',addrLines)-LEN(city)`, which the `LEFT` function can't use. | try this:
```
SELECT LEFT(addrLines,(CHARINDEX(',',addrLines + ',')-LEN(city)))
FROM MyTable
``` | Invalid Length Parameter Passed to The Left or SUBSTRING funcction | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I'm trying to puzzle through a large set of database stored procedures I'm now maintaining, and I've come to a piece that is confusing. I can't tell if it contains redundant/useless code, or if I'm missing some nuance to it, as I'm still only intermediate at the SQL language. Here's the section of code in question:
``... | It depends on the nature of the data. If a single `Sku` can have multiple records in the newvalues table, then the `outer join` might be needed and it could be possible to set `validnumber = 0`.
---
Here's some sample data to try to illustrate (fiddle below):
```
create table newvalues (validnumber int, sku int, mod... | The original coder is just being safe.
There is a possibility that there could be an item in #NewValues which does not exist in Stage.Products, and if that is the case the LEFT JOIN will cause all fields in SP to be NULL where there is no match. | SQL CASE statement, one result seems unreachable | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
"case",
""
] |
I am very new to programming. I am trying to teach myself SQL. I made a video store database with a customer, rental, and inventory table. I am looking at examples online to try to LEARN SQL, so please be kind. I want this trigger to stop a person from renting the same movie at the same time. I have been reading up on ... | Your trigger has several **fundamental** flaws:
* please ***never ever*** use `BEGIN TRAN` inside a trigger! The trigger is running in the context of the statement that caused it to fire, and therefore is *already* in the context of a transaction
* you need to be aware that the trigger will be called **once per statem... | Your first SELECT is missing a FROM before "inserted". | SQL TRIGGER THE MULTI-PART IDENTIFIER CANT BE BOUND | [
"",
"sql",
"sql-server-2008",
"triggers",
"syntax-error",
""
] |
I have this database structure:
## Tables:
**Category**
```
id | category
1 | fruit
2 | cars
3 | tables
```
**Product**
```
id | product | category_id
1 | banana | 1
2 | apple | 1
3 | orange | 1
4 | example 1 | 2
5 | example 2 | 3
```
... | I thought of one ordering. You want to order by the earliest or latest date for each category. For that, use window functions.
```
SELECT c.id, u.bought_date, max(u.bought_date) over (partition by c.id) as category_bd
FROM categry c left join
product p
on (c.id=p.category_id) left join
user_list u
... | It sounds as though you just need two columns in your `order by` clause:
```
SELECT c.id, u.bought_date
FROM categry as c
left join product p on (c.id=p.category_id)
left join user_list u on (p.id=u.product_id)
WHERE u.user_id=3
ORDER BY category_id, u.bought_date DESC NULLS LAST
``` | PostgreSQL Order By SubQuery | [
"",
"sql",
"postgresql",
"sql-order-by",
""
] |
I have a database table below.

And I want to get list of all DBKey that have: at least one entry with Staled=1, and the last entry is Staled=0
The list should not contain DBKey that has only Staled=0 OR Staled=1.
In this example, the list would be: DBKey=2 and ... | I think this should do the trick:
```
SELECT DISTINCT T.DBKey
FROM TABLE T
WHERE
-- checks that the DBKey has at least one entry with Staled = 1
EXISTS (
SELECT DISTINCT Staled
FROM TABLE
WHERE DBKey = T.DBKey
AND Staled = 1
)
-- checks that the last Staled entr... | Should be done with a simple JOIN... Starting FIRST with any 1 qualifiers, joined to itself by same key AND 0 staled qualifier AND the 0 record has a higher date. Ensure you have an index on ( DBKey, Staled, EntryDateTime )
```
SELECT
YT.DBKey,
MAX( YT.EntryDateTime ) as MaxStaled1,
MAX( YT2.EntryDat... | Need help creating SQL query from example of data | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I would like to get your opinion about my problem. I am working on a project that stores publications from google scholar. So, when I store the data, it is displayed like that.
```
ID| COLUMN1 | COLUMN2
1 | 'Knowledge and Data Engineering' | 'IEEE transactions on 16 (1)'
1 | 'Knowledge and Dat... | You can use the **[ROW\_NUMBER()](http://msdn.microsoft.com/en-GB/library/ms186734.aspx)** windows function to produce a sequential number per `ID`, from which you would want to take the last / highest row number.
> **ROW\_NUMBER()** : Returns the sequential number of a row within a partition of a result set, starting... | ```
WITH CTE AS(
SELECT Id,
Column1,
Column2,
ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY Id DESC) AS rownum
)
SELECT Id, Column1, column2
FROM CTE
WHERE rownum = 1
``` | How to remove duplicate records by taking last record in each group | [
"",
"sql",
"sql-server",
""
] |
I know that if an SQL query is not sorted by an Order By argument, it's not sorted at all. When running a query without an Order By, I'd expect to see the same results in a differing order.
However, the results *are* still returned in an order (i.e. there is a row 1, a row 2 and so on), just not a dependable one - so ... | For the obvious reason database vendors do not publish information about what order rows in an unordered result set will appear in (it would only lead to people relying on the unreliable current implementation).
Common sense, however, tells us that the most likely factors contributing to apparent order would include:
... | The answer as to what determines the row order when no `ORDER BY` is specified is: a lot of internal considerations that can depend on how the data is stored on disk (or in-memory), what types of operations the db does to execute your query (e.g. `JOIN`s), and many other factors that can vary by database engine.
Botto... | As there is no default order in SQL, what determines the order rows are returned in if an Order By is not specified? | [
"",
"mysql",
"sql",
"sorting",
""
] |
I am trying to create a stored proc and have a where clause where to different operations can take place depending on the value of a parameter passed in:
```
WHERE
(cdr.CircuitReference = @CircuitReference)
AND
CASE WHEN (@JDEDocumentReference <> 'Unbilled Calls')
THEN
... | This problem could be solved without a CASE statement by using the following:
```
WHERE
(cdr.CircuitReference = @CircuitReference)
AND
((@JDEDocumentReference <> 'Unbilled Calls' AND sct.JDEDocumentReference = @JDEDocumentReference)
OR
(@JDEDocumentReference = 'Unbilled Calls' AND ((sct.JDEDocumentRe... | STATEMENT FULLY WRONG : There is no need for case here(Even there is a possibility to it correctly. But here no needed).
**USE:**
```
(cdr.CircuitReference = @CircuitReference)
AND ((JDEDocumentReference <> 'Unbilled Calls'
AND @JDEDocumentReference) OR @JDEDocumentReference = 'Unbilled Calls' )
OR (JDEDocum... | SQL Server Case in Where clause | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.