Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a scenario where I have to find out missing record. ``` --Code for Creating Source Table CREATE TABLE [dbo].[NaTarget]( [BillKey] [int] NULL, [StartDate] [date] NULL, [EndDate] [date] NULL ) GO --Code for Creating Target Table CREATE TABLE [dbo].[NaSource]( [BillKey] [int] NULL, [StartDate...
Here is an attempt at this: If I understand your question correctly, you're looking to check to see if any expected values in the Target table based on the Start and End Dates in the Source table aren't actually there. You'll need to essentially recreate the results table with what you are expecting from the `NaSource...
Here's my solution using recursive CTE. Build what the natarget table should look like and compare it to the actual natarget. I started getting confused on the dates piece so it may be simplified but this does work. ``` ;with targetCte as ( select billkey, startdate, CAST(DATEADD(d, -1, DATEADD(m, DATEDIFF(m...
SQL finding Missing Record
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following table `log`: ``` event_time | name | ------------------------- 2014-07-16 11:40 Bob 2014-07-16 10:00 John 2014-07-16 09:20 Bob 2014-07-16 08:20 Bob 2014-07-15 11:20 Bob 2014-07-15 10:20 John 2014-07-15 09:00 Bob ``` I would like to generate a report, where I can group da...
I took it in two steps. Inner query gets the base counts. The outer query uses case statements to sum counts. [SQL Fiddle Example](http://sqlfiddle.com/#!15/328ef/6) ``` select event_date, sum(case when cnt between 0 and 2 then 1 else 0 end) as "0-2", sum(case when cnt = 3 then 1 else 0 end) as "3", sum(case wh...
This is a variation on a `PIVOT` query (although PostgreSQL supports this via the [`crosstab(...)` table functions](http://www.postgresql.org/docs/current/static/tablefunc.html)). The existing answers cover the basic technique, I just prefer to construct queries without the use of `CASE`, where possible. To get starte...
SQL: grouping by number of entries and entry date
[ "", "sql", "postgresql", "" ]
I want to provide a correct ordered list of names. My question: is the SQL `ORDER BY` clause the best way to provide correct ordered strings in multiple languages or are there some problems which should be considered? I just tested it with Russian letters and it seems to work.
The sorting of a column depends on the `collation` in use for that column, or the optional collation applied to that sort - ie: `ORDER BY {column name} COLLATE {collation name}` You would be advised to pick a collation that meets your requirements, perhaps `Cyrillic_General_CI_AS` See <http://msdn.microsoft.com/en-us...
SELECT \* FROM your\_table ORDER BY nlssort(your\_column, 'NLS\_SORT=russian');
Order By on cyrillic letters
[ "", "sql", "sql-server", "unicode", "sql-server-2012", "sql-order-by", "" ]
We use foll. query **to count no. of primary key columns** in a database:- ``` SELECT t.name,is_primary_key FROM sys.indexes i INNER JOIN sys.tables t ON i.object_id = t.object_id AND t.type = 'U' LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T. [object_id] WHERE (EP.class_desc IS NULL OR (EP.class_desc...
Run the below query. This will work for the required purpose: ``` SELECT KC.Column_Name, t.Table_Name, tc.Constraint_Name FROM information_schema.table_constraints tc LEFT JOIN information_schema.tables t ON tc.Table_Name = t.Table_Name LEFT JOIN information_schema.KEY_COLUMN_USAGE kc ON kc.CONSTRAINT_NAME = tc.CONSTR...
This ? ``` SELECT DISTINCT A.COLUMN_NAME, B.CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE A JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B ON A.CONSTRAINT_NAME = B.CONSTRAINT_NAME ORDER BY CONSTRAINT_TYPE ASC ``` Use a where clause if needed
Count number of foreign key columns, ignore system tables, display against each tablename
[ "", "sql", "sql-server", "" ]
The Oracle documentation claims that it stores XMLType more compact as BINARY XML than as CLOB. But how do I find out how much space is taken by the binary xml? ``` CREATE TABLE t (x XMLTYPE) XMLTYPE x STORE AS BINARY XML; SELECT vsize(x), dbms_lob.getlength(XMLTYPE.getclobval(x)) FROM t; 94 135254 94 63848 94 601...
Oracle Binary XML format corresponds to "Compact Schema Aware XML Format" abbreviated as CSX. Encoded data stored as BLOB field. Details about binary XML format available from Oracle documentation ([here](http://www.vldb.org/pvldb/2/vldb09-148.pdf) and [here](http://www.oracle.com/technetwork/database-features/xmldb/or...
Actual storage consumption is stored in a view called user\_segments. To find the correlating LOB to the column you will have to join user\_segments with user\_lobs: ``` CREATE TABLE clob_table (x XMLTYPE) XMLTYPE x store as CLOB; CREATE TABLE binaryxml_table (x XMLTYPE) XMLTYPE x STORE AS BINARY XML; INSERT INTO cl...
How big is an Oracle XMLType when stored as BINARY XML
[ "", "sql", "xml", "oracle", "oracle11gr2", "" ]
Here how my tables look like: CREATE TABLE my\_table(id INT,user\_id VARCHAR(5)); INSERT INTO my\_table VALUES (1, 100), (2, 200), (3, 100), (4, 150), (5, 200), (6, 300), (7, 400), (8, 500); what i want first of all,i need to check the query group by user\_id , i got **100,150,200,300,400,500** then check ea...
Try using [**GROUP\_CONCAT**](http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php) function like ``` SELECT user_id,GROUP_CONCAT(id separator ",") as sets FROM my_table GROUP BY user_id; ```
See using [GROUP\_CONCAT()](http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php) function.
How to get selected value group set in single query for mysql?
[ "", "mysql", "sql", "dataset", "" ]
I have a query which returns several rows of data (in `datetime` format) of a single column obtained by performing `JOINS` on multiple `SQL Tables`. The Data obtained is a DateTime type and now I just want the individual count of latest three dates probably the count of lat three distinct dates as it sorted from earlie...
I would do this with `top` and `group by`: ``` SELECT TOP 3 ST.EffectiveDate, COUNT(*) as cnt FROM Person.Contact C INNER JOIN Sales.SalesPerson SP ON C.ContactID = SP.SalesPersonID FULL OUTER JOIN Sales.SalesTerritory ST ON ST.TerritoryID = SP.TerritoryID GROUP BY ST.EffectiveDate ORDER BY ST.Effe...
added another query to get the latest 3 distinct dates ``` SELECT count(1) FROM Person.Contact C INNER JOIN Sales.SalesPerson SP ON C.ContactID = SP.SalesPersonID FULL OUTER JOIN Sales.SalesTerritory ST ON ST.TerritoryID = SP.TerritoryID WHERE ST.effectivedate in (select distinct top 3 effectivedate ...
Getting individual counts of last three distinct rows in column of data retrieved from multiple tables
[ "", "sql", "sql-server", "" ]
I have the following tables with data: **Projects table:** ``` ProjID Name 1 A 2 B ``` **Project Tags table:** ``` ProjID TagID 1 1 2 2 2 3 ``` **Tags Metadata table:** ``` TagID TagName 1 Series:Go 2 Series:Exploring 3 Chapter:01 ``` 1. The `Pro...
Try this: ``` select * from (select p.projid, p.projname, m.tagname, case when substring(m.tagname,1,1) = 'S' then 1 else 2 end tagtype --Type from projects p left join projecttags t on p.projid = t.projid left join tagsmetadata m on t.tagid = m.tagid ) as src pivot (max(tagname) for tagtype in ([1],[2]) )...
This will work for your sample data: ``` select p.ProjID, max(p.Name) as ProjName, max(case when charindex('Series:', t.TagName) > 0 then t.TagName else null end) Series, max(case when charindex('Chapter:', t.TagName) > 0 then t.TagName else null end) Chapter from Projects p join ProjectTags pt on (pt.ProjID = p.ProjI...
SQL - query to create custom table
[ "", "sql", "sql-server", "" ]
Results of 1,2 and 3 below are same. Just need to know whether this logic is correct that both of the queries return the value of no. of primary keys.. 1. ``` SELECT * FROM sys.indexes i INNER JOIN sys.tables t ON i.object_id = t.object_id AND t.type = 'U' LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T....
``` SELECT Count(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' ``` I think this is the better way to do that
Third query is correct as it is. But the second query needs to be modified to add checks to exclude SYS Tables. sys.Objects has System Tables (so we need to add a check) whereas Information Schema doesnot includes System Tables 2) ``` SELECT COUNT(*) AS 'PRIMARY_KEY_CONSTRAINT' FROM sys.objects WHERE type_desc IN ('P...
Query logic check: to calculate no. of primary keys in db
[ "", "sql", "sql-server", "" ]
i have the following table ``` create table mytab ( mID int primary key, pname varchar(100) not null, pvalue varchar(100) not null ) ``` example data looks like ``` mID |pname |pvalue ----------------------- 1 |AAR | 2.3 1 |AAM | 1.2 1 |GXX | 5 2 |AAR | 5.4 2 ...
Write `Dynamic Pivot Query` as: ``` DECLARE @cols AS NVARCHAR(MAX) DECLARE @query AS NVARCHAR(MAX) DECLARE @colsFinal AS NVARCHAR(MAX) select @cols = STUFF((SELECT distinct ',' + QUOTENAME(pname) FROM mytab FOR XML PATH(''), TYPE ...
``` Declare @t table (mID INT, pname VARCHAR(10), pvalue FLOAT) INSERT INTO @t (mID,pname,pvalue)values (1,'AAR',2.3) INSERT INTO @t (mID,pname,pvalue)values (1,'AAM', 1.2) INSERT INTO @t (mID,pname,pvalue)values (1,'GXX', 5) INSERT INTO @t (mID,pname,pvalue)values (2,'AAR', 5.4) INSERT INTO @t (mID,pname,pvalue)v...
SQL Transpose table - sqlserver
[ "", "sql", "sql-server", "pivot", "" ]
I am trying to alter the code below to also include suppliers who did not supply anything from the l\_foods table. I got it to display them if they do supply food, but I cannot figure out how to display the rest with a 0 in the number of foods column. I thought the left join would help with that. I'm not sure where to ...
In order to see all suppliers you need to select from the suppliers table and left join to the foods table ``` SELECT a.supplier_id , b.supplier_name , count(a.supplier_id) AS "number of foods" FROM l_suppliers b , LEFT JOIN l_foods a ON a.supplier_id = b.supplier_id GROUP BY b.suppli...
Trying using the NVL function (replaces null with 0 the way I've used it here) and using table b in the select list and group by ``` SELECT b.supplier_id, b.supplier_name, nvl(count(a.supplier_id), 0) AS "number of foods" FROM l_foods a LEFT JOIN l_suppliers b ON a.supplier_id = b.supplier_id GR...
SQL count the number of foods supplied by each supplier even if they did not supply anything
[ "", "sql", "oracle", "join", "" ]
I have a Query where I get the **WeekDay** of a date but by default: * Sunday = 1 * Moday = 2 * etc. The function is: ``` DATEPART(dw,ads.date) as weekday ``` I need the result so: * Sunday = 7 * Monday = 1 * etc. Is there any shortcut to do this? Or I will have to do a `CASE statement`?
You can use a formula like: ``` (weekday + 5) % 7 + 1 ``` If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want. **addition**: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula...
This will do it. ``` SET DATEFIRST 1; -- YOUR QUERY ``` Examples ``` -- Sunday is first day of week set datefirst 7; select DATEPART(dw,getdate()) as weekday -- Monday is first day of week set datefirst 1; select DATEPART(dw,getdate()) as weekday ```
SQL DATEPART(dw,date) need monday = 1 and sunday = 7
[ "", "sql", "sql-server", "" ]
Suppose I have a table with two relevant columns: A primary key and an amount. The 'amount' represents money and is one of two things: Either a numeric value (e.g., 47.50) or the word 'unliquidated'. I want to use aggregate functions on this data set. The following works just fine when the criteria doesn't return any ...
Although y state the the only non-numeric string in the column is 'unliquidated', I don't necessarily believe that. In any case, this should be safe: ``` select count(primary_key), sum(case when isnumeric(amount) = 1 then cast(amount as numeric) end) from table where (criteria); ``` `ISNUMERIC` returns 1 when ...
Use `NullIF` ``` select count(primary_key), sum(cast(nullif(amount,'unliquidated') as numeric)) from (table) where (criteria) ```
TSQL: How to cast varchar as numeric when some entries are text
[ "", "sql", "sql-server", "t-sql", "" ]
Im trying to get the min time for each call. Each call can have sevealr parts to it all logged on the same call id. What I want to do is fine the min time for each call id but im getting duplicate values when I query it one way or if I query it another way I just get the min value. I want to end up with being able to ...
You don't need a subquery for that, just use `GROUP BY` to define the grouping expression and add the aggregation as a column: ``` select t.callid, min(timein) as 'mintime' from loggeddata GROUP BY callid ```
``` ;WITH CTE AS ( select t.callid, (select min(timein) from loggeddata t2 where t2.callid = t.callid and t2.timein > t.timein ) as 'mintime' from loggeddata t ) Select c.callid,c.mintime from (select row_number() over (partition by mintime order by callid desc) as seqnum ...
Get MIN value for each id
[ "", "sql", "sql-server", "time", "min", "" ]
Let's say I have the following tables **Table A** ``` id pk_id name value (Varchar) 1 1 name test name 2 1 city los angeles ``` **Table B** ``` id pk_id name value (int) 1 1 age 33 2 1 amount 30 ``` Is it possible to get the followin...
What you want is a `UNION` but with a particular thing since you have different types of fields and the `UNION` requires that all fields should be the same type. So as you did not specify what your RDBMs is I will do it for oracle. But the basic idea is that you need just a function to convert your number column to a ...
Yes. ``` SELECT name, value FROM tablea WHERE id=<somevalue> UNION ALL SELECT name, CONVERT(varchar(10), value) FROM tableb WHERE pk_id=<somevalue> ``` You need to use the `UNION` keyword, but your columns must be the same data type
Getting rows from tables with same columns, but a different type
[ "", "sql", "" ]
How do I convert a string to a date type in SQL Server 2008 R2? My string is formatted `dd/mm/yyyy` I tried this ``` SELECT CAST('01/08/2014' AS DATE) ``` But that does the cast in `mm/dd/yyyy` format.
You need the `convert` function, where you can specify a format code: ``` select convert(datetime, '01/08/2014', 103) ``` The `103` means dd/mm/yyyy. See the [docs](http://msdn.microsoft.com/en-nz/library/ms187928.aspx).
Dateformat. ``` SET DATEFORMAT DMY ; SELECT cast('01/08/2014' as date) ; ``` Convert. ``` SELECT convert(date, '01/08/2014', 103 ) ; ``` And for completeness, SQL Server 2012 and later has the following. ``` SELECT parse('01/08/2014' as date using 'en-NZ' ) ; ```
Convert string to date in specific format
[ "", "sql", "sql-server", "t-sql", "sql-server-2008-r2", "date-parsing", "" ]
following is my table ``` CREATE TABLE tblnull ( tnull integer ) ``` for example `tblnull` contains `3652` rows all rows are `NULL` So how can i delete only `3452` rows from `tblnull` on `PostgreSQL` and `SQL-Server`
In Postgres, you can do this via the hidden [`ctid`](http://www.postgresql.org/docs/current/interactive/ddl-system-columns.html) column: ``` DELETE FROM tblnull WHERE ctid IN (SELECT ctid FROM tblnull LIMIT 3452) ```
Try following query: ``` DELETE z FROM (SELECT TOP 3452 * FROM tbnull)z ```
how to delete fixed number of rows from a table with null values in PostgreSQL
[ "", "sql", "sql-server", "postgresql", "" ]
I was trying to take the last row from my customer table,While executing the following Query: ``` mystring = " mystring = "SELECT TOP 1 customer_id FROM customer ORDER BY customer_id DESC"" openconnection() cmd = New Odbc.OdbcCommand(mystring, myconnection) MsgBox(cmd.ExecuteScalar()) closeconnection() ``` An er...
This is one of the "few" (I expect a bit of backlash on that one) differences between T-SQL and MySQL. While in TSQL, you'd be spot on by calling `SELECT TOP n ...`, in MySQL you should use the [`LIMIT`](http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html) keyword to specify that you want only `n` number of ...
Try to use LIMIT in mysql instead of `TOP` like ``` SELECT customer_id FROM customer ORDER BY customer_id DESC LIMIT 1 ```
Error while retriving the last row of a table
[ "", "mysql", "sql", "" ]
I want to display all data in the left table only once and display matching data on the right table. table 1 ``` id name 1 abc 2 cdr 3 sdf 4 asew 5 sda 6 few 7 asdq 8 uio 9 kjh ``` table 2 ``` id table1_id table2_name 1 1 ...
``` select t1.name, t2.min_table2_name from table1 t1 left join (select t2.table1_id, min(t2.table2_name) min_table2_name from table2 t2 group by t2.table1_id ) t2 on t1.id = t2.table1_id ``` or if you want to only show a certain table2\_name value ``` select t1.name, t2.min_table2_name from table1 t1 left...
You can do this in SQL, but it is not a simple `left outer join`. The key is reducing `table2` to get only the first occurrence for each `id`. The following uses the `substring_index()`/`group_concat()` trick: ``` select t1.name as table1_name, t2.table2_name from table1 t1 left outer join (select table1_id, ...
how to display all data in the left table only once and display matching data on the right table
[ "", "mysql", "sql", "left-join", "" ]
**yes I know the table names have been changed as with the fields names so it may be a bit confusing** I am trying to do a batch update, effectively I want to pass in a list of XXXX and YYYY that together make a composite key, I want to update all records that match the list of composite keys, the bellow statement wil...
``` UPDATE t SET id = 99 FROM ( VALUES ('xxx', 'yyy'), ('zzz', 'ttt') ) v (x, y) JOIN mytable t ON t.d_id = x AND t.[uid] = y ```
Another way is to concatenate both columns and use that to compare the pair as if it was a single column: ``` where convert(varchar, d_id) + ' ' + convert(varchar, [uid]) in ('1 5', '2 6', '3 7') ``` <http://sqlfiddle.com/#!3/aecea/2>
Multi row update statement where record = composite key
[ "", "sql", "sql-server", "" ]
I have a Stored Procedure that retrieves employee daily summary intime - outtime: ``` SELECT ads.attendancesumid, ads.employeeid, ads.date, ads.day, -- month day number ads.intime, ads.outtime --employee shift intime and outtime ss.intime, ss.outtime FROM emplo...
``` select ads.attendancesumid, ads.employeeid, ads.date, ads.day, ads.intime, ads.outtime, ss.intime, ss.outtime from employee_attendance_daily_summary ads join employee emp on emp.employeeid = ads.employeeid join setup_shift ss on ss.shiftcode = emp.shift...
This would be much easier if the times were in seconds after midnight, rather than in a `time`, `datetime`, or string format. You can convert them using the formula: ``` select datepart(hour, intime) * 3600 + datepart(minute, intime) * 60 + datepart(second, intime) ``` (Part of this is just my own discomfort with all...
SQL Match employee intime (punch time) with employee shift
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
for an assignment I have to add three columns of a table (Basic, Additional Labour and Additional Parts) to make an overall charge. I then also have to determine the minimum and maximum overall charge found as well as the average. I have been successful in writing an Overall Charge query ``` SELECT Service.ServiceId, ...
Don't forget the `GROUP BY`: ``` SELECT MIN(OverallCharge) AS [MinOverallCharge], MAX(OverallCharge) AS [MaxOverallCharge], AVG(OverallCharge) AS [AverageOverallCharge] FROM (SELECT ServiceId, Sum([S.BasicCharges]+[S.AdditionalLabourCharges]+ [S.AdditionalPartCharges]) AS [OverallCharge] FROM S...
``` SELECT --get the min/avg/max of all charges MIN(OverallCharge) AS [MinOverallCharge], MAX(OverallCharge) AS [MaxOverallCharge], AVG(OverallCharge) AS [AverageOverallCharge] FROM ( -- calculate OverallCharge for each ServiceId SELECT S.ServiceId, Sum([S.BasicCharges]+[S.AdditionalLabourCharges...
Issue with Subquerying
[ "", "sql", "ms-access", "subquery", "" ]
I have access to a database and I need to know the Partition Scheme definitions in the database. i.e. I need to know the partition scheme name, which Partition function is it using, what file groups are the partitions assigned, etc... For example someone creates a partition scheme as so (taken from msdn): ``` CREATE ...
I have modified knkarthick24's first query to show Partition function values associated to each file group: ``` select distinct ps.Name AS PartitionScheme, pf.name AS PartitionFunction,fg.name AS FileGroupName, rv.value AS PartitionFunctionValue from sys.indexes i join sys.partitions p ON i.object_id=p.objec...
Please try this query: 1) ``` select ps.Name AS PartitionScheme, pf.name AS PartitionFunction,fg.name AS FileGroupName from sys.indexes i JOIN sys.partitions p ON i.object_id=p.object_id AND i.index_id=p.index_id join sys.partition_schemes ps on ps.data_space_id = i.data_space_id join sys...
Find Partition Schema Definitions in SQL Server Database
[ "", "sql", "sql-server", "partitioning", "database-partitioning", "partition", "" ]
I'm adding data to a db table one records at a time. After adding each record I need to check if the same item is already in the database. Whilst their may be multiple entries for the item, all column data other than 'reference' may be different in each record. So far I have the following: ``` CREATE PROCEDURE [dbo]....
``` DELETE FROM tblRes WHERE SCOPE_IDENTITY NOT IN ( SELECT MAX(Id) FROM tblRes GROUP BY reference ) ```
If the Id column is an identity then you can use @@IDENTITY to return the Id of the row that was inserted last. For example: ``` CREATE TABLE #MyTable (PK INT IDENTITY(1,1), SomeValue VARCHAR(50)); INSERT INTO #MyTable (SomeValue) SELECT 'xxx'; SELECT @@IDENTITY; INSERT INTO #MyTable (SomeValue) SELECT 'yyy'; SELECT @...
Insert record then delete older duplicates
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have been scratching my head on this for hours now. I am using PHP and MySQLi. I have two tables: table1 and table2. The table1 table has: ``` uid name phoneNumber ``` And the table2 table has ``` id phoneNumber ``` The registered table contains more than 100,000 entries as compared to the users table with about ...
``` SELECT count(t2.id) FROM table2 t2 WHERE exists (select t1.* FROM table1 t1 WHERE t1.phoneNumber = t2.phoneNumber) GROUP BY t2.phoneNumber ```
Could you give us a closer explanation how your tables look like? You need to have one foreign key for this to be possible (pretty much means an id or key that is the same in both tables so they can be LEFT JOIN'ed by that column), then a little WHERE t2.col IS NOT NULL and you are done but I cannot give you a sample ...
Fastest way to count from a table where a certain field exists in another table?
[ "", "mysql", "sql", "" ]
I am trying to write a SQL Select statement that will return all results that begin with an 'a' or an 'A'. (In other words, not case sensitive.) The way I think I should write this is as follows: SELECT \* FROM mytable WHERE name LIKE 'a%' OR 'A%'; No results are returned. Can someone tell me what I'm doing wrong?
Although I like MikeB's answer, you would get better performance by using an OR: ``` SELECT * FROM mytable WHERE name LIKE 'a%' OR name like 'A%' ``` This is because you wouldn't apply an `upper` on every `name`, which can't use the index.
Try the following SQL statement ``` SELECT * FROM mytable WHERE upper(name) LIKE 'A%'; ```
How do I return results that begin with a or A?
[ "", "sql", "" ]
i used the following code to create a table table is created but warning is shown ``` No index defined! ``` i used the following SQL command to create table ``` CREATE TABLE IF NOT EXISTS `test` ( `path` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ``` i used the following PHP code to insert multipl...
You should have a PK as A\_I field in your table, thats better performance for query/indexing. ``` CREATE TABLE IF NOT EXISTS `test` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `path` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ``` Also, the path only 50 chars, why you expected multiple paths in 1 r...
1. If you define a PRIMARY KEY on your table, InnoDB uses it as the clustered index. 2. If you do not define a PRIMARY KEY for your table, MySQL picks the first UNIQUE index that has only NOT NULL columns as the primary key and InnoDB uses it as the clustered index. 3. If the table has no PRIMARY KEY or suitable UNIQUE...
create index in SQL table shows no index defined
[ "", "mysql", "sql", "" ]
I have this query: ``` SELECT distinct a.Project_Manager, a.Project_ID, a.Topic, a.Stage, a.Presentation_Date, a.Presentation_Notes, a.Presentation_Status, a.Category, a.Postponed_Reason, a.Postponed_Manager FROM GSC_Presentation_Info a inner join ( SELECT Project_ID as Project_ID, MAX(Presentation...
You just need to remove the alias for your Project\_ID column - Access won't let you use an alias name that already exists as a column name or another alias name. ``` ...inner join ( SELECT Project_ID, MAX(Presentation_Date) as Max_Presentation_Date from GSC_Presentation_Info ...
I think this would work with RANK() function as well. I am using Teradata SQL. The synatx might be slightly different for us. The table I created: ``` CREATE TABLE stack_test ( Project_ID VARCHAR(3) CHARACTER SET LATIN CASESPECIFIC, Project_Manager VARCHAR(20) CHARACTER SET LATIN CASESPECIFIC, Presentation_Date D...
Access SQL sorting the data with latest date
[ "", "sql", "ms-access", "inner-join", "" ]
Pardon the question title but I have table CUSTOMER(ACCT\_NUM,LRN,NAME,ADDRESS,CITY,STATE,COUNTRY) I have to write a query to pull records which have more than 1 (distinct) combination of name,address,city,state and country for a **same combination of acct\_num and LRN**. This is what I have tried but I am not sure if...
Creating some test data ``` DECLARE @Customer TABLE ( ACCT_NUM INT, LRN INT, name varchar(20), address varchar(100), state varchar(2), country varchar(100), city varchar(100) ) INSERT INTO @Customer VALUES ( 1, 1, 'Test1', 'Addr1', 'FL', 'USA', 'Tampa' ), ( 1, 1, 'Test1', 'Addr2', 'FL', 'U...
The `RANK() OVER` answer is correct but does fail to show the first address in the results. I would prefer to use an additional level of nesting to accomplish this. ``` SELECT * FROM ( SELECT *, COUNT(*) OVER (PARTITION BY acct_num, LRN) AS distinct_matches FROM ( SELECT acct_num, LRN, name,...
How to pull distinct rows based on combination of few columns of a table
[ "", "sql", "sql-server", "count", "group-by", "distinct", "" ]
I have a table like this and want to add a column so that for the same bpin it should be increase by 1 and for different it should be reset and again start by 1. ``` BPIN Name 101 A 101 B 101 C 102 D 102 E 103 F 103 G 103 H 103 I 104 K ``` Nee...
Using variables to do the count. The first sub query forces the order prior to the processing that adds the counter. The 2nd sub query initialises the variables. ``` SELECT BPIN, Name, @value:=IF(@bpin=BPIN, @value + 1, 1) AS value, @bpin:=BPIN FROM ( SELECT BPIN, Name FROM some_table ORDER BY BPIN, Name ...
Something like below will work ``` set @no:=0; set @BPIN:=''; select BPIN,Name,@no:=case when @BPIN=BPIN then @no+1 else 1 end , @BPIN=BPIN from table; ```
For the same value it should be incremented by 1 and different it should be reset and gives result
[ "", "mysql", "sql", "" ]
I'm struggling with the performance of one MS-sql query, which I have to run to create a report in our ERP system. Hopefully you can help me with that query. Here is the query: "Original version": ``` SELECT artikel.artikelnummer, artikel.bezeichnung, SUM(positionen.anzahl), artikel.Einheit FROM artikel, auftrag, p...
If you phrase the `where` clause correctly, then performance will probably improve. I would suggest: ``` WHERE artikel.warengruppe in (2, 1234, 1235, 1236, 1237, 1239, 1240, 2139) and auftrag.lieferscheinnr IS NOT NULL; ``` Your logic is finding everything for the first 7 `warengruppe` values. Then it is also l...
Apart from indexing, would something like this get you the results you need: ``` SELECT article.articlenr, article.description, SUM(positions.amount), article.unit FROM positions INNER JOIN order AS order1 ON (order1.order = positions.order) INNER JOIN article AS article1 ON (positions.article = article1.arti...
Optimizing MS-SQL Query
[ "", "sql", "sql-server", "" ]
So I have a table of scores with a foreign key TeamID ``` ID TeamID Score Month 1 1 100 1 2 2 90 2 3 2 80 3 ``` And on table Team there are duplicates like this: ``` ID TeamName 1 Team A 2 Team A ``` I want to update TeamID field on the sco...
``` select t1.id, t2.id as newId from team t1 join (select min(id) as id, TeamName from team group by TeamName) t2 on t1.TeamName=t2.TeamName ``` The query will return you which id should be replaced with new one. Use it in the score table to update ids
Try this ``` UPDATE score SET TeamID = (SELECT ID from Team ORDER BY ID limit 1); ```
Update field that have duplicates on another table
[ "", "mysql", "sql", "" ]
In **Oracle**, if I have a table defined as … ``` CREATE TABLE taxonomy ( key NUMBER(11) NOT NULL CONSTRAINT taxPkey PRIMARY KEY, value VARCHAR2(255), taxHier NUMBER(11) ); ALTER TABLE taxonomy ADD CONSTRAINT taxTaxFkey FOREIGN KEY (taxHier) REFERENCES tax(key); ``` With these valu...
Use a `RECURSIVE` CTE in Postgres: ``` WITH RECURSIVE cte AS ( SELECT key, value, 1 AS level FROM taxonomy WHERE key = 0 UNION ALL SELECT t.key, t.value, c.level + 1 FROM cte c JOIN taxonomy t ON t.taxHier = c.key ) SELECT value FROM cte ORDER BY level; ``` Details and links t...
Postgres does have an equivalent to the connect by. You will need to enable the module. Its turned off by default. It is called **tablefunc**. It supports some cool crosstab functionality as well as the familiar "**connect by**" and "**Start With**". I have found it works much more eloquently and logically than the re...
What is the equivalent PostgreSQL syntax to Oracle's CONNECT BY ... START WITH?
[ "", "sql", "oracle", "postgresql", "recursive-query", "connect-by", "" ]
I am still getting a weird error: > The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns. Code: ``` INSERT INTO @tab (Phone) select t2.Phone from ( SELECT DISTINCT top 999 t3.Phone, MIN(t3.Ord) ...
You've focussed on the wrong insert. This is the one with the mismatch: ``` INSERT INTO @tabTemp (Phone1,Phone2) (select (case when o.TYP1=@catH then o.TEL1 else null end) Phone1 ,(case when o.TYP2=@catH then o.TEL2 else null end) Phone2 ,so.POR_C from ... ``` ...
Not sure why you have distinct AND a group by on the same query. You could greatly simplify this. ``` INSERT INTO @tab (Phone) SELECT top 999 t3.Phone FROM ( select Phone1 as Phone, Ord from @tabTemp union all select Phone2 as Phone, Ord from @tabTemp ) t3 GROUP BY t3.Phone ORDER BY MIN(t3.Ord) asc, t3....
INSERT INTO from SELECT: The select list for the INSERT statement contains more items than the insert list
[ "", "sql", "sql-server", "sql-insert", "insert-into", "" ]
Need eloquent/fluent query to get sum with groupBy function. So far I have tried: ``` $this->data['no_of_pages'] = Document::sum('no_of_pages') ->groupBy('users_editor_id'); ``` Which ofcourse gives me `call to member function groupBy() on non-object` because of the fact that sum(...
``` Document::groupBy('users_editor_id') ->selectRaw('sum(no_of_pages) as sum, users_editor_id') ->pluck('sum','users_editor_id'); // originally lists(), which was deprecated in favour of pluck in 5.2 // and dropped completely in 5.3 // ->lists('sum','users_editor_id'); // returns array like this: arr...
``` Document::Where('some_condition',true) ->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")]) ->groupBy('id') ->get() ```
Laravel Eloquent: sum with groupBy
[ "", "sql", "eloquent", "" ]
Hi I have a column called mix which is as follows ``` 120 102 201 300 234 212 11 21 ``` So the issue is I want to extract the digits of the left when a space is found, I am trying that with substring as shown below, I wonder why it is not working. ``` select mix, SUBSTRING(mix,1,CHARINDEX(' ',mix)-1) FROM tbl_x...
Find string comes first in `CHARINDEX`... Change it in WHERE condition ``` SELECT mix, SUBSTRING(mix, 1, CHARINDEX(' ',mix) - 1) FROM tbl_xx WHERE CHARINDEX(' ', mix) > 0 ```
Try this ``` select mix, SUBSTRING(mix,1,CHARINDEX(' ',mix)-1) FROM tbl_xx where CHARINDEX(' ',mix)>0 ``` Your where clause charindex is wrong check the above
SQL Substring Issue
[ "", "sql", "sql-server", "" ]
I have a table similar to below: ``` +-----+-----------+--------+--------+ | key | timestamp | event1 | event2 | +-----+-----------+--------+--------+ | 123 | 07:06 | 1 | 0 | | 123 | 07:21 | 1 | 0 | | 123 | 07:59 | 0 | 1 | | 123 | 08:02 | 0 | 1 | | 456 | 14:21 ...
Or you could use multiple CTEs, depending on your RDBMS: [SQL Fiddle](http://sqlfiddle.com/#!3/41f9e/5) ``` with mins as ( select [key], min([timestamp]) as event1 from table1 where [event1] = 1 group by [key]) ,maxes as (select [key], max([timestamp]) as event2 from table1 where [event2] = 1 group by [key]) selec...
Try this (using SQL Server syntax only for the *TimeFromParts(...)* and \*Right(...) functions for formatting, and standard SQ elswwhere): ``` select "key" ,right(cast(event1 as char(8)),5) as event1 ,right(cast(event2 as char(8)),5) as event2 ,right(timefromparts(0,0,datediff(ss,event1, event2),0,0),...
SQL Column with Max Values where seperate column = 1
[ "", "sql", "max", "" ]
I have the following code ``` SELECT PhysicalAddressID FROM tblPhysicalAddresses as a WHERE EXISTS ( SELECT PhysicalAddressID FROM tblPhysicalAddresses as b WHERE a.PhysicalAddressID <> b.PhysicalAddressID AND a.Address1 = b.Address1 AND a.Address2 = b...
Not clear what you want but this might be it ``` SELECT a.PhysicalAddressID FROM tblPhysicalAddresses as b JOIN tblPhysicalAddresses as b ON a.PhysicalAddressID <> b.PhysicalAddressID AND (a.Address1 = b.Address1 or (a.Address1 is null and b.Address1 is null)) AND (a.Address2 = b.Address2 or (a.Address...
You can use [this technique](http://web.archive.org/web/20180422151947/http://sqlblog.com:80/blogs/paul_white/archive/2011/06/22/undocumented-query-plans-equality-comparisons.aspx) to evaluate two corresponding nulls as equal ``` WHERE a.PhysicalAddressID <> b.PhysicalAddressID AND EXISTS (SELECT a.Addre...
Comparing Columns with Null
[ "", "sql", "sql-server", "t-sql", "" ]
I do a `sum` function over a column. But the column can have string values also. I want SQL Server to ignore the string values and sum only the string values. Eg: column can have values like 16000Euro or 2588, or 3671. The input is from user and I cant change validation in the app to integer I have tried this but st...
Try the below Query, it will work perfectly :) ``` SELECT SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe + '.0e0') = 1 THEN Summe ELSE 0 END) AS total_Euro FROM TableName ``` IsNumeric returns 1 if the varchar value can be converted to ANY number type (includes int, bigint, decim...
Try this ``` SUM(CASE WHEN Type = 202 AND case when Sum not like '%[^0-9]%' THEN Sum END ELSE 0 END) AS total_Euro ``` or ``` SUM(CASE WHEN Type = 202 AND ISNUMERIC(Sum+'.e0') = 1 THEN Sum ELSE 0 END) AS total_Euro ```
SQL Server : ignore strings in SUM function
[ "", "sql", "sql-server", "sql-server-2012", "sum", "" ]
I'm currently designing a MS SQL table for use in a project. The problem I'm currently facing is that the [data types of "Transact SQL "](http://msdn.microsoft.com/de-de/library/ms187752.aspx) are pointing to the deprecation of the types "text" and "ntext", which I always used for big texts. Char, nchar, varchar and n...
Using `nvarchar(MAX)` will allow you to store up to 2 GB of data. The same goes for `varchar(MAX)` too.
varchar(MAX) and nvarchar(MAX). Try 'em; you'll like 'em.
SQL: Alternative to text and ntext data type?
[ "", "sql", "text", "char", "varchar", "ntext", "" ]
Is there any way to make table pivot in sql server like such a way. I have data like ``` | OldItem | NewItem | --------------------- | HD1 | 365 | ``` I need output like below. ``` | Name | Value1 | --------------------- | OldItem | HD1 | | NewItem | 365 | ``` Thanks in advance.
Please try using `UNPIVOT`. Sample given is for static two rows. ``` SELECT Name, Value1 FROM (SELECT * FROM tbl) p UNPIVOT (Value1 FOR Name IN (OldItem, NewItem) )AS unpvt; ```
And here is my little code :D ``` DECLARE @dataTable TABLE (OldItem VARCHAR(10), NewItem INT) INSERT INTO @dataTable SELECT 'HD1', 365 INSERT INTO @dataTable SELECT 'HD2', 300 INSERT INTO @dataTable SELECT 'HD3', 200 INSERT INTO @dataTable SELECT 'HD4', 200 --first select data what you need and add upcoming new col...
Pivot Header Data in row using sql server
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have two tables Category ``` CategorySerno | CategoryName 1 One 2 Two 3 Three ``` Status ``` StatusSerno | Status 1 Active 2 Pending ``` Data ``` CatId |Status | Date 1 1 2014-07-26 11:30:09.693 2 2 2...
You could use `ROW_NUMBER` in a CTE: ``` WITH CTE AS ( SELECT c.CategoryName, s.Status, d.Date, dateNum = ROW_NUMBER() OVER (PARTITION BY CatId, d.Status ORDER BY Date DESC) FROM Category c LEFT OUTER JOIN Data d ON c.Categ...
You prabobly have mismatch between SELECT and GROUP BY columns withch couse duplications Try this: ``` SELECT Category.CategoryName, Status.Status, MAX(Data.Date) Data FROM Data LEFT JOIN Category ON Category.CategorySerno = Data.CatId LEFT JOIN Status ON Status.StatusSerno = Data.Status GROUP BY Category.CategoryNam...
Joining and Grouping data from 3 tables
[ "", "sql", "join", "group-by", "" ]
I have a table: ``` CREATE TABLE tblproducts ( productid integer, product character varying(20) ) ``` With the rows: ``` INSERT INTO tblproducts(productid, product) VALUES (1, 'CANDID POWDER 50 GM'); INSERT INTO tblproducts(productid, product) VALUES (2, 'SINAREST P SYP 100 ML'); INSERT INTO tblproducts(productid, p...
With postgres 9.0+ you can write: ``` select string_agg(product,' | ' order by product) from "tblproducts" ``` [Details here](http://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES).
For Microsoft SQL: Use "WITHIN GROUP" <https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017> ``` SELECT STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product) FROM ... ```
How to sort the result from string_agg()
[ "", "sql", "postgresql", "string-aggregation", "" ]
Hello I have a sql script like this. My intention of the script is to produce out the highest value of today. However the script produce out an unintended result. Can anyone help me look at my code and see what is wrong with it ? Script ``` SELECT MAX(Value), TIMESTAMP, fooditem, cashcurr...
``` SELECT Value, TIMESTAMP, fooditem, cashcurren FROM farm1 f WHERE timestamp between 1405987200 and (1405987200 + 86400) AND fooditem = '2' AND cashcurren = '10' where value = (select max(x.value) from farm1 x where x.timestamp between 1405987200 and (1405987200 + 86400) ...
``` SELECT MAX(Value), TIMESTAMP, fooditem, cashcurren FROM farm1 WHERE r.timestamp > 1405987200 AND r.timestamp <= (1405987200 + 86400) AND fooditem = '2' AND cashcurren = '10' GROUP BY timestamp, fooditem, cashcurren order by 1 desc limit 1; ```
SQL . Timestamp issue with max value
[ "", "sql", "sqlite", "oracle-sqldeveloper", "" ]
have a single column `Varchar(2000)`. Data looks like in a single column, ``` 12:10:08: Dialing12:10:08: Connecting12:10:08: ABC: abc:9433769781$100.88.77.0:878712:10:08: ABCD: 000012:10:09: Agent Initializing12:10:25: On Call12:10:25: Assigned to operator12:10:25: Waiting for Supervisor12:10:30: Waiting for Manager1...
Yuck. But, you can do this with a recursive CTE. Here is how: ``` with t as ( select '12:10:08: Dialing12:10:08: Connecting12:10:08: ABC: abc:9433769781$100.88.77.0:878712:10:08: ABCD: 000012:10:09: Agent Initializing12:10:25: On Call12:10:25: Assigned to operator12:10:25: Waiting for Supervisor12:10:30: Waiting...
Alternative; ``` DECLARE @string VARCHAR(1024) = '12:10:08: Dialing12:10:08: Connecting12:10:08: ABC: abc:9433769781$100.88.77.0:878712:10:08: ABCD: 000012:10:09: Agent Initializing12:10:25: On Call12:10:25: Assigned to operator12:10:25: Waiting for Supervisor12:10:30: Waiting for Manager12:11:30: Call Ended12:11:30: ...
Parse data, single to multiple
[ "", "sql", "sql-server", "" ]
I'm trying to make it so that it copies all the data from oa\_tags into member\_info, but the problem is that I have a unique auto\_increment key in both oa\_tags and member\_info(it's the same in both, called ID). I need it to copy all the data from oa\_tags into member\_info, but obviously it has to ignore the entrie...
This is the how mysql supports what you're wanting to do. <http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html> This explains why I wanted to know the field list/structure of both tables. (I don't like the not in . I think there has to be a way to do it with exists but I'm struggling; and I'm not s...
If you implemented a best practice where you identify all the columns it will fix many of the problems you are currently having. In general it is poor practice to use the \* for columns other than testing. Naming/Qualifying your columns (even when there is a lot) will prevent a lot of future issues when tables change. ...
Trying to use INTO...SELECT in MySQL. Having trouble with the WHERE clause.
[ "", "mysql", "sql", "syntax", "" ]
I have a many-to-many relationship between User & Role, with a role\_user table. My migrations are setup as so (simplified): `users` table: ``` public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); }); } ```...
Try setting when trying to create this table. This fix has worked for me. ``` $table->engine = 'InnoDB'; ``` I have filed a bug under: <https://github.com/laravel/framework/issues/8730>
It is established by Jake's answer that you have set default engine to InnoDB ``` $table->engine = 'InnoDB'; ``` Instead of doing it in each migration file, You can do so in `config/database.php` ``` 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PO...
Laravel foreign key onDelete('cascade') not working
[ "", "sql", "laravel", "eloquent", "foreign-key-relationship", "" ]
I need to optimize a query. I have two tables: * `tblcard` (`CardID int, SerialNumber varchar(15), clientID`) * `tblTransaction` (`TransactionID int, SerialNumber Varchar(15), Transactiondate datetime, ...`) I need to list for a date interval all cards that were involved in a transaction, client name and the date of ...
An execution plan would help. Out of the box, replacing `left` joins with `inner` joins might help if possible. And using a subquery is also an awful idea from performance viewpoint. Instead, you might want to use a view or a CTE: ``` with LatestTransactions (SerialNumber, TransactionDate) as ( select SerialNumbe...
Luaan, your answer is good, here is a more readable(in my opinion) answer (ingnore the missing of tblclient table) ``` select tblTransaction.TransactionDate, Mindate.SerialNumber, Mindate.TransactionDate from tblTransaction outer apply (select MIN(tra.Transactiondate) TransactionDate, car.SerialNumber fr...
sql query performance improvements
[ "", "sql", "performance", "query-optimization", "" ]
I really don't know what I did wrong...I was following advice from a blog post stating that this code would allow me to keep Access from breaking up my criteria (I have a ton of criteria and it was making this statement into four separate lines and adding columns.) Here's my code right now. ``` Choose(1,(([dbo_custome...
I have found what it was now. My statement ``` Choose(1,(([dbo_customerQuery].[store])>=[forms]![TransactionsForm]![txtStoreFrom] Or [forms]![TransactionsForm]![txtStoreFrom] Is Null) And (([dbo_customerQuery].[store]) <=[forms]![TransactionsForm]![txtStoreTo] Or [forms]![TransactionsForm]![txtStoreTo] Is Null)) ```...
My concern is that you are trying to work around a bad design. You may get this immediate issue solved to some degree, and continue to build the bad design. Access is flexible, and forgiving, but there's a big price eventually -- maybe you're already there. I realize this is not an answer. It may seem rude -- I apolog...
Why does this choose statement not work in an Access criteria?
[ "", "sql", "ms-access", "" ]
I have this trigger to merge a column value to its parent table. In this case the InvoiceTotal gets added/subtracted to the Account's InvoiceTotal ``` WITH Deltas as ( SELECT AccountID, Sum(InvoiceTotal) as InvoiceTotal From inserted Group By AccountID UNION ALL SELECT AccountID, Sum(InvoiceTotal * -1) as ...
By adding the IsCancelled flag to your invoice table, you are saying that when an invoice is cancelled, then you want to remove that invoice total amount from the account balance. Another way to say this is that when IsCancelled = 1 then the InvoiceTotal should be treated as 0, and the account balance updated according...
``` WITH Deltas as ( SELECT AccountID, CASE WHEN IsCancelled=0 THEN Sum(InvoiceTotal) ELSE Sum(InvoiceTotal*-1) END as InvoiceTotal From inserted Group By AccountID UNION ALL SELECT AccountID, CASE WHEN IsCancelled=0 THEN Sum(InvoiceTotal*-1) ELSE Sum(InvoiceTotal) END as InvoiceTotal From deleted Group By...
SQL trigger to merge totals to parent table (with cancelled column)
[ "", "sql", "sql-server", "triggers", "" ]
I stumbled over a database design in which a table has in one column the name of the table that needs to be joined and in another column the foreign key to that table (integer, not the foreign key name). I wonder how would you solve this? This is the current situation: *Table chatting:* ``` id | someColumn | ...
This is the classic Polymorphic Association anti-pattern. There are a number of possible solutions: 1 Exclusive Arcs (as suggested by Argeman) e.g. for the chatting table ``` id | someColumn | customerId | colleagueId ------------------------------------------ 1 2 1 2 3 1 3 ...
I would put two or more **nullable** rows into the chatting table that are referencing the different other tables. For example one column chatter\_colleague and one chatter\_customer. That is also not very nice but I just don't know any *really* good solution! That would need some effort to keep the table clean but o...
How to resolve "tablename to be joined in a table"?
[ "", "mysql", "sql", "database-design", "" ]
below is a query I use to get the latest record per `serverID` unfortunately this query does take endless to process. According to the stackoverflow question below it should be a very fast solution. Is there any way to speed up this query or do I have to split it up? (first get all serverIDs than get the last record fo...
**Edit** Ok I solved it. Here is expanded rows showing your original slow query: ![enter image description here](https://i.stack.imgur.com/OuTfj.jpg) And here is a fast query using `MAX()` with `GROUP BY` that gives the identical results. Please try it for yourself. ``` SELECT s1.id ,s1.performanc...
I would phrase this query using `not exists`: ``` SELECT ss.performance, ss.playersOnline, ss.serverID, s.name, m.modpack, m.color FROM stats_server ss INNER JOIN server s ON ss.serverID = s.id INNER JOIN modpack m ON s.modpack = m.id WHERE NOT EXISTS (select 1 from stats_server s...
MySQL Query performance improvement for order by before group by
[ "", "mysql", "sql", "" ]
``` SELECT `text`, `oc_product_to_category.product_id` FROM `oc_product_attribute` AS pa LEFT JOIN `oc_attribute_description` AS od ON pa.`attribute_id`=od.`attribute_id` LEFT JOIN `oc_product_to_category` AS opc ON pa.`product_id`=od.`product_id` ``` the problem caused by `oc_product_to_category.product_id`. I...
Backticks aren't causing your problem in this case. You aliased the table, but then used the original name in the column list. You need to refer to it by its alias. ``` oc_product_to_category.product_id ``` should be ``` opc.product_id ``` I recommend you remove all of the backticks and just write standard SQL. ...
`oc_product_to_category.product_id` If you want to use backticks, then use it for your table and column separately, like this: `oc_product_to_category`.`product_id` Also, you have aliased your table, so use your alias, like this: `opc`.`product_id` But you do not need backticks in this case.
backtick quote causing error in sql query
[ "", "mysql", "sql", "" ]
I am trying to get the max + 1 value from one column, and all of the values from another column. However, my query does not give any results. For example, ``` SectionItemID SectionItem 1 blue 2 red ``` The query should return ``` SectionItemID SectionItem 3 ...
``` SELECT SectionItem, (select MAX(SectionItemID)+1 FROM Core.SectionItem_Lkup) AS SectionItemID FROM Core.SectionItem_Lkup ```
Whenever you `GROUP BY`, you *should* aggregate the other columns involved. * Mysql does allow to omit aggregation on other colums * MsSQL does not, cause the result is undefined for columns without Aggregation. Best way *is* to aggregate other columns. For your szenario, you could use `group_concat` ``` SELECT MA...
Select Max and Select other column
[ "", "mysql", "sql", "select", "max", "" ]
I have a table with a login column that has the text FTO and then a sequence of numbers following it (i.e. `FTO3210` or `FTO1002`). I have a query that says `SELECT * FROM tablename`. I am trying to filter it so that it does not `SELECT` any row that has a login value ranging from `FTO1000` to `FTO1010`.
``` SELECT * FRM [Table] WHERE [Login] NOT BETWEEN 'FTO1000' AND 'FTO1010' ``` or ``` SELECT * FROM [Table] WHERE CAST(REPLACE([Login],'FTO','') AS INT) NOT BETWEEN 1000 AND 1010 ```
[SQLFiddle](http://sqlfiddle.com/#!2/1feced/6/0): ``` CREATE TABLE X ( V VARCHAR(100) NOT NULL ); INSERT X (V) VALUES ('FTO3210'); INSERT X (V) VALUES ('FTO1002'); SELECT V FROM X WHERE NOT SUBSTR(V,4,4) BETWEEN '1000' and '1010'; ```
How do I filter out SQL rows where numbers range?
[ "", "mysql", "sql", "" ]
I think I'm encountering a fairly simple problem in PL/SQL on an Oracle Database(10g) and I'm hoping one of you guys can help me out. I'm trying to explain this as clear as possible, but it's hard for me. When I try to compare varchar2 values of 2 different tables to check if I need to create a new record or I can re-...
Your method is fine, unless one of the values could be a space. The "standard" way of doing the comparison is to explicitly compare to `NULL`: ``` WHERE col1 = col2 or col1 is null and col2 is null ``` In Oracle, comparisons on strings are encumbered by the fact that Oracle treats the empty string as NULL. This is a ...
You can use `LNNVL` function (<http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions078.htm>) and reverse the condition: ``` SELECT TABLE2ID INTO iReUsableID FROM TABLE2 WHERE LNNVL(SOMEFIELDNAME != rowTable1.SOMEFIELDNAME); ```
PL/SQL Oracle condition equals
[ "", "sql", "oracle", "plsql", "" ]
I have two tables: 1st table: ``` NAMES ----------------------------- CD_SPECIES SPECIES 1 Sp1 2 Sp2 3 Sp3 ``` Created with this command: ``` CREATE TABLE NAMES ( CD_SPECIES serial PRIMARY KEY, SPECIES varchar(64)); ``` and the 2nd one: ``` COEFFICIENTS ---...
You would do this with `create table as` and a `cross join`: ``` create table thirdtable as select s.species, c.coefficient, cast(12345 as real) as cvalue from species cross join coefficients; ```
Create the 3rd table, like you have done for other two. And then insert the records in this 3rd table taking the data from a join of table 1 and 2. ``` INSERT INTO TABLE3 (col1, col2) values (select tab1.SPECIES.tab2.COEFFICIENT from tab1,tab2 where tab1.CD_SPECIES = tab2.CD_COEFFICIENT); ```
Combining two tables and defining a third field
[ "", "sql", "postgresql", "" ]
I have looked through questions here and have not been able to find exactly what I am looking for. How would I create a query in mysql that would return missing data in field Name in database Demo as a string (such as 'Blank') instead of NULL? I really appreciate your help!
``` SELECT IFNULL(fieldname, 'Blank') FROM tablename ``` or ``` SELECT COALESCE(fieldname, 'Blank') FROM tablename ```
Yes, in MySQL you can use `IFNULL`, as in: ``` SELECT IFNULL(fieldname, 'Blank') as fieldname, ... ```
SQL Renaming NULL with string
[ "", "mysql", "sql", "string", "null", "" ]
I have a really big stored Procedure which I cannot share but I am only having trouble with implementing a dynamic where clause, which already has 7 ANDs. Within the last 'And' of the WHERE clause, I need to check a parameter passed to the stored procedure and construct the 'And' accordingly. Basically, a user can pass...
Please try this, hope its useful. ``` DECLARE @CliType VARCHAR(100); DECLARE @Name VARCHAR(100); DECLARE @TableBuyer TABLE (ID INT, S_FNAME VARCHAR(100), S_SNAME VARCHAR(100)); DECLARE @TableSeller TABLE (ID INT, S_FNAME VARCHAR(100), ...
You can parse the parameter and build a string variable that you plug into your select statement. ``` if @CliType = 'Buyer' THEN @WhereVariable = B.S_FNAME LIKE '''%''' + @Name + '''%''' OR...' else if @CliType = 'Seller' then ... ``` Then just plug that into a string that ends up being your full query, and exec...
dynamic where clause in one 'AND' of stored procedure
[ "", "sql", "sql-server", "stored-procedures", "if-statement", "case", "" ]
i have table as `Dept` ``` DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON ``` and another table as `Emp` ``` EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7369 SMITH CLERK 7902 12/17/1980 800 NULL 20 749...
``` SELECT dname, SUM(CASE WHEN emp.hierdate > '1981/01/01' THEN 1 ELSE 0 END) FROM dept LEFT JOIN emp ON dept.deptno = emp.empno GROUP BY dname ```
It involves a bit of trickery in order to get the departments with 0 matching employees ``` SELECT Dept.DNAME, COALESCE(t.cnt, 0) AS count FROM Dept LEFT JOIN ( SELECT deptno, count(*) FROM Emp WHERE HIREDATA > '1981/01/01' GROUP BY deptno) as t ON t.deptno = De...
Count Query with joins needed
[ "", "sql", "" ]
I'm moving from MySQL to PostgreSQL and have hit a wall with user privileges. I am used to assigning a user all privileges to all tables of a database with the following command: ``` # MySQL grant all privileges on mydatabase.* to 'myuser'@'localhost' identified by 'mypassword'; ``` It appears to me that the PostgreS...
### Basic concept in Postgres Roles are global objects that can access all databases in a db cluster - given the required privileges. A *cluster* holds many *databases*, which hold many *schemas*. Schemas (even with the same name) in different DBs are unrelated. Granting privileges for a schema only applies to this p...
> Maybe you could give me an example that grants a specific user > select/insert/update/delete on all tables -- those existing and not > yet created -- of a specific database? What you call a database in MySQL more closely resembles a PostgreSQL schema than a PostgreSQL database. Connect to database "test" as a super...
Grant privileges for a particular database in PostgreSQL
[ "", "sql", "database", "postgresql", "privileges", "" ]
I am trying this query to get unique rows based on ID\_B but I also want ID\_B where DueDate is nearest, this is what I am trying, ``` SELECT distinct ID_B, ID_A, Own_ID, DueDate FROM Table1 WHERE (ID_A = 6155) ``` Result I am getting, ![enter image description here](https://i.stack.imgur.com/ntV8z.png) ***I want ...
Try this: ``` ;with cte as (select id_b, id_a, own_id, duedate, row_number() over (partition by isnull(id_b,0) order by duedate) rn from yourtable where id_a = 6155) select id_b,id_a,own_id,duedate from cte where rn = 1 ``` [Demo](http://rextester.com/DHPCEK71622)
You can write as: ``` ;with CTE as ( Select ID_B, ID_A, DueDate, Row_number() over ( partition by ID_B order by [DueDate] asc) as rownum from Table1 ) select ID_B, ID_A,DueDate from CTE C where C.rownum = 1 and ID_A = 6155 and ISNULL(ID_B,0)<>0 ``` [Check Demo here..]...
How to get unique record based on due date
[ "", "sql", "sql-server-2012", "" ]
I need help in building the query as the below structured.i have tried using for loop but its just printing as 1 2 3 4 5 6 7 8 9 For example if the N Value is 9 means the output should be like this. **EXAMPLE Output** : 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 ...
This select query gives exact result: ``` WITH CTE1 AS (SELECT 9 AS COL FROM DUAL) ,CTE2 AS ( SELECT LEVEL - 1 AS A, SYS_CONNECT_BY_PATH(LEVEL - 1, ' ') AS B, COL FROM DUAL, CTE1 CONNECT BY LEVEL <= COL + 1) SELECT B FROM (SELECT A, B FROM CTE2 UNION ALL SELECT 2 * COL - A, B FROM CTE2 WHERE A != COL) ORDER BY A;...
To do this just in SQL - albeit with a bind variable if you want to be able to specify `n` - you need to combine start with the `connect by` and build from there. This is one way, though I'm pretty sure it can be done without the `union`: ``` with t as ( select level as rn, level - 1 as val from dual connect by ...
SQL or PL/SQL queries to Print sequence of given N numbers
[ "", "sql", "oracle", "plsql", "" ]
I have a table with some basic address data: ![table structure](https://i.stack.imgur.com/RsK2l.png) If Street and Postcode/Town are filled, I want Street and Postcode/Town separated by comma. `select Concat(coalesce(Street,''),", ", coalesce(Postcode,'')," ",coalesce(Town,'')) from adresses` If street is not avail...
The easiest way to do this with with the built-in `concat_ws()`: ``` select concat_ws(', ', Street, Postcode, Town) from adresses; ``` If any of the arguments are `NULL` (except the separator), then `concat_ws()`, simply skips that string and the associated separator.
``` select (case when street is not null and postcode is not null and town is not null then concat(street,', ',postcode,', ',town) when street is null and postcode is not null and town is not null then concat(postcode,' ',town) when street is ...
Intelligent coalesce
[ "", "mysql", "sql", "coalesce", "" ]
There are situations where ActiveRecord sets the alias table name if there are multiple joins with the same table. I'm stuck in a situation where these joins contain scopes (using 'merge'). I have a many-to-many relationship: > Models table\_name: `users` > > Second models table\_name: `posts` > > Join table name: `a...
I've been able to solve my own problem in the meantime. I'll post my solution to help others that are having similar issues. Preamble: It's a long way to the promise land ;) I'll keep the setup as short as possible: ``` # # Setup # class Post < ActiveRecord::Base has_many :access_levels, -> { merge(AccessLevel.val...
After looking closer at this problem on a [similar question here](https://stackoverflow.com/a/28821450/488195), I came up with a simpler and cleaner (to my eyes) solution to this question. I'm pasting here the relevant bits of my answer of the other question for completeness, along with your scope. The point was to fi...
Join the same table twice with conditions
[ "", "sql", "ruby-on-rails-4", "rails-activerecord", "arel", "" ]
I am looking for a solution, how to create SQL UDF with optional params. Pseudocode for function where Param1 is necessary and Param2 may be filled (but not needed): ``` dbo.myFnc(Param1 int [, Param2 int]) ``` Is there a way to create thislike function? For existing built-in sample watch the [STR function](http://m...
You can define default parameters in the create statement (= default): ``` --Transact-SQL Inline Table-Valued Function Syntax CREATE FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type [ = default ] [ READONLY ] } [ ,...n ] ] ) RETURNS TABLE ...
You need to pass all arguments to functions, unlike stored procedures. You can use the `default` keyword to indicate that default value is to be used for the parameter, rather than a user-specified value. So you can create your function like this: ``` CREATE FUNCTION dbo.myFnc ( @param1 int, @param2 int) ... ``` ...
Optional parameters in SQL UDF without DEFAULT keyword
[ "", "sql", "sql-server", "function", "" ]
I have a stored procedure which uses dynamic sorting, 2 parameters determine the sorting - column: `@SortIndex` and sort direction: `@SortDirection` relevant code: ``` ... ROW_NUMBER() OVER ( ORDER BY -- string order by CASE @SortDirection WHEN 'ASC' ...
``` ROW_NUMBER() OVER ( ORDER BY -- string order by CASE @SortDirection WHEN 'ASC' THEN CASE @SortIndex WHEN 1 THEN SKU WHEN 2 THEN BrandName + ',' + ItemName WHEN 3...
If you cannot use Dynamic SQL, the only way is to list all the possible combination for `ASC` and `DESC` For example: ``` ORDER By CASE WHEN @SortIndex = '1' AND @SortDirection = 'ASC' THEN SKU END, CASE WHEN @SortIndex = '1' AND @SortDirection = 'DESC' THEN SKU END DESC, CASE WHEN @SortIndex = '2' AND @SortDirection...
SQL Server dynamic sorting on multiple columns
[ "", "sql", "sql-server", "sorting", "" ]
Could someone kindly point me to the right direction to seek further or give me any hints regarding the following task? I'd like to list all the distinct values from a MySQL table from column A that don't have a specific value in column B. I mean none of the same A values have this specific value in B in any of there ...
This might help you: ``` SELECT DISTINCT A FROM MY_TABLE WHERE A NOT IN (SELECT DISTINCT A FROM MY_TABLE WHERE B = 1) ```
Since there are null values, I have also added a nvl condition to column B . **ORACLE:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT COLUMN_A FROM MY_TABLE WHERE nvl(COLUMN_B,'dummy') = '1'); ``` **MYSQL:** ``` SELECT DISTINCT COLUMN_A FROM MY_TABLE WHERE COLUMN_A NOT IN (SELECT CO...
MySQL query all distinct from column A where none of them has a specific value in column B
[ "", "mysql", "sql", "" ]
I have the case when there are two date fields. If one is Null then take the other one. At the moment this is working fine with the below code ``` select e.EMPLOY_REF, ISNULL(e.PROB_DOCS_SENT, ec.USR_FINALPROB) from EMPLOYEE_TABLE e join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF ``` However, it could be t...
Try the following query, the advantage of this solution over a case when solution is that you can easily extend it with more columns ``` SELECT EMPLOY_REF, MAX(Date) FROM ( select e.EMPLOY_REF, e.PROB_DOCS_SENT AS Date from EMPLOYEE_TABLE e join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF union sele...
You can use CASE-WHEN in order to handle all the possible cases. In the case where both the dates are null, the following query will take today's date as value. ``` select e.EMPLOY_REF, ISNULL(e.PROB_DOCS_SENT, ec.USR_FINALPROB) case when e.PROB_DOCS_SENT is null and ec.USR_FINALPROB is null then getdate() when e...
SQL - ISNULL or if not latest date
[ "", "sql", "date", "isnull", "" ]
I am looking to get an SQL Statement that will get me all data with the highest price and link\_id = 1 <http://sqlfiddle.com/#!2/26a13/2> ``` ID .. LINK_ID .. PRICE 10 .. 1 .. 100,000 20 .. 1 .. 150,000 30 .. 2 .. 150,000 ``` The following returns the correct price/offer but doesnt bring across the ...
if you just want the highest price record try this ``` SELECT id, p_id, offer FROM offers WHERE p_id = 1 order by offer desc limit 1 ```
Try this, It is much faster than sub query. ``` SELECT o1.* FROM offers o1 LEFT JOIN offers o2 on o2.prop_id=o1.prop_id and o1.offer<o2.offer where o2.id is null and o1.prop_id=2; ``` example : <http://sqlfiddle.com/#!2/26a13/29>
Use SQL to get highest item with same id
[ "", "mysql", "sql", "" ]
Thanks to advise me for the below issue: I am using below query to fetch the value of a column: ``` Select OptionList = case when isnull(AS_CIS_Code,'') <> '' then AS_CIS_Code else '' end from added_services ``` AS\_CIS\_Code column is of varchar(10) in added\_services table. It contains values like 'AB...
You can split the string using a numbers table and the rebuild it using `for xml path()`. ``` select isnull(C.Value, '') as AS_CIS_Code from added_services as A cross apply ( select substring(A.AS_CIS_Code, T.N, 1)+'_' from (values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) as T(N) ...
Try this: ``` DECLARE @Input VARCHAR(100) = 'TESTING' DECLARE @Pos INT = LEN(@Input) WHILE @Pos > 1 BEGIN SET @Input = STUFF(@Input,@Pos,0,'_') SET @Pos = @Pos - 1 END SELECT @Input ``` **Output** ``` T_E_S_T_I_N_G ``` **UDF** ``` CREATE FUNCTION PadStr(@Data VARCHAR(100)) RETURNS VARCHAR(200) AS BEGIN ...
Append a specific character after each character of a string in sql server
[ "", "sql", "sql-server", "" ]
EDIT original question: Our UDW is broken out into attribute and attribute list tables. I would like to write a data dictionary query that dynamically pulls in all column values from all tables that are like `%attr_list%` without having to write a series of unions and update or add every time a new attribute list is ...
Something like this might work for you if all tables contain the same columns. Just change the temp table and the selected columns to match your own columns. ``` CREATE TABLE #results ( ATTR_TABLE SYSNAME, ATTR_LIST_ID INT, ATTR_NAME NVARCHAR(50), ATTR_FORMAT NVARCHAR(50), SHORT_DESCR NVARCHAR(50),...
For SQL Server you should be able to use something like this: ``` SELECT c.name AS ColName, t.name AS TableName FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id WHERE t.name LIKE '%attr_list%' ``` And this will include views as well as tables ``` SELECT COLUMN_NAME, TABLE_NAME FROM INFORMATION_...
Select all values from all tables with specific table name
[ "", "sql", "sql-server", "select", "dynamic-sql", "" ]
Say, I have a customer profile with many contacts. That means I will have separated contact table from customer table. **tbl\_customer** ``` CustomerId (PK, NOT NULL, UNIQUE, AUTO_INCREMENT) CustomerName Address (etc) ``` **tbl\_contact** ``` ContactId (PK, NOT NULL, UNIQUE, AUTO_INCREMENT) CustomerId (F...
Try like this ``` START TRANSACTION; insert into (feilds name) values(Values); insert into tbl_contact(CustomerId ,ContactType,ContacNumber) values((select max(CustomerId) from tbl_customer),'type1','Fax'); COMMIT; ``` Pass all other contacttype
Assuming the name is unique, you can do this as: ``` insert into tbl_contact(CustomerId, ContactType, ContactNumber) select cust.CustomerId, c.ContactType, c.ContactNumber from (select 'Fax' as ContactType, Faxnumber as ContactNumber union all select 'Office', Officenumber union all select ...
SQL insert one record with multiple relational data in one transaction
[ "", "mysql", "sql", "" ]
I have a query to get some data: ``` select max(v.SEQUENCENO) as vmaxseq, v.CODE, v.NAMECODE, v.CODENO from smalltbl v join (select max(SEQUENCENO) as maxseq, CODE, CODENO from smalltbl group by CODE, CODENO) sm on sm.CODE = v.CODE and sm.CODE = 'D50451489' group by v.CODE, v.NAMECODE, v.CODENO; ``` But when I run, ...
You can do what you want with analytic functions. I think the query you want is: ``` select sm.* from (select sm.*, max(SEQUENCENO) over (partition by codeno) as maxseq from smalltbl sm where sm.CODE = 'D50451489' ) sm where sequenceno = maxseq; ```
namecode is your problem. Because it varies over your rows and doesn't relate directly to codeno, you're essentially getting a cartesian product.
SQL query oracle return more than expected result
[ "", "sql", "oracle", "" ]
How to combine two SQL queries in one? ``` SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23 ```
``` SELECT * FROM TABLE1 WHERE ( CHAPTER = 88 AND SENTENCE >= 23 ) OR ( CHAPTER = 89 AND SENTENCE >= 1 AND SENTENCE <= 23 ) ```
This is one way ``` SELECT *FROM table1 WHERE chapter=88 AND sentence>=23 UNION ALL SELECT *FROM table1 WHERE chapter=89 AND sentence>=1 AND sentence<=23 ``` but you should get into the habit of explicitly listing columns. The columns must align or it won't work. Here's another way ``` SELECT * FROM table1 WHERE (...
Merge two SQL queries
[ "", "sql", "" ]
I have a table with the left 2 columns. I am trying to achieve the 3th column based on some logic. Logic: If we take date 1/1 and go further the highest score that wil be reached with going further in dates before the score goes down will be on 3/1. With a score of 12. So as HighestAchievedScore we will retrieve 12 fo...
Lets make some test data: ``` DECLARE @Score TABLE ( ScoreDate DATETIME, Score INT ) INSERT INTO @Score VALUES ('01-01-2014', 10), ('01-02-2014', 11), ('01-03-2014', 12), ('01-04-2014', 10), ('01-05-2014', 11), ('01-06-2014', 9), ('01-07-2014', 8), ('01-08-2014', 9); ``` Now we are going to n...
I'm not sure this will work.... but this is the general concept. Self join on A.Date < B.Date to get max score, but use coalesce and a 3rd self join on a rowID assigned in a CTE to determine if the score dropped on the next record, and if it did coalesce that score in, otherwise use the max score. NEED TO TEST but ha...
SQL Query Find x rows forward the highest value without having a lower value in between
[ "", "sql", "sql-server", "" ]
In our database each user has a `created_at` and `cancelled_at` date. How could I calculate the distribution of days active for users (that have a `cancelled_at` date present).
By distribution, I would expect that you want to see the histogram. For that, you want aggregation: ``` select date_part('day', cancelled_at - created_at) as activedays, count(*) from databasetable group by date_part('day', cancelled_at - created_at) order by activedays; ```
``` SELECT *,DATE_PART('day', cancelled_at - created_at) as daysActive FROM tableName WHERE cancelled_at IS NOT NULL ```
Calculate distribution of date differences in SQL
[ "", "sql", "postgresql", "" ]
Following table structure name: table ``` quantity price 100 30.00 50 15.00 25 25.00 25 24.00 25 23.00 ``` I want to select the rows `WHERE SUM(quantity)<=90 AND price<26.00` the output should be ``` quantity price 50 15.00 25 ...
`SUM()` is an aggregation function and you provide no aggregate, so this is bound to fail. What you seem to want is a running total, this can easily be achieved: ``` SELECT quantity, price, @rt:=@rt+quantity AS runningtotal FROM `table` INNER JOIN (SELECT @rt:=0) AS init ON 1=1 WHERE price<26.00 AND @rt<...
Did you mean - `WHERE quantity <=90 AND price<26.00`
SUM() in WHERE in MYSQL statement
[ "", "mysql", "sql", "join", "sum", "" ]
Is there a way that i can eliminate all 'special characters' from a SQL Server query? Sometimes our users will put odd things like '@' or '&' in their name fields and I am trying to eliminate anything that is not a number or letter. Is this possible? Thanks in advance.
I would use the answer here: [How to strip all non-alphabetic characters from string in SQL Server?](https://stackoverflow.com/questions/1007697/how-to-strip-all-non-alphabetic-characters-from-string-in-sql-server) If you cannot create a function, you might be able to use the function's code in your query.
Best way, if possible, is to do this before you even get to SQL Server. SQL Server is not the best tool for string manipulation. RegEx in the middle tier would handle it well or you could potentially use CLR in SQL using RegEx. Unsure on performance of latter, so would need to be tested.
Eliminating Special Characters From a SQL Server Query
[ "", "sql", "sql-server", "ascii", "" ]
I have a table that has data that holds a total amount for each month of sales and each column is split by month. E.g. ``` InvJan | InvFeb | InvMar ... TotalInv | CrdJan | CrdFeb | CrdMar ...TotalCrd ------------------------------------------------------------------------------ 100 | 120 | 200 ... 420 ...
This type of data transformation columns into rows is known as UNPIVOT. Since you are using SQL Server 2008, you should be able to use `CROSS APPLY` to unpivot your columns in pairs: ``` select Mnth, Inv, Crd from yourtable cross apply ( values ('Jan', InvJan, CrdJan), ('Feb', InvFeb, CrdFeb), ...
First define what is Inv and Crd: ``` SELECT 'Inv' as Types, InvJan AS Jan, InvFeb as Feb, InvMar as Mar INTO #testTable FROM @table UNION SELECT 'Crd' as Types, CrdJan AS Jan, CrdFeb as Feb, CrdMar as Mar FROM @table ``` Then Unpivot this| ``` select months, Types, data INTO #test2 from #testTable unpivot ( data ...
PIVOT a horizontal table with Totals
[ "", "sql", "sql-server", "sql-server-2008", "stored-procedures", "" ]
I've got 2 tables, called `Entry` and `Booking`. The idea is: I create an `entry` which has a `start` and an `end` time and then I can create bookings for this `entry`. A `booking` is associated with an `entry` and it also has a `start` and an `end`. A `booking` lies within the time of its `entry`, meaning `booking.sta...
It got a bit ugly: ``` SELECT e.id AS entry_id, e.start AS start, COALESCE(MIN(b1.start), e.end) AS end FROM entry e LEFT JOIN booking b1 ON b1.entry_id = e.id AND b1.start >= e.start AND b1.end <= e.end GROUP BY e.id HAVING start < end UNION SELECT e.id ...
**MS SQL** ``` SELECT * FROM ( SELECT ENTRY_ID, b1.BOOK_END_DATE AS INTERVALL_START_DATE, (SELECT TOP 1 b2.BOOK_START_DATE FROM Booking b2 WHERE b1.BOOK_ENTRY_ID = b2.BOOK_ENTRY_ID AND b2.BOOK_START_DATE > b1.BOOK_END_DATE ORDER BY b2.BOOK_START_DATE) AS INTERVALL_END_DATE FROM Entry JOIN Booking...
Find available intervals
[ "", "sql", "" ]
I am trying to create a function which has a cursor in it. I want to get the Quanatity value from that cursor and put it in the temp table. But I havent succeeded to get the value and put it into the temp table. I put comment where I couldnt get it done... here is my code ``` alter FUNCTION test(@input VARCHAR(250))...
You can do the following. Note that it only inserts the quantity so it needs to be modified if you intend to include the price. ``` DECLARE @Temp TABLE ( Quantity Decimal(8,2), Price Decimal(8,2) ) INSERT INTO @temp (Quantity) SELECT AMOUNT FROM LG_001_01_ORFLINE WHERE LINETYPE = 0 AND ORDFICHEREF = (SELECT ...
``` CREATE PROCEDURE [dbo].[usp_demo_cursor_with_temp_table] AS BEGIN DECLARE @temp TABLE (value1 varchar(5),value2 varchar(5),value3 INT,value4 varchar(1)) DECLARE @value1 varchar(5) DECLARE @value2 varchar(5) DECLARE @value3 INT DECLARE @value4 varchar(5) DECLARE check_data_cursor CU...
In Sql Server, how do you put value from cursor into temp table?
[ "", "sql", "sql-server", "temp-tables", "database-cursor", "" ]
When performing a SQL Query with using an alias on a column name, I am trying to reference that alias in the same query to perform a calculation on it. Such as: ``` SELECT QUANTITY, AMOUNT, Count(AMOUNT) AS CntAmount, Sum(CNTAMOUNT) FROM MY_TEST GROUP BY QUANTITY, AMOUNT ``` T...
You can use an alias in the same query, but... If you need to use an alias of an aggregate function (such as `SUM(amount) AS aggregated_alias`, `AVG()`, `COUNT()`, etc) in the same query, you must use a subquery. Here is a sample subquery: ``` SELECT a.QUANTITY, a.AMOUNT, SUM(a.CntAmount) AS SUM_CNTAMOUNT FROM (SELE...
As Per my knowledge you **cant directly use an alias** to perform the calculation on it. Because if you use any name such as **'xyz'** to perform the calculation it searches into the table & if you have used alias for performing the calculation it will not permanently appears on your table. Thats why you will get an ...
Use alias name in same query for SQL Server
[ "", "sql", "sql-server", "" ]
I am new to MySQL having previously done everything in MS Access. I am trying to join together 2 tables so that I can show all of the records from Table1 and add in certain columns from Table2. I can join the tables together using ``` SELECT Table1.Name, Table1.Address, Table1.TelephoneNumber FROM Table1 LEFT JOIN Ta...
You have blanks in your data (not nulls): ``` SELECT Table1.Name, Table1.Address, Table1.TelephoneNumber FROM Table1 LEFT JOIN Table2 ON Table1.TelephoneNumber = Table2.PhoneNumber AND Table1.TelephoneNumber != '' ``` Checking for `NOT NULL` won't help, because null is not equal to null (whereas blank is equal to...
``` SELECT Table1.Name, Table1.Address, Table1.TelephoneNumber FROM Table1 LEFT JOIN Table2 ON Table1.TelephoneNumber=Table2.PhoneNumber WHERE Table1.TelephoneNumber IS NOT NULL ```
Left Join returning more records than in Table 1 and adding in additional data
[ "", "mysql", "sql", "join", "" ]
I need to merge 2 select results, one is like this: ``` SELECT count(emaildata2.EM_SENT_FLAG), emaildata2.EMAIL_FINANCIAL_WEEK FROM `email-redeye`.emaildata2 WHERE emaildata2.EM_SENT_FLAG='Yes' GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK ``` and the other like this: ``` SELECT count(emaildata2.EM_OPEN_FLAG), emaildata...
You can use **SUM WITH CASE** as below: **Syntax** : `CASE WHEN CONDITION THEN TRUE_VALUE ELSE FALSE_VALUE END` ``` SELECT SUM(CASE WHEN emaildata2.EM_SENT_FLAG = 'Yes' THEN 1 ELSE 0 END) SEND_COUNT, SUM(CASE WHEN emaildata2.EM_OPEN_FLAG= 'Yes' THEN 1 ELSE 0 END) OPEN_COUNT, emaildata2.EMAIL_FINANCIAL_WEEK FROM ...
Just add the extra count but use IF and SUM:- ``` SELECT SUM(IF(emaildata2.EM_SENT_FLAG='Yes', 1, 0), SUM(IF(emaildata2.EM_OPEN_FLAG, 1, 0)), emaildata2.EMAIL_FINANCIAL_WEEK FROM `email-redeye`.emaildata2 GROUP BY emaildata2.EMAIL_FINANCIAL_WEEK ```
Merging two select statements
[ "", "mysql", "sql", "" ]
``` id name number counter 1 test 010101 2 2 test 010101 1 ``` I need to select the duplicates rows that have the same number-name combination. And I need to update the counter in one of the rows with the sum of the counter in the two rows and then delete the second row I'm using the below query to select the dupli...
The update would be something like this. ``` update prof set counter = counterSum from prof join (select name, number, sum(counter) counterSum from prof where whatever group by name, number) temp on prof.name = temp.name and prf.number = temp.number where whatever ``` The two "where whatever"s should be the same.
This will update the counter and keep the first(lowest) id. It will only keep one unique id so if there are 3 or more rows with the same name, number this will still work. ``` Update [prof] set counter=a.cnt from [prof] p inner join ( select name,number,sum(counter)cnt from [prof] group by name,number)a ...
Join Duplicate Rows Into One Row in SQL Server
[ "", "sql", "sql-server", "" ]
**dbcc useroptions** shows the date format later i changed format using **set dateformat dmy** even though i changed the format the date is being display in the the format of yyyymmdd how to change the display format without using *CONVERT*
Since, you didn't mentioned that we can't use ***CAST***, Would the following work for you? > select CAST(getdate() as nvarchar(30)) I know i am not being too fair, but that's all i could do.
you can do something like ``` SELECT ProductName, Price, FORMAT(Now(),'dd/MM/yyyy') AS PerDate FROM Products; ```
Change the Display date format without using CONVERT
[ "", "sql", "sql-server-2008", "" ]
I am trying to spool results directly to a CSV using a few substitution variables. I have this query: ``` SET echo off set feedback off set pagesize 0 set termout off define startdate='12-JAN-14' define enddate='01-JUN-14' define vpath=C:\14-0724_Spool testing\' define dt='60_testupdate_subvar' define ext='.csv' SPO...
Assuming SQL\_Developer is sqlplus compliant, first, try adding "SET VERIFY OFF" . If that doesn't work you can also try putting the spool after the query as in the following example: ``` set verify off define x = 'X' select * from dual where '&x' = 'X' spool x.out / spool off ``` Note the blank line after the SEL...
Use `-s`. The -s flag means silent, a complete bash script will look like something as follow: ``` #!/bin/bash sqlplus -s /nolog << EOF CONNECT USER/PASSWORD set echo off set verify off set colsep "," set linesize 9999 set trimout on set trimspool on set heading on set pagesize 0 embedded on set wrap off set feedback ...
Remove query from spool output in SQL Developer with variables
[ "", "sql", "oracle", "csv", "oracle-sqldeveloper", "sqlplus", "" ]
I have to update a column in one table with values in another column which is another table. I have to update around 100000 records (not a single row update). My query is ``` update asset_dmr_revision adr set adr.revision_date = (select adrt.revision_date_test from asset_dmr_revisio...
Add `and rownum = 1` or `and rownum <=1` to the inner select query. This will ensure that always only 1 record is returned by the inner query. ``` select adrt.revision_date_test from asset_dmr_revision_test adrt, asset_dmr_revision ad ...
Like I said in my comment, you need to return only ONE row. You can achieve this by using functions : ``` update asset_dmr_revision adr set adr.revision_date = (select max(adrt.revision_date_test) from asset_dmr_revision_test adrt, asset_dmr_revisio...
Not able to update column in DB
[ "", "sql", "oracle", "" ]
I am having a hard time constructing an sql query that gets all the associated data with respect to another (*associated*) table and loops over into that set of data on which are considered as latest (*or most recent*). The image below describes my two tables (*Inventory and Sales*), the Inventory table contains all t...
You can use [APPLY](http://technet.microsoft.com/en-us/library/ms175156%28v=sql.105%29.aspx) ``` Select Item,Sales.Price From Inventory I Cross Apply(Select top 1 Price From Sales S Where I.id = S.Inventory_Id Order By Date Desc) as Sales ```
I would just use a correlated subquery: ``` select Item, Price from Inventory i inner join Sales s on i.id = s.Inventory_Id and s.Date = (select max(Date) from Sales where Inventory_Id = i.id) ```
Join two tables but only get most recent associated record
[ "", "sql", "sql-server", "" ]
I am not that good at subqueries. I am trying to essentially create columns by selecting certain values from another table, and then insert those columns into my table [Presummary 7/24 . . . AM]. The thing is in my select subqueries to generate the values I want to be inserting, I reference the workstation column of my...
Never figured out the true cause of the syntax errors. But regardless, for what i was trying to do, I realized I needed to use an UPDATE rather than INSERT statement.
Try this code, ``` INSERT INTO [Presummary 7/24/2014 11:07:33 AM] (660201, 660202, 660203, 660206, 660207, 660208, 660209) SELECT Sum(IIF(Right([qry EngineHoursSummaryA].MODULE_ENGINE_SWO_SERIAL,6) = '660201', [qry EngineHoursSummaryA].SumOFHRS_Claimed, 0)) As E1, Sum(IIF(Right([qry EngineHoursSummaryA].MODUL...
INSERT INTO - Reference outer table in Values subquery
[ "", "sql", "ms-access", "vba", "" ]
Let's assume we have such data set: Table: DataTable1 ``` ID ExperienceId LanguageId ... ------------------------------------------- 1 1 1 2 1 2 3 1 3 4 2 1 5 2 2 6 2 3 7 3 1 ...
Wrapping it in another query does the trick? ``` SELECT RequiredId, <all_the_other_fields> from ( SELECT t2.SomeId AS RequiredId -- ...other data mainly from t2 FROM DataTable1 AS t1 LEFT JOIN DataTable2 AS t2 ON t2.OtherId = t1.ExperienceId AND t2.LanguageId = (SELECT TOP 1 t1.LanguageId ORDER...
Try this: ``` ;with cte as (select *, row_number() over (partition by someid order by languageid) rn from datatable2) select * from datatable1 dt left join cte c on dt.experienceid = c.otherid and c.rn = 1 ```
SQL LEFT JOIN first row only
[ "", "sql", "sql-server", "join", "" ]
I have a query which looks something like this: ``` select distinct col1, ( select ltrim(str(col2))+',' from @temp t2 where t2.col1 = t1.col1 for xml path('') ) col2 from @temp t1 ``` Some of the values in col2 are null, so instead of displaying a string with null, that part is missing totally, i.e. ...
To get a NULL output, you'll need to change the NULL value into the string 'NULL'. That also means that you'll need to cast the numeric value to a string to have a consistent type for the field; ``` SELECT DISTINCT col1, ( SELECT COALESCE(CAST(col2 AS VARCHAR),'NULL')+',' FROM @temp t2 WHERE t2.col1 = t1.c...
A NULL value is not the string NULL. It is simply absence of information. What you could do is to force a NULL value to be treated as the string NULL for your purposes like so: ``` SELECT CASE WHEN col2 IS NULL THEN 'NULL' ELSE col2 END + ',' ``` To make it more concise, you may use `isnull(col2,'NU...
Concat with NULL value
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I have a stored procedure to update data, which is being called through C#. I also have several triggers set to my table which insert audit information to audit table when the data is changed. The problem is I have two columns in audit table called changedBy(UserName) and changeSetID, which I can only retrieve them fr...
I actually figured out a workaround about this. First, I pass my username and changesetID from C# to SQL stored procedure as parameters. Inside my stored procedure, I set CONTEXT\_INFO to the combination of userName and changeSetID ``` Declare @userAndSetID VARBINARY(128) SET @UserName = @UserName + ',' + @ChangeSetI...
Several approaches: 1) As granadaCoder, suggested, add those columns to your updated table, so that the trigger will be able to access them 2) Disable the trigger at the beginning of your proc, include the inserts to the audit tables in your proc (instead of letting the trigger do them), then re-enable the trigger at...
How to set two dynamic temporary global variables for triggers in SQL server?
[ "", "sql", "sql-server", "stored-procedures", "triggers", "global-variables", "" ]
I got in trouble with a sql script as this: ``` SELECT A, B, C, CASE WHEN D < 21 THEN '0<20' WHEN D < 51 THEN '21-50' WHEN D < 101 THEN '51-100' ELSE '>101' END AS E COUNT(*) FROM TABLE_X GROUP BY A, B, C, D; ``` Resultset like this; ``` A B C D count(*) CAR 1 2 21-50 1 ...
The problem here is that you're grouping by `D` first and only then applying the `case` logic. If you add `D` to the select list, you'd see results that probably look like this: ``` A B C D E count(*) CAR 1 2 20 21-50 1 CAR 1 2 30 21-50 1 BIKE 1 3 7 0-20 1 ...
The below query should work. Basically, I am just pulling the count(1) function and hence the group by clause to an outer query while leaving all the rest functionality to the inner query. ``` SELECT A,B,C,E, count(1) from ( SELECT A, B, C, CASE WHEN D < 21 THEN '0<20' WHEN D < 51 THEN '21-50' WHEN D <...
Sql grouping trouble
[ "", "sql", "" ]
I have a select result like this: ``` ID | DATE ---------------- 10 | 2014-07-23 7 | 2014-07-24 8 | 2014-07-24 9 | 2014-07-24 1 | 2014-07-25 2 | 2014-07-25 6 | 2014-07-25 3 | 2014-07-26 4 | 2014-07-27 5 | 2014-07-28 ``` The result above is ordered by date. Now, I want to select the one previous row before: ...
Here's one way... ``` DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (ID INT NOT NULL PRIMARY KEY ,DATE DATE NOT NULL ); INSERT INTO my_table VALUES (10 ,'2014-07-23'), (7 ,'2014-07-24'), (8 ,'2014-07-24'), (9 ,'2014-07-24'), (1 ,'2014-07-25'), (2 ,'2014-07-25'), (6 ,'2014-07-25'), (3 ,'2014-07-...
You can add a row id to the select like this ``` SELECT @rowid:=@rowid+1 as rowid, t1.* FROM yourdatabase.tablename t1, (SELECT @rowid:=0) as rowids; ``` Then you can run a simple query to get the lower rowid from the input.
How to select a row before a specific row on MySQL, if the table is ordered by date?
[ "", "mysql", "sql", "database", "" ]
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inus...
Check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters. ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count DECLARE @SQLString nvarchar(500); DECLARE @ParmDefi...
Shouldn't be "SET" instead of "select" ? E.g., changing: ``` select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ``` for: ``` SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ```
Converting dynamic sql query's COUNT result to INT
[ "", "sql", "sql-server", "" ]
I am having issues with a query I have written in that the data warehouse we use does not want to accept the query as it contains a portion which is Parallel from Serial or S->P. When I run the explain plan it gives me a Trivial error, yet when I run the query it errors out. Any thoughts would be helpful. **Query** `...
As for the Serial to Parallel, I was unable to find a solution, but it seems to be a trivial issue and will only make the query take a few seconds longer. The error ORA-01861 that was being seen was able to be resolved through the use of changing the line doi.ORDER\_DAY= '2009/04/06' To doi.ORDER\_DAY = TO\_DATE ('2009...
This should be the same as your query. ``` SELECT doi.ORDER_ID AS "PO" , doi.DISTRIBUTOR_ID AS "Vendor ID" , doi.ISBN AS "ASIN" , doi.QUANTITY_ORDERED AS "Quantity Confirmed" FROM D_DISTRIBUTOR_ORDER_ITEMS doi JOIN PRODUCT_SEGMENT_MEMBERSHIP psm ON doi.ISBN = psm.ASIN AND psm.SEGMENT_ID = 784885 WHERE doi.ORDER_DAY =...
Is there a way to resolve Parallel from Serial in SQL?
[ "", "sql", "oracle", "parallel-processing", "" ]
I have a stored procedure that returns two columns like this; ![enter image description here](https://i.stack.imgur.com/ujEFU.png) I want to know if it's possible for me to create a comma delimited string from the iTypeID column of the result set. I'm just not sure how to loop through that result set to create the st...
You can use [COALESCE](http://msdn.microsoft.com/en-gb/library/ms190349.aspx) ``` DECLARE @Str varchar(100) SELECT @Str = COALESCE(@Str + ', ', '') + CAST(iTypeID AS varchar(5)) FROM TableName Select @Str ```
This could create table variable to insert data from sproc and then select output into one line string. ``` DECLARE TABLE @tmpBus ( iTypeId INT, Desc INT ) INSERT INTO @tmpBus EXEC cfn_PlanningGoalGetType 0,'xmlString' DECLARE @CodeNameString varchar(100) SELECT @CodeNameString = STUFF( (SELECT ',' + iTyp...
Looping through stored procedure results to create string
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a very simple query , and yet I can't get it to work like I want it to. I have 2 tables, `A` and `B` which are very similar and look like this : `A` : ``` +------+----------+---------+ | a_id | a_cnt_id | a_value | +------+----------+---------+ | 1 | 848 | 0.5 | | 2 | 848 | 3 | | 3 ...
Adding a `WHERE` clause will filter the results to what the where suggests. So if you have `where a.a_cnt_id = 849` it will get only these rows, not the ones with the `null`. Move your filters to the join: ``` select distinct a.a_id, b.b_id, a.a_value, b.b_value from b full join a on b.b_id = a.a_id and a.a_cnt_id = 8...
I don't remember where I found this but here you go: ![enter image description here](https://i.stack.imgur.com/IbX73.jpg) EDIT: The link of the image belongs to [Visual-Representation-of-SQL-Joins](http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins). Thanks @jyparask
Simple outer join between two tables not working
[ "", "sql", "oracle", "" ]