Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Currently I have a table that has a user\_type column and will only show the row if the user matches that user\_type. I want to make it so there can be multiple user\_types set without duplicating the data and without creating another table. I thought that I could convert the column from an int to varchar and have it b...
There'e many examples of TSQL code that split separated string into "array" or table variable. For example using this function: <https://stackoverflow.com/a/10914602/961695>, you can rewrite your query as: ``` SELECT p.* FROM perm p JOIN dbo.splitstring('50,40,30') s ON p.user_type = s.name ``` (and avoid dynamic SQ...
I'll give you the way that works with what you have now (horrible) and the right way to do it (as @paqogomez suggested). This way involves abusing `PARSENAME`, and only works with SQL Server and only if perm.user\_type has 4 or fewer user types. There's another way that doesn't have the limit of 4--it involves abusing ...
Using SQL, how do I convert a comma separated list to be used with the IN command?
[ "", "sql", "sql-server", "join", "sql-like", "sql-in", "" ]
Was not sure how to express this in the title. So here's the deal: I have a table storing information about currency pairs used in foreign exchange rates: ``` PAIR_ID | BASE_CURRENCY | TERM_CURRENCY | ATTRIBUTE1 | ATTRIBUTE2 ... ``` Ideally I should have another table to store the currency symbols (master data), say ...
Approach 2 seems like a good idea at first, but there are a few problems with it. I'll list them all even though 1 and 2 don't really apply as much to you, since you're only using it with 3-digit ISO codes: 1. **Foreign key references can take up more room.** Depending on how long you need to make your VARCHARs, they ...
In both cases you need a join so you are not saving a join. Option 1 adds an ID. This ID will default to have a clustered index. Meaning the data is sorted on disk with the lowest ID first and the highest ID at the end. This is a flexible option that will allow easy future development. Option 2 will hard code the sym...
Use the values of a column (instead of numeric ids) as foreign key reference
[ "", "sql", "database", "oracle", "" ]
I have the tables: ``` +------------+ | Ingredient | +------------+ | id | +------------+ | name | +------------+ +---------------+ | Relingredient | +---------------+ | id_ingredient | +---------------+ | id_recipe | +---------------+ +--------+ | Recipe | +--------+ | id | +--------+ | name ...
Try something like this: ``` SELECT R.id, R.name FROM Recipt R JOIN Relingredient RI ON R.Id = RI.Id_recipe JOIN Ingredient I ON RI.Id_ingredient = I.Id WHERE I.name = 'onion' OR I.name='oil' GROUP BY R.id, R.name HAVING COUNT(I.name) = 2 ```
Try this : ``` SELECT R.id, R.name FROM Recipe R Where R.Id in ( Select RI.Id_recipe From Relingredient as RI INNER JOIN Ingredient as I ON RI.Id_ingredient = I.Id WHERE I.name = 'onion' ...
many-to-many select with complex condition
[ "", "sql", "select", "many-to-many", "" ]
I'd like to be able to print some debug information from sql script / function. Of course, I can do this by ``` RAISE NOTICE 'hello!' ``` But I also need to print a whole table's data. This doesn't work: ``` RAISE NOTICE '%' (SELECT * FROM table1) ``` Is it possible and how?
The most straightforward way would be to iterate over the rows in a `for loop` and use `RAISE NOTICE` containing each column you're interested in interpolated in it. i.e. something like: ``` FOR items IN SELECT * FROM table1 LOOP RAISE NOTICE 'col1: %, col2: %', quote_ident(items.col1), quote_ident(items.col2); E...
Since postgres 9.3 you can use `to_json()` to convert record into text suitable for notice, ``` RAISE NOTICE '%', to_json(record1); ```
Raise notice to print a table's data
[ "", "sql", "postgresql", "postgresql-9.2", "" ]
I am writing following query to fetch all details of table `bill_details`. ``` select * from bill_details; ``` Along with data, I also want to fetch number of records in this table.
``` SELECT *, (SELECT COUNT(*) FROM bill_details) AS cnt FROM bill_details ``` Every row of the results will have an additional column with the row count.
``` mysql_num_rows(mysql_query("select * from bill_details")) ```
How to fetch all data and also the number of records in table
[ "", "mysql", "sql", "" ]
I have three tables and trying to use left join and inner join in same query with the three tables. But its not working the way i want. i have four tags A,B,C,D and only two tags are used by agent\_id=22. Below is the query i am using ``` SELECT MDT.tags,COUNT(MDTM.tag_id) AS tagCount FROM mp_desk_agent_added_cust...
There are four tags and you want four result records, one per tag. So select from the tags table. You get the count with a sub-select. ``` select tag_id, tag, ( select count(*) from mp_desk_tags_match dtm where dtm.tag_id = dt.tag_id and u_cust_id in ( select u_cust_id from mp_de...
Looking at your table structure your query should be: ``` SELECT MDT.tags,COUNT(MDTM.tag_id) AS tagCount FROM mp_desk_agent_added_customers MDAC INNER JOIN mp_desk_tags_match MDTM ON MDAC.u_cust_id=MDTM.u_cust_id LEFT JOIN mp_desk_tags MDT ON MDTM.tag_id=MDT.tag_id WHERE MDAC.agent_id=22 G...
Left join and Inner join in same mysql query not working
[ "", "mysql", "sql", "join", "left-join", "" ]
I wish to take table A and create something like table B, but based on an arbitrary set of split dates contained in table C. For example, (note it is not always true that start\_date = inception\_date, and so inception\_date must be preserved rather than derived from start\_date; this actually represents hundreds of f...
Here's a hybrid SQL/datastep approach - but it is shorter! Input the data (taken from the answer given by @Joe):- ``` data table_a; informat start_date end_date date9.; format start_date end_date date9.; input customer_id $ start_date end_date; datalines; aaa 18JUN2011 17JUN2012 aaa 18JUN2012 17JUN2013 b...
Data step solution. First, sample data (I left out the other date variable, I think it's unimportant to the solution although of course you'll want it in production): ``` data table_a; informat start_date end_date date9.; format start_date end_date date9.; input customer_id $ start_date end_date; datalines; aaa 18JUN...
Create table that splits records on specific dates using SAS
[ "", "sql", "date", "sas", "" ]
This is my select statement: ``` SELECT * FROM Persons p WHERE p.Name= ISNULL(@Name, p.Name) ``` it `@Name` is null it only selects the rows where `Name` is not NULL but not the one with `NULL` value. What has to be done to select desired rows?
``` DECLARE @name varchar(290) ='Thomas' SELECT * FROM Persons P WHERE exists(select name intersect select coalesce(@name, name)) ```
When `@Name` is `NULL` the query became ``` SELECT * FROM Persons P WHERE p.Name = p.Name ``` and `NULL` is not equal `NULL`, as it mean unknown value and two unknown values are not equal. A way to get all the data is ``` SELECT * FROM Persons P WHERE COALESCE(p.Name, N'a') = COALESCE(@Name, p.Name, N'a') ``` ...
Select rows where one cell value is equal to parameter or everything in ms sql
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am making a shopping cart project. I want to copy a data from table to another one but when i use this query ``` USE PRODUCTS SELECT NAME,PRICE,BOUGHT INTO CART FROM COMPUTERS ``` i can only copy 1 data and after the first run it says table already created. What i want to do is append the old table not try to cr...
``` insert into CART (NAME, PRICE, BOUGHT) select NAME, PRICE, BOUGHT from COMPUTERS ```
How about: ``` USE PRODUCTS SELECT NAME,PRICE,BOUGHT FROM COMPUTERS INSERT INTO CART ```
Sql copying a data from table to another table
[ "", "sql", "sql-server", "" ]
I don't know what's the proper syntax but hope you understand what I'm trying to achieve: ``` SELECT Count(BookCategory) AS TotalBookAC FROM Passenger WHERE BookCategory='AC'; SELECT Count(BookCategory) AS TotalBookGen FROM Passenger WHERE BookCategory='General'; ... ``` What `keyword` is needed to **join** two or mo...
You want to select all records from table Passenger and count occurences. So you must scan the whole table and count conditionally. In standard SQL you would use CASE WHEN; in MS Access you'd use IIF. The counting is done with SUM; you add a 1 per match, so you are actually counting. ``` SELECT TrainNumber, SUM( ...
Create a separate query for each count you need. Let's say they will be called qryTotalSeatsGen, qryTotalSeatsAC, qryTotalBookGen, qryTotalBookAC. Each query will have two fields: `TrainNumber` and `Total` Now create a final query with all the above mentioned queries. Join them all on `TrainNumber` and include each ...
Multiple SELECT statements with different WHERE condition in one query
[ "", "sql", "ms-access", "" ]
When inner joining two tables the results are essentially "or" driven. So for example if I had a parent and child table, and I wanted to know that children who have red or blond hair I would write something like: ``` SELECT parent.parent_name FROM parent INNER JOIN child ON parent.parent_ID = child.parent_ID WHERE chi...
This is a great example of when to use a having clause. You know you want at least one of each color so a distinct will be necessary. The where clause limited to blond or red already. We grouped by parent so the having clause is only looking at each parents, not all kids; and if the distinct count is 2, then it must b...
I would probably hit the child table twice, once for blond and once for red: ``` SELECT parent.parent_name FROM parent INNER JOIN child BlondChild ON parent.parent_ID = Blondchild.parent_ID and Blondchild.hair = 'blond' inner join chile RedChild on parent.parent_id = RedChild.parentid and RedChild.hair = 'red' ```
SQL Query Joining Multiple tables using and critrea
[ "", "sql", "inner-join", "" ]
I have two tables, but IMO only the first is necessary for this question. ``` conversation_id user conv1 randomuser conv1 admin conv2 derp conv3 derp conv3 admin conv3 herp conv4 derp conv4 admin ``` Now I want to select the conversation\_id ...
If you have only few values you can use `EXISTS`/`NOT EXISTS`: ``` SELECT DISTINCT c1.conversation_id AS conv_id FROM chat_och_users_in_conversation c1 WHERE EXISTS ( SELECT 1 FROM chat_och_users_in_conversation c2 WHERE c1.conversation_id = c2.conversation_id AND c2.user = 'derp' ) AND EXISTS ( ...
Not sure if you want all value: ``` SELECT conversation_id AS conv_id FROM chat_och_users_in_conversation WHERE USER IN ('derp', 'admin') GROUP BY conversation_id HAVING COUNT(DISTINCT USER) = 2 ``` Or only the last one? ``` SELECT MAX(conversation_id) AS conv_id FROM chat_och_users_in_conversation WHERE USER ...
Find id by matching the values
[ "", "sql", "relational-division", "" ]
I have two tables (A and B) that contain ID's however in table B some records have these ID's grouped together e.g the IDExec column may consist of a record that looks like 'id1 id2'. I'm trying to find the ID's in table A that do not appear in table B. I thought that by using something like: ``` SELECT * FROM A WHER...
This data should be normalized, storing multiple values in one field is a bad idea. A workaround is using `LIKE`: ``` SELECT * FROM A WHERE NOT EXISTS( SELECT * FROM B WHERE ' '+B.ExecID+' ' LIKE '% '+A.ExecID+' %') ``` This is using space delimited values per your example.
This is kind of crude, but it will give you all of the entries in `A` that are not contained in `B`. ``` SELECT * FROM A WHERE A.ExecID not in (SELECT ExecID from B); ```
SQL Contains query
[ "", "sql", "sql-server", "" ]
I got query: ``` INSERT INTO peekquick.file_storage (file_id, size, content, file_desc, files_set_id, content_type, file_name, answer_id) VALUES (file_id = 62745251829, size = 1295585,...
> Make sure the column set as your PRIMARY KEY is set to AUTO\_INCREMENT **`INT`** has a [maximum signed value of 2147483647](http://dev.mysql.com/doc/refman/5.0/en/integer-types.html). Any number greater than that will be truncated to that value. In Sql Server define the column like this... ``` FILE_ID [PrimaryI...
Remove the FILE\_ID=... after VALUES. Like this: ``` INSERT INTO peekquick.FILE_STORAGE (FILE_ID, SIZE, CONTENT, FILE_DESC, FILES_SET_ID, CONTENT_TYPE, FILE_NAME, ANSWER_ID) VALUES (62745251829, 1295585, '', '', '', 'image/jpeg', 'witryna.jpeg', 176458); ``` Make sure you primary key is inserted correctly, make it ...
SQL error : duplicate entry for value'0' PRIMARY
[ "", "mysql", "sql", "" ]
i need to do an update query on a postcode field to create a space between. E.g is there are 7 characters e.g `HP114GT` i want to have `HP11 4GT` or if there are 6 e.g `HP14GT` i want `HP1 4GT`. any help would be great!!
``` UPDATE Table SET Column = CASE WHEN LEN(Column) = 6 THEN STUFF(Column, 4, 0, ' ') WHEN LEN(Column) = 7 THEN STUFF(Column, 5, 0, ' ') END WHERE CHARINDEX(' ', Column, 1) = 0 AND LEN(Column) BETWEEN 6 AND 7 ```
Please try below query for SQL Server: ``` UPDATE tbl SET Col=LEFT(Col, len(Col)-3)+' '+RIGHT(col, 3) WHERE LEN(Col)>3 AND CHARINDEX(' ', Col, 1)=0 ```
SQL Update, Space inbetween a Postcode
[ "", "sql", "sql-server", "string", "sql-update", "" ]
# What I Need I have a database with fields that can contain long phrases of words. I wanted the ability to quickly search for a keyword or phrase in these columns, but when searching a phrase, I want to be able to search the phrase like Google would, returning all rows that contain all of the specified words, but in ...
I found [another question on here](https://stackoverflow.com/questions/506034/) that deals with this same topic. In fact, the post detailing the method is even titled "[A Google-like Full Text Search](http://www.sqlservercentral.com/articles/Full-Text+Search+%282008%29/64248/)". It uses an open-source library called [I...
Have you looked at using the Semantic Index functions in SQL Server 2012? They are built on full text indexes but extend them to include details about word frequency. I used them just recently to build a word cloud and it was really good. There are some good articles to be found on the internet and you can also searc...
How do you use T-SQL Full-Text Search to get results like Google?
[ "", "sql", "sql-server", "" ]
I have an XML block that I am sending to my stored procedure. ``` <vehicles> <licensePlate>ABC123</licensePlate> <vehicle> <model>Ford</model> <color>Blue</color> <carPool> <employee> <empID>111</empID> </employee> <employee> <empID>222</empID> </employee> <employee> ...
[You can insert the node directly](https://meta.stackexchange.com/q/185681) ``` INSERT INTO licensePlates (carColor, carModel, licencePlate, empId, dateAdded, carPoolMembers) SELECT ParamValues.x2.value('color[1]', 'VARCHAR(100)'), ParamValues.x2.value('model[1]', 'VARCHAR(100)'), ParamVa...
Assuming your stored procedure has a parameter called `@Input XML`, you could use this code: ``` INSERT INTO dbo.YourTable(XmlColumn) SELECT @input.query('/vehicles/vehicle/carPool') ``` That should select the `<carPool>` XML tag and insert it into the XML column of your table.
TSQL XML Parsing
[ "", "sql", "sql-server", "xml", "t-sql", "" ]
I have the following table structure: `Value` (stores random integer values), Datetime` (stores purchased orders datetimes). How would I get the average value from all `Value` rows across a full day? I'm assuming the query would be something like the following ``` SELECT count(*) / 1 FROM mytable WHERE DateTime = ...
Looks like a simple `AVG` task: ``` SELECT `datetime`,AVG(`Value`) as AvgValue FROM TableName GROUP BY `datetime` ``` To find average of a specific day: ``` SELECT `datetime`,AVG(`Value`) as AvgValue FROM TableName WHERE `datetime`=@MyDate GROUP BY `datetime` ``` Or Simply: ``` SELECT AVG(`Value`) as AvgValue FROM...
You can `GROUP BY` the `DATE` part of `DATETIME` and use `AVG` aggregate function to find an average value for each group : ``` SELECT AVG(`Value`) , DATE(`Datetime`) FROM `mytable` GROUP BY DATE(`Datetime`) ```
Calculate average column value per day
[ "", "mysql", "sql", "datetime", "" ]
I need to construct a query that returns rows that have certain empty fields. For example I have 300 records that contain a `Name, Address and City`. Once one or more fields are empty they need to be returned. If I for example have a row that has an empty `City` and a row that has an empty `address`, both need to be r...
``` SELECT * FROM TABLE WHERE Name IS NULL OR Name = '' OR City IS NULL OR City = '' OR [Address] IS NULL OR [Address] = '' ```
Well we have the `IS NULL OR` and the `NULLIF`, so I take the `COALESCE` ``` SELECT Name , City , Address , ... FROM TABLE WHERE COALESCE(Name,'') = '' OR COALESCE(City,'') = '' OR COALESCE([Address],'') = '' ```
SQL Server Query check empty fields for a number of columns
[ "", "sql", "sql-server", "ssms", "" ]
I'm having trouble building my query, I'm getting an error on Unknown Column, j.id in on clause. Here's my query so far ``` SELECT j.id, j.title, venues.name as venueName, ja.completed FROM dbsivcmsnew.jobs AS j, venues LEFT JOIN dbsiv.job_applications AS ja ON ja.jobId = j.id WHERE j.v...
Well, you'r mixing syntaxes for "table joining", which is... not a good idea Just add your additional clause in the LEFT JOIN should do the trick ``` SELECT j.id, j.title, v.name as venueName, ja.completed FROM jobs j inner join venues v on v.id = j.venueID left join dbsiv.job_applications ja on ...
Change your select to: ``` SELECT j.id, j.title, venues.name as venueName, ja.completed FROM dbsivcmsnew.jobs AS j join j.venueId = venues.id venues on LEFT JOIN dbsiv.job_applications AS ja ON ja.jobId = j.id WHERE j.closingDate > UNIX_TIMESTAMP() AND j.active = 1 ORDER BY j....
Unknown column error when joining from 2 different databases
[ "", "mysql", "sql", "" ]
I have 4 tables tab\_1, tab\_2, tab\_3 and tab\_4 how can i get the count of all the 4 tables using one single dynamic query? ``` expected result: count of tab_1 = count of tab_2 = count of tab_3 = count of tab_4 = ``` Thanks in Advance
It sounds like you want to run four separate queries, not a single query. It sounds like you're describing something like ``` DECLARE TYPE tbl_list IS TABLE OF VARCHAR2(30); l_tables tbl_list := tbl_list( 'table_1', 'table_2', 'table_3', 'table_4' ); l_cnt pls_integer; BEGIN FOR i IN 1 .. l_tables.count LOO...
Please try: ``` SET SERVEROUTPUT ON DECLARE result1 NUMBER; result2 NUMBER; result3 NUMBER; result4 NUMBER; BEGIN select count(*) into result1 from tab_1; select count(*) into result2 from tab_2; select count(*) into result3 from tab_3; select count(*) into result4 from tab_4; DBMS_OUTPUT.PUT_LI...
Dynamic SQL Query using loops
[ "", "sql", "oracle", "dynamic", "count", "" ]
Suppose I have the following table `table`: ``` +---------+---------+ | column1 | column2 | +---------+---------+ | A | B | | A | A | | A | A | | C | D | | B | B | | B | B | +---------+---------+ ``` I'm querying the DB in order to get all the...
Does this do what you want? ``` select groupnum, column1, column2, seqnum from (select t.*, count(*) over (partition by column1, column2) as cnt, dense_rank() over (order by column1, column2) as groupnum, row_number() over (partition by column1, column2 order by column1) as seqnum from ...
From the logical perspective... ``` A | A A | A ``` ...is the same thing as... ``` A | A | 2 ``` So why not just: ``` SELECT column1, column2, COUNT(*) FROM T GROUP BY column1, column2 HAVING COUNT(*) > 1 ``` ? You'll get a result such as... ``` A | A | 2 B | B | 2 ``` .....
Differentiate between groups of duplicated values
[ "", "sql", "database", "oracle", "" ]
I have 2 MYSQL TABLES: ``` TABLE 1: PRODUCTID | BRAND | BASECOLOR | COLORNAME Table 2: PRODUCTID | BRAND | COLORNAME ``` In table 1 the field 'COLORNAME' is empty and the fields 'PRODUCTID' and 'BRAND' must match in the two tables. I need to moove the row 'COLORNAME' from table2 to table 1. I've done this SQL requ...
Try this: ``` update table1 tab1, table2 tab2 set tab1.colorname=tab2.colorname where tab2.brand=tab1.brand; ```
``` INSERT INTO tablel (COLORNAME) (SELECT t2.COLORNAME FROM table2 t2,tablel t1 WHERE t1.PRODUCTID = t2.PRODUCTID AND t1.BRAND = t2.BRAND) ```
Migrating row from one table to another with conditions [MYSQL]
[ "", "mysql", "sql", "database", "" ]
I am using the following Select as part of a bigger query. Can someone here tell me how I can refer to the manually defined name "`amountUSD`" in my Case statement ? I am always getting the following error when trying to save it this way: "`Invalid column name 'amountUSD'.`" A work-around would probably be to insert ...
Will this work? ``` SELECT (CASE WHEN R.currency = 'USD' THEN '1' ELSE E.exchange_rate END) AS exchangeRate, (R.amount * E.exchange_rate) AS amountUSD, ( CASE WHEN (R.amount * E.exchange_rate) < 1000 THEN '18' WHEN (R.amount * E.exchange_rate) < ...
You can not - because amountUSD does not exist at this point. It only exists in the output projection. You have 2 choices: * Not use amountUSD or * Not use your table, but make a 2 step query, first project amountUSD, THEN select over that and make the case there (approvalLevel). This is not as hard as it sounds as y...
SQL Server: how to use manually defined column name for case statement
[ "", "sql", "sql-server", "stored-procedures", "case", "" ]
I have the following statement: ``` SELECT DISTINCT COUNT(Z.TITLE) AS COUNT FROM QMFILES.MPRLRREQDP Y, QMFILES.MPRLRTYPP Z WHERE Y.REQUEST_TYPE = Z.ID AND Y.REQUEST_ID = 13033; ``` On this particular result set, if I removed `DISTINCT` and `COUNT()` the result set will return nine rows of the exact same dat...
`SELECT DISTINCT COUNT(Z.TITLE)` counts the number of rows with a value for `Z.TITLE` (nine). The `DISTINCT` is superfluous, since the `COUNT` has already aggregated the rows. `SELECT COUNT(DISTINCT Z.TITLE)` counts the number of distinct values in `Z.TITLE` (one).
The COUNT results in one new record which contains the number of items in the SELECT statement. DISTINCT is looking for the results of the COUNT, which is only that single record after all.
Why would DISTINCT COUNT() return 9 instead of 1?
[ "", "sql", "db2", "ibm-midrange", "" ]
I am new to mySQL development and I'm trying to set a simple hotel reservation database. One part of the database is the list of tables below: * Hotels * Rooms The relationship is: One hotel contains many rooms, but one room belongs to one specific hotel (one-to-many relationship). So I designed the table like this: ...
InnoDB tables do not support auto-increment that tracks different max values per hotel, in the way you describe. InnoDB tracks only one auto-increment value per table. MyISAM tables do support this feature, but that only works because MyISAM does table-level locking, so it is able to scan the table for the largest id ...
Why is Room Number an auto inc? What about suites, what about hotels where room numbers have gaps? I personally would be tempted by a room\_id auto inc surrogate, but that's another issue and in general a highly opinionated one. Room number is a natural key, it should not be auto-incrementing.
Auto_Increment: how to auto_increment a combined-key (ERROR 1075)
[ "", "mysql", "sql", "" ]
I am doing report in SSRS, I need dataset column for calculating the number of leap years between two dates in t-SQL. I found the function for single input parameter whether it is the leap year or not but for my requirement two parameters in function or any t-SQL statement. Thanks..waiting for anybody reply
I thought, will add as another answer. ``` DECLARE @A DATE = '2008-03-23', @B DATE = '2012-04-20' DECLARE @AM INT,@AY INT,@BM INT,@BY INT SET @AM = DATEPART(MONTH,@A), --3 @AY = DATEPART(YEAR,@A), --2008 @BM = DATEPART(MONTH,@B), --4 @BY = DATEPART(YEAR,@B) --2012 DECLARE @COUNT INT = 0 W...
Number of leap days between two dates. ``` DECLARE @StartDate DATETIME = '2000-02-28', @EndDate DATETIME = '2017-02-28' SELECT ((CONVERT(INT,@EndDate-58)) / 1461 - (CONVERT(INT,@StartDate-58)) / 1461) ``` -58 to start counting from 1st March 1900 and / 1461 being the number of days between 29th Februaries. N...
how to calculate number of leap years between two dates in t-sql?
[ "", "sql", "sql-server", "t-sql", "reporting-services", "" ]
The solution to the topic is evading me. I have a table looking like (beyond other fields that have nothing to do with my question): NAME,CARDNUMBER,MEMBERTYPE Now, I want a view that shows rows where the cardnumber AND membertype is identical. Both of these fields are integers. Name is VARCHAR. Name is not unique, ...
Since you mentioned names can be duplicated, and that a duplicate name still means is a different person and should show up in the result set, we need to use a GROUP BY HAVING COUNT(\*) > 1 in order to truly detect dupes. Then join this back to the main table to get your full result list. Also since from your comments...
> What's the most efficient way of doing this? I believe a `JOIN` will be more efficient than `EXISTS` ``` SELECT t1.* FROM myTable t1 JOIN ( SELECT cardnumber, membertype FROM myTable GROUP BY cardnumber, membertype HAVING COUNT(*) > 1 ) t2 ON t1.cardnumber = t2.cardnumber AND t1.membertype = t2.memb...
SQL - select rows that have the same value in two columns
[ "", "mysql", "sql", "join", "" ]
As I understand I have a denormalized table. Here is some list of table columns: ``` ... C, F, T, C1, F1, T1, .... C8, T8, F8..... ``` Is it possible to select those values in a rows? Something like this: ``` C, F, T C1, F1, T1 ...... C8, F8, T8 ```
You can do it easily with a `union all`: ``` select C, F, T from table t union all select C1, F1, T1 from table t union all . . . select C8, F8, T8 from table t; ``` Note the use of `union all` instead of `union`. `union` does automatic duplicate elimination, so you might not get all your values with `union` (as well...
``` select c,f,t from table union all select c1,f1,t1 from table union all select c8,f8,t8 from table ``` Make sure to filter by WHERE clause each SELECT statement.
Denormalized table. SQL Select
[ "", "sql", "db2", "" ]
I want to show blank '' instead of Zero value of Expression field. If exp is of INT datatype. whenever I try to use(case when exp1 is 0 then '' else exp1 end as exp1)but it still gets 0 as output.any help appreciated. Thanks
If `exp` is a numeric type you'll need to convert it to a string using [`CAST` or `CONVERT`](http://msdn.microsoft.com/en-us/library/ms187928.aspx). Also, I don't believe `exp1 is 0` will work; I think you're looking for `exp1 = 0` instead. Try something like this this: ``` (case when exp1 = 0 then '' else cast(exp1 ...
I used RegEx ``` { cast(trim( replace(to_char(value),'0','' )) as int) } ```
replace 0 with blank spaces
[ "", "sql", "sql-server", "t-sql", "" ]
I am having trouble with some logic here. Trying to get a count of rows where S.ID's not in my subquery. ``` COUNT(CASE WHEN S.ID IN (SELECT DISTINCT S.ID FROM...) THEN 1 ELSE 0 END) ``` I am recieving the error: ``` Cannot perform an aggregate function on an expression containing an aggregate or a subquery. ``` H...
Maybe something like this? ``` SELECT COUNT(*) FROM .... WHERE ID NOT IN (SELECT DISTINCT ID FROM ...) ```
Using `EXISTS` : ``` SELECT COUNT(t.*) FROM table1 t WHERE NOT EXISTS (SELECT * FROM table2 WHERE ID = t.ID) ```
TSQL Count Case When In
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I'm looking at the documentation for the Play framework and it appears as though [SQL is being written in the framework](https://github.com/playframework/playframework/blob/master/documentation/manual/scalaGuide/tutorials/todolist/ScalaTodoList.md#persist-the-tasks-in-a-database). Coming from Rails, I know this as a b...
One of the feature/defects (depending on who you ask) of Play is the **there is no ORM**. (An ORM is an object-relational mapper/mapping; it is the part of Rails, Django, etc. that writes your SQL for you.) * Pro-ORM: You don't have to write any SQL. + Ease-of-use: Some developers unused to SQL will find this easie...
In addition to Paul Draper's excellent answer, this post is meant to tell you about what Play developers usually do in practice. **TL;DR: [use](https://github.com/playframework/play-slick) [Slick](http://slick.typesafe.com/)** Play is less opinionated than Rails and gives the user many more choices for their data sto...
Writing SQL in Play with Scala?
[ "", "sql", "scala", "orm", "playframework", "" ]
I am trying to get the following result in Sql: example: 23/05/2014 to 20142305 but get this: ``` select convert(decimal, convert(datetime, '5/23/2014')) ``` result:41780 anyone know how you can get the following format?? (if possible ??) regards and thanks
In many databases (including SQL Server), you can just do: ``` select 10000 * year(datetime) + 100 * month(datetime) + day(datetime) ``` Some databases don't support these functions, so you might need `extract(datepart from datetime)` or a similar function.
You can try this ``` SELECT CAST(CONVERT(VARCHAR(8), datetime, 112) AS DECIMAL) ```
convert datetime (mm/dd/YYYY) to decimal(YYYYmmDD)
[ "", "sql", "sql-server-2008", "" ]
I have a table with PO#,Days\_to\_travel, and Days\_warehouse fields. I take the distinct Days\_in\_warehouse values in the table and insert them into a temp table. I want a script that will insert all of the values in the Days\_in\_warehouse field from the temp table into the Days\_in\_warehouse\_batch row in table 1 ...
One more way without a TEMP table and DELETE. ``` UPDATE T SET [Days_in_warehouse_batch] = [Days_in_warehouse]; INSERT INTO T ([PO], [Days_to_travel], [Days_in_warehouse], [Days_in_warehouse_batch]) SELECT T.PO, T.Days_to_travel, T.Days_in_warehouse, DAYS_Table.D...
What you're looking for is the `cartesian product` between your two tables. ``` select t1.po, t1.daystotravel, t1.daysinwarehouse, temp.daysinwarehousebatch from table1 t1, temp ``` The easiest way I can think of updating table1 with these values is to insert them, and then delete the originals. ``` insert into tabl...
Insert rows based on number of distinct values in another table in SQL
[ "", "sql", "sql-server", "t-sql", "" ]
i have 2 tables, one is called `TEMP` and the other one is called `MAIN`. So all what i am trying to do is to check if all records from the `TEMP` table are in the `MAIN` table. The logic should be all records from temp table must also be in the main table but when i run the sql query here; it does not give me any reco...
I suspect your problem has something to do with NULLs. If either GRP\_NM or GRP\_VAL is null in either table, then GRP\_NM + GRP\_VAL will be null, and your IN and EXISTS statements get totally bollixed up. In any case, try this one out: ``` INSERT MAIN (GRP_NM, GRP_VAL) select GRP_NM, GRP_VAL from TEMP except se...
``` INSERT INTO MAIN(GRP_NM, GRP_VAL ) SELECT GRP_NM, GRP_VAL FROM TEMP WHERE NOT EXISTS (SELECT 1 FROM MAIN WHERE GRP_NM = TEMP.GRP_NM AND GRP_VAL = TEMP.GRP_VAL ) ```
issues using if exists statement in sql
[ "", "sql", "sql-server", "t-sql", "" ]
I have a strange bug here. I'm trying to limit the result from the query below to just ONE row/result: ``` SELECT userEmail FROM [LunchUsersAvailable] WHERE LunchGroupsID = '301' AND availableDate = '2015-01-01' AND userEmail != 'userEmail@company.com' EXCEPT ( SELECT DISTINCT (COALESCE([user1], [...
I got it! The TOP 1 or MIN is processing **before** the EXCEPT which means that it will first get the TOP 1 from the available users result and only them apply the EXCEPTION. **Solution**: get the full list of available users, run the exception and only then get TOP 1 ``` SELECT TOP 1 useremail FROM ( SELECT use...
This suggests that `userEmail` takes on multiple values, one of which is the empty string (`''` -- not `NULL`). The first row returned by `userEmail` has this empty value. The `min()` would capture it. The `max()` doesn't. Put in a check that `userEmail <> ''` or just use `max()`. If you want the `min()`, you could ...
SQL - TOP 1 and MIN doesn't work but MAX works
[ "", "sql", "max", "min", "" ]
I need to copy a table into a new table on SQL server 2008. Also, add a new column into the new table. The values of the new column depends on the compare result between the new table and another table. Example, Table1: ``` col1 col2 col3 abc 346 6546 hth 549 974 ``` Expected Table1\...
You could use an outer join: ``` SELECT table1.col1, col2, col3, CASE WHEN table2.col1 IS NULL THEN 0 ELSE 1 END AS col4 INTO table1_new FROM table1 LEFT OUTER JOIN table2 ON table1.col1 = table2.col1 ```
You can do this in several ways. The following uses an `exists` clause in a `case` statement: ``` insert into table1_new(col1, col2, col3, col4) select col1, col2, col3, (case when exists (select 1 from table2 t2 where t2.col1 = t1.col1) then 1 else 0 end) from table1 t1...
copy a table into a new table and add a new column on SQL server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to convert a number to a decimal with two decimals places. ``` SELECT CONVERT(DECIMAL(10,2),12345) ``` The above would return 12345.00 but I'm trying to achieve 123.45
You need something like that: ``` SELECT CONVERT(DECIMAL(15,2),12345/100.0) ```
``` SELECT CONVERT(DECIMAL(10,2),CAST(12345 as float)/CAST(100 as float)) ```
SQL - Convert number to decimal
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table that looks like this: ``` memberno(int)|member_mouth (varchar)|Inspected_Date (varchar) ----------------------------------------------------------------------------- 12 |'1;2;3;4;5;6;7' |'12-01-01;12-02-02;12-03-03' [7 members] ``` So by looking at how this table has been structured (po...
The best way will be SQL itself. The way followed in the below code is something which worked for me well with 2-3 lakhs of data. I am not sure about the below code when it comes to 4 Million, but may help. ``` Declare @table table (memberno int, member_mouth varchar(100),Inspected_Date varchar(400)) Insert into @ta...
You can take a reference here. [Splitting delimited values in a SQL column into multiple rows](https://stackoverflow.com/questions/11018076/splitting-delimited-values-in-a-sql-column-into-multiple-rows)
comparable varchar "arrays" in seperate fields but on same row
[ "", "sql", "sql-server", "stored-procedures", "database-normalization", "denormalization", "" ]
I want to select distinct based on two columns so that if either of the two columns has the same value, then it will only post that row once. If it helps you understand, I am doing a sender/receiver thing and I only want to pull one row (whether it be sender or receiver). Here is how I want the MySQL to work: ``` SEL...
From the OP comment to the answer of Gordon Linoff it seems he is interested to retrieve the last message to every conversione between he and someone else, in that case the sender or the receiver will be him ``` SET @myname = 'Michael' --just stick here your name SELECT m.* FROM messages m INNER JOIN (SELECT...
You need to use the concat function. ``` SELECT distinct concat(sender,receiver) FROM messages WHERE receiver=receiver_name OR sender=sender_name; ``` See [here](http://www.mysql.com/about/contact/) for more info.
How do I use an AND statement with SELECT DISTINCT?
[ "", "mysql", "sql", "" ]
I want to pull data from table t ``` select (select round(avg(High),2) from t where High!=0)as High, (select round(avg(Med),2) from t where Med!=0) as Med, (select round(avg(Low),2) from t where Low!=0) as Low ``` and my table t is ``` select AAAA as High, BBBB as Med, CCCC as Low from TABLE1 where compa...
Try this query. It uses the CASE function. If the condition is not satisfied, then the value is assumed to be NULL, so that it would not be counted in the average. Since you do not have t to start with, you can create it using a CTE. ``` WITH t as ( select AAAA as High, BBBB as Med, CCCC as Low from TABL...
You can not because every of the subqueries is different -in the filter condition.
SQL using subquery table multiple times
[ "", "sql", "sql-server", "" ]
I have two databases : DataB1 with table1 and DataB2 with Table2 ``` Table1 has : field1, field2, filed3 Table2 has : fielda, fieldb, fieldc ``` Different fields name but same data type. Question : How can I do a stored procedure that opens databases and copies from table1 to table2?
You can do this with an insert. In most databases, it would look like: ``` insert into datab1.table1(field1, field2, field3) select fielda, fieldb, fieldc from datab2.table2; ``` Some databases might have a three part naming convention if the schema name is also involved. EDIT: With a three-part naming conv...
You do not specify your database server, but most have `INSERT ... SELECT`: ``` INSERT INTO DataB2.Table2 (fielda,fieldb,fieldc) SELECT field1,field2,field3 FROM DataB1.Table1 ``` A better alternative is probably a `VIEW`, if you just want to easily see the data from another database. ``` CREATE VIEW DataB2....
copy data from table in different database
[ "", "sql", "" ]
I have a DB that looks like ``` Year Name TR AST 1 Player 1 10 3 2 Player 1 23 "-" 3 Player 1 35 5 1 Player 2 32 1 2 Player 2 29 "-" 3 Player 2 50 2 1 Player 3 74 3 2 Player 3 23 1 3 Player 3 93 9 `...
The easiest way to get what you want is using `order by` and `limit`: ``` SELECT name, TR FROM database WHERE TR <> '-' ORDER BY TR DESC LIMIT 1; ``` You don't even need the `max()`.
I would use a subquery, probably something like this: ``` SELECT name, TR FROM database WHERE TR IN ( SELECT MAX(TR) FROM database WHERE TR != "-" ) ``` Note that this can give you multiple results when there are multiple players the same...
SQL MAX Statement returning wrong column
[ "", "sql", "sqlite", "" ]
Hi I have 2 table With same column name (Id,FName, LName,DOB,Type,Contact, Add). Now I want to get all data as a separate row which have same FName, LName and DOB from both table as order by Fname . I try to use intersect and Union but not work for me. ``` Select * from #t1 where FirstName in (select FirstName fro...
This would do it I think but I'm sure there's a more succinct way... ``` SELECT T1.* FROM T1 INNER JOIN T2 ON T2.FirstName = T1.FirstName AND T2.LastName = T1.LastName AND T2.DateOfBirth = T1.DateOfBirth UNION ALL SELECT T2.* FROM T2 INNER JOIN T1 ON T1.FirstName = T2.FirstName AND T1.LastName = ...
Try this ``` SELECT T1.Id, T1.FName, T1.LName, T1.DOB, T1.Type, T1.Contact, T1.Add FROM #t1 T1 INNER JOIN #t2 T2 ON T1.FName=T2.FName AND T1.LName=T2.LName AND T1.dob=T2.dob ```
Get Common data from two different table
[ "", "mysql", "sql", "sql-server", "sql-server-2008", "" ]
Take three layers of information: # Layer 1: Information This layer contains data with `UNIQUE` natural indexes and a surrogate key that is easily transferrable. ``` Table Surnames: +-----------------------------+--------------+ | ID (Auto Increment, PK) | Surname | +-----------------------------+---------...
Here's some trade-offs: ## Single Surrogate (artificially created): * All child tables foreign keys only need a single column to reference the primary key. * Very easy to update the natural keys in table without needing to update every child table with foreign keys * Smaller primary/foreign key indexes (ie. not a wid...
First of all, your second layer can be expressed at least four different ways, and they're all relevant to your question. Below I'm using pseudo-SQL, mainly with PostgreSQL syntax. Certain kinds of queries will require recursion and more than one additional index regardless of the structure, so I won't say any more abo...
Composite vs Surrogate keys for Referential Integrity in 6NF
[ "", "sql", "database", "6nf", "" ]
``` ID Date1 Date2 Date3 158 5/3/13 15:11 2/20/13 11:38 2/20/13 11:38 ``` I want to get the latest date from this three columns.
``` SELECT CASE WHEN Date1 IS NOT NULL AND Date1>=COALESCE(Date2,CAST('0001-01-01 00:00' AS DATETIME2)) AND Date1>=COALESCE(Date3,CAST('0001-01-01 00:00' AS DATETIME2)) THEN Date1 WHEN Date2 IS NOT NULL AND Date2>=COALESCE(Date1,CAST('0001-01-01 00:00' AS DATETIME2...
Try using `CASE`: ``` SELECT ID, CASE WHEN Date1>=Date2 AND Date1>=Date3 THEN Date1 WHEN Date2>=Date1 AND Date2>=Date3 THEN Date2 WHEN Date3>=Date1 AND Date3>=Date2 THEN Date3 END AS GreatestDate FROM TableName ```
Get the Latest date from the Three columns
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
I need to find all rows whose one column belongs to the same value and also satisfy a condition on SQL server 2008. Table1: ``` col1 col2 100 0 100 1 100 1 200 0 200 0 200 0 300 0 300 0 200 0 ``` I need to g...
Since you need the result for a *group of rows*, you could use grouping, e.g. like this: ``` SELECT col1 FROM table1 GROUP BY col1 HAVING SUM(col2) = 0 ; ``` That would give you all [distinct] `col1` values whose `col2` totals are 0. That assumes, of course, that `SUM` is applicable in this situation – in particular,...
Here is the query: ``` select col1,col2 from samp a where not exists (select 1 from samp where col1 = a.col1 and col2 <> a.col2) ``` Hope this will help you!
find all rows whose one column belongs to the same value and also another column satisfy a condition on SQL server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Please refer to the below table: ``` +----------------------------------------------------------+ | +-----------+--------------------+---------------------+ | | | Company | GL Account | Amount | | | +-----------+--------------------+---------------------+ | | | Company 1 | Cash at Bank ANZ | $...
Grouping in SSRS is certainly not intuitive. I managed to achieve what I wanted by right clicking in the "Amount" field and then selecting "Insert Row" --> "Outside Group (Below)". I then put the sum in the new cell and everything was calculated how I desired.
Managing groups went from really simple in SSRS 2005 to very difficult and arcane in SSRS 2008. Adding a footer to a group is the least intuitive UX ever. To create a header or footer after the group has been created, go to the bottom of the design window where the `Row Groups` panel is. This will show your groups. Dr...
In SSRS, how can I SUM by multiple groups?
[ "", "sql", "reporting-services", "sum", "" ]
I am learning SQL trough a GalaXQL tutorial. I can't figure out the following question (Exercise 12): > Generate a list of stars with star ids below 100 with columns > "starname", "startemp", "planetname", and "planettemp". The list > should have all stars, with the unknown data filled out with NULL. > These values a...
Lets build this up slowly. First, lets see about getting just the information about stars: ``` SELECT name AS starName, (class + 7) * intensity * 1000000 AS starTemp FROM Stars WHERE starId < 100 ``` (this should look might familiar!) We get a list of all stars whose `starId` is less than 100 (the `WHERE` clause)...
``` SELECT * FROM (SELECT [...]) as Alias1 LEFT OUTER JOIN (SELECT [...]) as Alias2 ON Alias1.id = Alias2.id ```
LEFT OUTER JOIN with subquery syntax
[ "", "sql", "subquery", "outer-join", "" ]
**I need to delete all the data from some tables**. `DELETE FROM TableTwo`, `DELETE FROM TableOne` etc works (it doesn't reseed but I can learn to live with that). **I would like to do this by truncating the tables** (because it's faster and I'm certain that when I'm done emptying these tables the data integrity will ...
Nathan, There are a couple of things I should point out... 1) The example code you posted is dropping and creating a DEFAULT CONSTRAINT (i.e. something that sets the default value for a column if you do not specify a value during an insert). A default constraint has no affect on the ability to truncate a table (as yo...
The only way is to drop the foreign key, truncate the table, and then re-create the foreign key. For an in-house solution, you would probably take this approach in order to account for the transaction log’s size and performance. In SQL Azure, however, you’re not concerned with the transaction logs.
How to clear data from tables with foreign key contraints in SQL Azure
[ "", "sql", "sql-server", "azure", "azure-sql-database", "" ]
``` ID | NAME | REFERENCE | STATUS ------------------------------- 1 | name1 | 123 | 0 2 | name1 | 123 | 1 3 | name2 | 111 | 0 4 | name3 | 222 | 0 5 | name5 | 555 | 1 ``` Let's say I have this table TABLE1. I need a select statement that will only find records wi...
Based on your suggested results, I am reading your question as "find only records with status = 0 where the same name/reference combination doesn't have a record with status = 1". One way you can do this is with a `not exists` clause: ``` select t.* from table t where status = 0 and not exists (select 1 ...
`MINUS` can be used to get the value with Status both 0 but not 1. ``` SELECT ID, Name, Reference, Status FROM Table1 WHERE (Name, Reference) IN (SELECT Name, Reference FROM Table1 WHERE Status = 0 MINUS ...
ORACLE - remove from result set if two or more "same" records found
[ "", "sql", "oracle", "" ]
I have given an example of data table like below. key\_value is unique and is used to get search results. What I do currently is query with key\_value and then parse the content. ``` +-----+-------------+----------------+ | id | key_value | content | +-----+-------------+----------------+ | 1 | 001 ...
First you can create function ``` CREATE FUNCTION [dbo].func_split_string ( @input as varchar(max) ) RETURNS @result TABLE ( content VARCHAR(20), [percent] VARCHAR(20) ) AS BEGIN DECLARE @name VARCHAR(255) DECLARE @content VARCHAR(20) DECLARE @percent VARCHAR(20) DECLARE @pos INT SET @input = @input ...
i am not sure if this works for sql server 2005. it does however for sql server 2008. what you do first is a recursive cte, chopping the content at the `/` character (`with...`). you can then split the result in numeric and alphanumeric parts. for your testdata i have used `@t` as you can observe. replace `@t` with the...
Parse result text during SQL query or on Server side
[ "", "sql", "sql-server", "sql-function", "" ]
I am having a problem with creating a view. Saying: Expression must be of same data type. This occurs at name. ``` CREATE VIEW V_DETAILS_BY_CATEGORY AS SELECT category_id, name FROM category UNION ALL SELECT DISTINCT(category_id), COUNT(film_id) FROM film_category GROUP BY c...
The count(film\_id) is a number, while name is (probably) some sort of string. You probably want to do a JOIN, not union (union takes rows that have the same structure from two different tables). Also, the distinct is not needed, since you're doing a group by. You probably want something like ``` SELECT category_id, ...
Unions must contain the same types of data. If you convert your count to whatever data type the "name" field is, it might work. ``` SELECT category_id, name FROM category UNION ALL SELECT category_id, TO_CHAR(COUNT(film_id)) FROM film_category GROUP BY category_id; ``` But, I agree with okaram, you might actually ...
UNION Error when creating a Veiw
[ "", "sql", "oracle", "" ]
I have the following query which takes about 10 minutes. I need this to be much quicker. Any ideas what can be done to tune this query? The `r_pos_transaction_head` table has a little under 500,000 records, and the `r_pos_transaction_detl` has a little under 900,000 records. I have created indexes where I thought appr...
The query is correctly written, as everyone suggest, try to add some indexes on joined fields. For me the bad part of the query is : ``` and ( s.colour_position = d.colour_no or s.colour_position is null and d.colour_no = 0 ) and ( s.size_position = d.size_no or s.size_position is null and d.size_no =...
You can use indexed views in order to perform beter joining. Perform better indexing so instead of index scan it can use index seek. Image percentage sum is not 100% where is others?
How can I improve the performance of this slow query
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Yesterday in a job interview session I was asked this question and I had no clue about it. Suppose I have a word "Manhattan " I want to display only the letters 'M','A','N','H','T' in SQL. How to do it? Any help is appreciated.
Well, here is my solution ([sqlfiddle](http://sqlfiddle.com/#!3/d41d8/34733)) - it aims to use a "Relational SQL" operations, which *may* have been what the interviewer was going for conceptually. Most of the work done is simply to turn the string into a set of (pos, letter) records as the relevant final applied [DQL]...
One way (if using SQL Server) is with a [recursive CTE (Commom Table Expression)](http://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx). ``` DECLARE @source nvarchar(100) = 'MANHATTAN' ; WITH cte AS ( SELECT SUBSTRING(@source, 1, 1) AS c1, 1 as Pos WHERE LEN(@source) > 0 UNION ALL SE...
How to split and display distinct letters from a word in SQL?
[ "", "sql", "" ]
I would like to search for records that occurred in a specific time of day and between a date/time range. **Example:** My table: ``` ID | EmpID | AuthorizationTime ------------------------------- 1 | 21455 | '23/01/2012 12:44' 2 | 22311 | '23/01/2012 18:15' 3 | 21455 | '23/01/2012 23:04' 4 | 10222 | '24/01/2012...
This should give you what you want: ``` select * from Times where AuthorizationTime >= @from and AuthorizationTime <= @to and ( (@fromtime > @totime and ((cast(AuthorizationTime as time) between '00:00:00' and @totime) or (cast(AuthorizationTime as time) between @fromtime and...
Add a check to see if `@fromtime > @totime`. If that is the case, compare the TIME-casted value of AuthorizationTime like this: ``` (cast(AuthorizationTime as time) between '00:00:00' and @totime) or (cast(AuthorizationTime as time) between @fromtime and '23:59:59.999') ```
T-SQL Overlapping time range parameter in stored procedure
[ "", "sql", "t-sql", "stored-procedures", "sql-server-2008-r2", "" ]
I am trying to write the single search statement to search the Product Views in multiple ways. My requirements are as follow: 1. If @SearchType is not provided, show all products 2. If @SearchType is **ProductID** (Integer), search by ProductID 3. If @SearchType is **Code** (VARCHAR(50)), search by Code Here is my TS...
You need to pass all parameters with corresponding type or null if not needed. ``` DECLARE @Value1 INT = 11 DECLARE @Value2 VARCHAR(50) = 'XYZ123' DECLARE @Value3 DATETIME = '20140505' SELECT * FROM dbo.vProductsCurrent WHERE ( ProductID = @Value1 OR @Value1 IS NULL) AND (Code = @Value2 OR @Value2 I...
Here you can use dynamic SQL queries, for dynamically constructing your query based on your condition. ``` Eg: DECLARE @SelectStatement NVARCHAR(2000); DECLARE @WhereClause NVARCHAR(2000); DECLARE @FullStatement NVARCHAR(4000); SET @SelectStatement = 'SELECT * FROM TableName' IF (cond1 is true) SET @WhereClaus...
TSQL Intelligence Search, Type Conversion Error, SQL 2008
[ "", "sql", "sql-server-2008", "t-sql", "search", "" ]
``` Table: users =============== id | name | =============== 1 | steve | 2 | peter | ================ Table: relation_favorites ======================= | idFavorite | idUser | ======================= | 1 | 1 | | 2 | 1 | | 4 | 1 | | 5 | 1 | | 1 ...
Using a JOIN and COUNT:- ``` SELECT u.id AS idUser, COUNT(rf.idFavorite) AS favourite_count FROM users u INNER JOIN relation_favorites rf ON rf.idUser = u.id WHERE rf.idFavorite IN (1, 4, 5) GROUP BY idUser HAVING favourite_count = 3 ``` You could also use multiple joins:- ``` SELECT u.id AS idUser FROM users u IN...
``` Select name from user where id in (Select distinct idUser from relation_favorites wher idFavorite in(1,4,5)) ``` Try this subquery may be it work for you. or you may be try this both query output same ``` Select distinct name from user x join relation_favorites y on x.Id=y.IdUser where y.idFavorite in(1,4,5) ...
query using two tables
[ "", "mysql", "sql", "" ]
I have a following situation (table schema: `ID, first name, last name, value`).: `table 1`: ``` ID | first name | last name | value -------------------------------------- 1 | John | Goodman | 5 2 | Peter | Snow | 6 3 | Mike | Walker | 7 4 | John | Goodman | 8 ``` ...
Something like this should work (if I ignore the `ID` column for now): ``` SELECT COALESCE(t1.FirstName,t2.FirstName) as FirstName, COALESCE(t1.LastName,t2.LastName) as LastName, COALESCE(t1.value,0) as t1value, COALESCE(t2.value,0) as t2value FROM (select FirstName,LastName,SUM(value) as value ...
``` With s as (Select firstname, lastname , value From table1 Union all Select firstname, lastname , value From table2) Select firstname, lastname , sum(value) From s Group by firstname , lastname ```
Full outer join
[ "", "sql", "sql-server", "database", "t-sql", "" ]
This works fine: ``` select case (1+2) -- (or_some_more_complicated_formula_yielding_a_numeric_result) when 200 then '200' when 100 then '100' else 'other' end hi_med_low from dual ; ``` But I need to do something more like this: ``` select case (1+2)...
`case` supports a syntax to evaluate boolean conditions. It's not as clean as you'd like as you need to re-write each expression, but it gets the job done: ``` select case when (1+2) > 200 then 'high' when (1+2) < 100 then 'low' else 'medium' end hi_med_low from dual ; ``` One possib...
Yes, use `CASE WHEN`: ``` CASE WHEN some_formula > 200 THEN 'High' WHEN some_formula < 100 THEN 'Low' ELSE 'Medium' END ```
How do you test inequality with Oracle Case Statement
[ "", "sql", "oracle", "case-statement", "" ]
I have a table that is event driven, ie when an event occurs it gets updated. When the event 'start' comes in it records a persons location, when 'end' comes in it does not. I want to count the number of Ends but report their corresponding locations which is recorded in their 'Start' event. Note: there are other type...
Try this (it shows only those persons who have finished their events: SUM of events = 0): **Updated solution:** ``` DECLARE @Events TABLE ( EventName VARCHAR(10) NOT NULL, EventPersonName VARCHAR(50) NOT NULL, EventPersonLocation VARCHAR(50) NULL, EventDate DATETIME2(0) NULL ); INSERT ...
This query gives you the results you want: ``` SELECT s.eventPersonName, s.eventPersonLocation, s.eventDate AS startDate, e.eventDate AS endDate FROM events e JOIN events s ON s.eventPersonName=e.eventPersonName AND s.eventName ='start' AND s.eventDate = ( SELECT MAX(p.eventDate) F...
Count occurrences of row couples
[ "", "sql", "sql-server-2008", "join", "group-by", "" ]
I'm making this database with superheroes for one of my school projects and I have a superheroes table (obviously) and an enemies table. So the enemies table have two foreign keys: ``` bad_superhero_id ``` and ``` good_superhero_id ``` The purpose of this table is to link the good superheroes with the bad superhero...
Your design is not intrinsically a bad design but it needs work. You are using a cross/intersection table which defines an n-to-n relationship. These are used all the time in production databases, like the relationship between Student and Course where a student can be taking several courses and a course will have many ...
Your teacher may be right: you very likely should define both superhero and enemy ids as separate foreign keys: ``` FOREIGN KEY good_sh_id REFERENCES superheroes(id), FOREIGN KEY bad_sh_id REFERENCES superheroes(id) ``` The syntax you specified, would instead specify superhero references as [a composite foreign key](...
Table with 2 foreign keys coming up from one primary
[ "", "mysql", "sql", "database", "foreign-keys", "" ]
**I have** `big_table` with about hundred of million rows, and `correlation_table` about few thousands of rows. `Corelation_table` correlates the rows of `big_table` to one another by `dep_id` field value. **I want** Select all ids of correlating rows form `big_table`. **Example:** ``` big_table id name ...
You can join the big table twice to the correlation table by giving it two different aliases, like this: ``` SELECT b1.id AS id1, b2.id AS id2 FROM big_table b1 INNER JOIN Correlation_table c ON c.dep_id1 = b.id INNER JOIN big_table b2 ON b2.id = c.dep_id2 ``` But if you want to select all these records fro...
try this: ``` select b1.id, b2.id from big_table b1 join correlation_table on depl_id = dep_id1 join big_table b2 on dep_id1 = b2.bep_id ``` It should join the tables together
MySQL: select correlating rows
[ "", "mysql", "sql", "" ]
I am designing a *JasperReports* report with *iReport* and my query is like this: ``` select * from TABLE_NAME where COLUMN_NAME = $P{PARAMETER_NAME} ``` my problem starts when I try to make it generic i.e. when the parameter is not passed I want the query to bring all the data from the table without filtering. I tri...
I found that I can do it by the following: ``` select * from TABLE_NAME where COLUMN_NAME = $P{PARAMETER_NAME} or $P{PARAMETER_NAME} is NULL ``` if there is better suggestions please provide.
try this : it is specific to oracle, but works for the situation mentioned by you `SELECT * FROM TABLE_NAME TM WHERE (CASE WHEN $P!{PARAMETER_NAME} IS NULL THEN 'TRUE' ELSE (DECODE(TM.COLUMN_NAME, '1001', 'TRUE', 'FALSE')) END) = 'TRUE';` Firstly, if the check of '$P!{PARAMETER\_NAME} IS NULL' fails and it moves to ELS...
How can I disable the where clause at the query when the parameter is not passed to the the report?
[ "", "sql", "jasper-reports", "" ]
I have an sql command similar to below one. ``` select * from table1 where table1.col1 in (select columnA from table2 where table2.keyColumn=3) or table1.col2 in (select columnA from table2 where table2.keyColumn=3) ``` Its performance is really bad so how can I change this command? (pls note that the two sql comma...
Try ``` select distinct t1.* from table1 t1 inner join table2 t2 ON t1.col1 =t2.columnA OR t1.col2 = t2.columnA ```
This is your query: ``` select * from table1 where table1.col1 in (select columnA from table2 and t2.keyColumn = 3) or table1.col2 in (select columnA from table2 and t2.keyColumn = 3); ``` Probably the best approach is to build an index on `table2(keyColumn, columnA)`. It is also possible that `in` has poor pe...
SQL command usage of in / or
[ "", "sql", "foxpro", "" ]
I have these tables on my SQL Server 1. view\_items - itemcode, itemname, description, length, width, height, weight 2. items - itemid, itemname, itemcode, description 3. items\_specs - itemspecsid, itemid, length, width, height, weight I tried to import data from my view (**view\_items**) to **items** table using **...
You would need 2 Data flow tasks. The first data flow component would populate the items table as you have done. The second data flow task would pull the use view\_items as the source and then you could use a lookup transformation.![Lookup ItemId](https://i.stack.imgur.com/jNV47.png) In the columns section you can map...
1)This is how I will start: Turn the identity\_insert off on the items table. Find the max from the items, and increment it by 1. This is your item id for the current row of information retrieved from the view\_items. You can use a look up table to store the max id. This item id can now be inserted into both items and ...
SSIS Populating to multiple table
[ "", "sql", "ssis", "" ]
I am having trouble displaying the average age alongside other data, i know it should display more then one field but it only displays one field. ``` SELECT EmpName, Age,AVG(Age) FROM Employee WHERE Age > ( SELECT AVG(Age) FROM Employee ) ```
``` SELECT EmpName, Age, (SELECT AVG(Age) FROM Employee) AverageAge FROM Employee WHERE Age > (SELECT AVG(Age) FROM Employee); ``` here is the right code , i think u can't use AVG(Age) next to SELECT cause it's not an exist column.
You cannot get the line *and* get the overall average. Try to join them: ``` SELECT e.EmpName , e.Age , a.AverageAge FROM Employee e CROSS JOIN ( SELECT AVG(Age) AverageAge FROM Employee ) a WHERE Age > AverageAge ```
SQL AVG cant get to work
[ "", "sql", "average", "" ]
When you need to change data in a MySQL table we used this command: `Replace into table_name` But for Sql Server I have no idea how to use a similar command. Does anyone could help me please. I liked to replace this: ``` ("replace into products" + " (date, hour, IdProduct, Ref1, Ref2, Ref3) values (?,?,?,?,?,?)"...
In SQL Server you can use UPDATE Command for changing data in a table: ``` UPDATE products SET date = new_value_1, hour = new_value_2, ... ... WHERE (where_clause) ```
Without REPLACE INTO or INSERT ON DUPLICATE KEY UPDATE, you need to find out which records should be updated or inserted. I had to do something like this in cases where there was no composite primary key, but it would work as a substitute for REPLACE INTO. * Create a temporary table that has the columns to be INSERTED...
How do a MySQL REPLACE INTO command in SQL Server?
[ "", "mysql", "sql", "" ]
So, I've been stuck on this problem for last couple of days and I still couldn't come up with solution. I want to group given month into weeks which is fairly easy but the (horrible)business requirement is to consider a single day also as a week if it falls on any day between Monday to Sunday. The end day of the week ...
``` WITH x (dt) AS ( SELECT DATE '2015-08-01' + LEVEL - 1 dt FROM DUAL CONNECT BY DATE '2015-08-01' + LEVEL - 1 < DATE '2015-09-01') SELECT dt, SUM ( CASE WHEN TO_CHAR (dt, 'd') = '2' --if the day is monday OR TO_CHAR (dt, 'fmdd') = '1' ...
``` --TRY THIS ``` --I DID IT FOR SYSDATE. ``` SELECT DT, CASE WHEN TO_CHAR(DT+1, 'W')='1' AND SUBSTR(DT,1,2)>'24' THEN '6' ELSE TO_CHAR(DT+1, 'W') END FROM (SELECT TO_DATE(SYSDATE)+ROWNUM DT FROM ALL_OBJECTS ); ``` --THE QUERY IN YOUR EXAMPLE. ``` SELECT DT,CASE...
Show number of weeks in a given month
[ "", "sql", "oracle", "oracle10g", "" ]
Is there a way to find all the tables that have an X column name within the Y database? So If X.Column Exists in Y.Database Print all.tables with x.column Thanks
Most, but not all, databases support the `information_schema` tables. If so, you can do: ``` select table_name from information_schema.columns t where column_name = YOURCOLUMNNAME; ``` If your database doesn't support the `information_schema` views, then any reasonable database has an alternative method for getting t...
For sql server try this... ``` SELECT t.name FROM sys.tables t INNER JOIN sys.columns c ON t.[object_id] = c.[object_id] WHERE c.name LIKE '%ColumnName%' ```
Find all tables that have X column name
[ "", "sql", "sql-server", "" ]
I have a table `user_access` with the following columns in MySQL database: ``` id int user int access_time datetime ``` I am trying to run a query that gives me the number of times a `user` accesses the system (`access_time`) in 15-minute intervals within a given a given set of timestamps. My current quer...
First of all, you have a subtle error in your `WHERE` clause. You need: ``` where access_time >= '2013-05-28 02:00:00' and access_time < '2013-05-28 10:00:00' ``` because your quarter-hour ranges run from a particular time until the moment *before* another particular time. You need `<`, not `<=`, for the end of yo...
What you need to create is a formula that will turn each access\_time into its nearest quarter-hour. Something like: ``` CONCAT(Hour(access_time),":",floor(Minute(access_time)/15))*15) ``` Then you can put that formula both in your select statement and your group by statement. You can modify this pseudocode statemen...
How to group datebase records into 15-minute time intervals
[ "", "mysql", "sql", "time-series", "aggregate-functions", "" ]
Just running a SQL and wrote a query with a sub query but it has returned a null value, when its not suppose too. Not to sure if anyone can help without the database but here is my query: \*This is the exercise question: 'Use an SQL statement with a sub-query to list the employee ID and full name of those employees wh...
Assuming I'm understanding your question, you want to return those employees that are marked as managers (denoted by the reportto column). If so, you could use `EXISTS`: ``` select employeeid, concat(firstname,' ', lastname) fullname from employees e where exists ( select 1 from employees e2 where e.employeeid =...
First, the subquery appears incorrect. You are trying to say "*Grab me ReportsTo and peoples names from the Employees table where the Employee ID is equal to any of the ReportsTo fields in the same table*" You would need to change the ReportsTo in the subquery to EmployeeID. IE ``` SELECT ReportsTo As 'Manager I...
SQL Returning a null value
[ "", "mysql", "sql", "sql-server", "" ]
With the following MySQL table containing debit or credit "actions" with associated amounts, how is it possible to select all CLIENT\_IDs with a non-zero "balance"? I have tried joining the table to itself in order to calculate all debit and credit totals, but something isn't working correctly. ``` CLIENT_ID ACTION...
``` DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (transaction_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,client_id INT NOT NULL ,action_type VARCHAR(12) NOT NULL ,action_amount INT NOT NULL ); INSERT INTO my_table(client_id,action_type,action_amount) VALUES (1 ,'debit', 1000), (1 ...
You need to use `case` statement ``` select client_id, debits, credits, debits-credits as balance from (SELECT client_id, SUM(case when ACTION_TYPE='debit' then action_amount else 0 end) AS debits, SUM(case when ACTION_TYPE='credit' then action_amount else 0 end) AS credits FROM categories GROUP BY client_id) a whe...
Using MySQL to calculate balances from debits and credits in a single table
[ "", "mysql", "sql", "" ]
I am trying to insert values into a temp table from within a cursor loop. It is hard to explain so I will just show what I have so far. ``` declare @sqlStatement varchar(max) declare @tmpTable table ( Table_Name varchar(max) ,Count int ) declare cur CURSOR FAST_FORWARD FOR Select 'Select ''' + TABL...
The format for the `exec` call must include parentheses: ``` exec(@tmp) ``` You will also need to change to a `#temp` table as a table variable will not be within the scope of the `exec`'d batch.
There are couple of issues, your while loop is missing 'FETCH NEXT FROM cur INTO @sqlStatement' which will lead it to indefinite loop. But this is not really the problem here. use exec ( ) with brackets it should solve the problem. ## Or if I was you I will try to achieve this using a set based statement like followin...
executing an insert into within a cursor loop
[ "", "sql", "ssms", "sql-insert", "database-cursor", "" ]
How want to use the sum of the time(n) operator so that i can calculate the overall total of the time but Sql server saying can't add the Time(n) column i have a casted column which contain difference of two dates, and being casted as Time(n) by me. Now i want to add those column to get how much time i had used in tot...
Convert the time to an integer value before you sum it (for example, seconds): ``` SELECT SUM( datediff(second, '00:00:00', [TimeCol]) ) FROM ... ``` Replace [TimeCol] with the name of the Time(n) column. This gives you the total time in seconds, which you can then easily convert to minutes, hours, et...
``` select Sum(DATEDIFF(Minute,date1,date2)) AS TIME from ABC_tbl ``` u have to calculate the date difference with DATEDIFF function then use SUM function to calculate your sum of time. you can change Minute to Second-Hour-month etc..
How to Sum (Time(n)) in Sql Server?
[ "", "sql", "sql-server", "" ]
I have data that looks something like: ``` Date UserID Visits 2012-01-01 2 5 ... ``` I would like to output a list of users who have > x visits on at least y dates (e.g., the users who have >5 visits for at least 3 dates from January 3 to January 10).
Try this: ``` SELECT SUB.UserId, COUNT(*) FROM ( SELECT VL.UserId FROM VisitLog VL WHERE VL.Visits > 5 AND VL.Date BETWEEN '2014-01-03' AND '2014-01-10') SUB GROUP BY SUB.UserId HAVING COUNT(*) >= 3 ``` The sub query returns all rows where the number of `Visits > 5` between your sampl...
Try this: ``` select * from users where id in ( select UserID from userVisits where date between '2014-01-03' and '2014-01-10' and visits >= 5 group by userid having count(*) >= 3) ```
SQL: List of users that meet a condition N times
[ "", "sql", "postgresql", "" ]
I have a set of SQL queries that each is an insert statement that gets its values from other tables: ``` insert into table1 values ( (select tableID from Table1 where Name = 'Name1'), (select tableID from Table2 where Name = 'Name2'), (select tableID from Table3 where Name = 'Name3') ) ``` If ...
What I would do is store the values in variables initially: ``` DECLARE @tableID1 INT = (SELECT tableID FROM Table1 WHERE Name = 'Name1') ``` Then you can do an ``` IF @tableID1 IS NOT NULL AND @tableID2 IS NOT NULL... INSERT... ``` or alternatively an `INSERT INTO table1 SELECT @tableID1 WHERE @tableID1 IS NOT...
The construct you are looking for is `insert . . . select`. This allows you to put a `where` clause on the query. Because your subqueries have to return one row, you can do a `cross join`, which will return at most one row: ``` insert into table1(id1, id2, id3) select t1.tableID, t2.tableId, t3.tableId from (s...
How to modify SQL INSERT query to fail if nested SELECT returns NULL
[ "", "sql", "sql-server", "" ]
After looking at [how to count the occurrences of distinct values](https://stackoverflow.com/questions/1346345/mysql-count-occurrences-of-distinct-values) in a field, I am wondering how to count the occurrences of each distinct value if the distinct values are known (or enumerated). For example, if I have a simple tab...
For mysql you can do so,by using expression in `sum(expr)` will result as boolean and you can count the occurrences for your colors individually ``` SELECT SUM(Colour = 'Red') AS RedCount, SUM(Colour = 'Amber') AS AmberCount, SUM(Colour = 'Green') AS GreenCount FROM t ``` ## [Demo](http://sqlfiddle.com/#!2/ab029/1...
Try this query: ``` SELECT (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Red') AS red_lights, (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Green') AS green_lights, (SELECT COUNT(*) AS ColourCount FROM tableA GROUP BY colour HAVING colour = 'Amber...
MySQL: Count occurrences of known (or enumerated) distinct values
[ "", "mysql", "sql", "" ]
I have a table `LOGPROCESS` that stores start/end of each process and I would like to do a select and return only one row using something like 'as DateStart' 'as DateEnd'. This is how the logs are saved for each process ( ThreadName could be different ): ``` |ThreadName |LEVEL |Who | T...
Your challenge is extracting `CampID` from your query string to identify your rows. You can do this using CHARINDEX and SUBSTRING as follows (I have separated out the logic into APPLY to hopefully make it more clear what is being done): ``` SELECT CampID = SUBSTRING(QUERY_STRING, StartIndex, EndIndex - StartIndex), ...
Well, it's not pretty: ``` SELECT b.ThreadName ,a.[date] as StartDate ,b.[date] as EndDate FROM logprocess a LEFT JOIN logprocess b ON SUBSTRING(a.query_string ,PATINDEX('%campId=%', a.query_string)+7 ,LEN(a.query_string)-(PATINDEX('%campId=%', a.query_string)+6)) = SUBSTR...
SQL Server - Retrieve two rows in a unique row using alias
[ "", "sql", "sql-server", "" ]
Im creating db project and one thing is no so clear for me. Have a look at this: ![part of database model](https://i.stack.imgur.com/nbnuc.png) Now im not sure what's the best way to make physical model. TOOL and RESOURCE doesn't need any other fields than ITEM. Only Recipe needs new column(for). But I have to somehow...
This is a classic "It depends" answer. The answer really depends on the potential relationships and whether an item can belong to more than one type. If there will be relations that all items can be in, then a single items table would be preferable since you can have a single foreign key column in your relation table....
Based on just the requirements that you've presented, I would suggest physically implementing only a single table (item) with a **partitioning attribute**, e.g. `item_type`. You can use check constraints to ensure that the extra columns that apply only to recipes are null for other item types and not-null for recipes. ...
Database subclassing design
[ "", "sql", "database", "database-design", "" ]
**Mock up table:** ![enter image description here](https://i.stack.imgur.com/sU2iM.jpg) I need to eliminate duplicate records from the first table. In case we have duplicate address\_num such as 100, we will go with the row of AddressType "Home". Please note that address\_num do not come in duplicates of 3 or more; ...
You can do this with `row_number()` and an intelligent use of `order by`: ``` select t.* from (select t.*, row_number() over (partition by address_num order by (case when AddressType = 'Home' then 1 else 0 end) desc ) as seqnum from tabl...
Something like: ``` SELECT id, address_num, ... FROM ( SELECT id, address_num, ... , row_number() over (partition by address_num order by addresstype) as rn FROM T ) AS X WHERE rn = 1 ```
Pick a Single Row Out of Each Set of Duplicates
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
Postgresql Database ``` Table User ----------- ID | Name 1 | John 2 | Bob 3 | Sarah Table Photo ------------- ID | Caption 1 | Vacation 2 | Birthday 3 | Christmas Table Comment -------------- ID | User ID | Photo ID| Text 1 | 1 | 1 | Mexico Looks Great 2 | 2 | 1 | Sure Does 3 ...
The clearest and most readable way, is the `Photo`s containing comments by: User1 `Intersect` User2 `Except` Any other user This [SQL Fiddle](http://sqlfiddle.com/#!15/dc786/3) and query will return that: ``` SELECT * FROM Photo WHERE ID IN ( SELECT "Photo ID" FROM Comment WHERE "User ID" = 1 INTERSECT S...
lets do three joins, one for john, one for sara, one for everyone else. Then we'll limit what we get back with the where clause. ``` select p.* from photo p left join comment john on john.photo_id=p.photo_id and john.user_id=1 left join comment sara on sara.photo_id=p.photo_id and sara.user_id=3 left join comment ever...
Postgres Many to many mapping sql query
[ "", "sql", "postgresql", "relational-division", "" ]
I need to select details from a table according to the language present. That is, I have a primary language culture and and a Secondary Culture. I need to select rows that have matching rows for primary if any else I need to select matching rows for secondary culture. I have more than 5 different tables to join all wil...
Other two ways to get that is using a `UNION` The first query removes the values of the secondary language that are duplicates of values of the primary languages checking with an `EXIST` ``` DECLARE @primary nvarchar(20) = 'en-AR' DECLARE @secondary nvarchar(20) = 'en-US' SELECT Name, Culture FROM LangTable1 WHERE...
This might give you what you want: ``` ;with cte(Name, Culture, CultureRank) as ( select t.Name, t.Culture, case when t.Culture = @primary then 1 when t.culture = @secondary then 2 else 3 end CultureRank from LangTable1 t ) select c.Name, c.Culture from cte c where c.CultureRank < 3 and c.CultureRank = (select MIN(C...
select columns with conditions with priority
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Lets say I have three tables with these columns, ``` Players - id, name Events - id, name Games - first_player_id, second_player_id, event_id. ``` And I need the `players` details who are playing in a `game` which is happening in an `event`. And I could write query like, ``` SELECT players.id, even...
If you do not want sub queries in your select statement then you must provide a join for each subset. Since your database is set oriented the two INNER JOINS would prove more efficient. ``` SELECT players.id, events.id as event_id, player_one_name=player_one.name, player_tow_name=player_two.name FROM events ...
You must do a join for each foreign key ``` SELECT players_a.id, events.id as event_id, players_a.name as player_one_name, players_b.name as player_two_name, games.id as game_id FROM events INNER JOIN games on events.id = games.event_id INNER JOIN players players_a on games.first_player_id = players.i...
SQL Query using multiple JOINS without sub query
[ "", "sql", "postgresql", "" ]
I have a sql query which returns a list of students which are enrolled in a conference, and their preferences for each session. When pulling the data from my database, each user session selection is showing in its own row as shown below: ``` **userid question answer** 1 S1 choose: a1, b1, c1 ...
In response to your comment, assuming you know the number of potential questions, one option is to use `max` with `case`: ``` select userid, max(case when questionid = 1 then question end) question1, max(case when questionid = 1 then answer end) answer1, max(case when questionid = 2 then question ...
Use dynamic SQL. Select a distinct list of sessions into a temp table that you've created with an identity column. ``` DECLARE @SQL varchar(1000), @Count int, @Counter int CREATE TABLE #report (userid int) CREATE TABLE #questions (MyIdx int IDENTITY(1,1), question varchar(50)) INSERT INTO #report (UserID) SELECT DIST...
Return 1 row per unique id instead of multiple rows
[ "", "sql", "sql-server", "" ]
I am writing a query like this... ``` select consumer_name,count(select * from consumer where product='TTT') from consumer; ``` I want filtered count... What will be perfect query for this?
Maybe something like this: ``` select consumer_name, ( SELECT COUNT(*) FROM consumer AS tbl WHERE tbl.product='TTT' ) from consumer; ```
Try ``` select consumer_name, COUNT(your_column_name which you want to count) from consumer WHERE tbl.product='TTT' group by colusumer_id; ```
How to select count of particular rows in Oracle?
[ "", "sql", "database", "oracle", "" ]
I have a **view** taken column from table question and table answer. table question have id and question text while table answer have id, question\_id(fk from table question) and answer text. ``` SELECT QuestionID, QuestionTxt, [1], [2], [3], [4] FROM (SELECT ROW_NUMBER() OVER (PART...
It's hard to tell from your question where you are hoping to get the AnswerID. If you want it in a single column, you will need to use @StayPuft's answer. If you want it as part of the text column, you can use the SQL below: ``` SELECT questionText, [1], [2], [3] FROM ( SELECT ROW_NUMBER() OVER (PARTITION...
First let me say that SQL Fiddle is awesome! And if you wanted to display the answer ID - this is what I did: ``` SELECT questionText, [1], [2], [3], answerID FROM ( SELECT ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid()) AnswerInQuestionID, answerTxt, QuestionText, answerID FROM ...
select id with text from table into view
[ "", "sql", "sql-server", "" ]
I habe a problem with the new lead olap function in sql server 2012. ``` CREATE TABLE Atext (id int, bez varchar(10), von date); GO INSERT INTO Atext VALUES (1, 't1', '2001-01-01'), (1, 't2', '2012-01-01'), (2, 'a1', '2020-01-01'), (2,'a1' , '2030-01-01'), (2, 'b', '2040-05-01'), (2, 'a3', '2989-05-01'); GO SELEC...
You can use DATEADD() in this query. Also the default value of LEAD for data type can't be `0` so I've changed it to NULL or you can use any DATE constant. ``` SELECT id, bez, von, DATEADD(DAY,-1,lead(von,1,NULL) over (partition by id ORDER BY von)) as bis FRO...
Same as all the other answers but with `DATEADD` as an argument of lead: ``` SELECT id, bez, von, lead(DATEADD(DAY,-1, von),1, null) over (partition by id order by von) from Atext order by id, Von ``` [SQLFiddle](http://sqlfiddle.com/#!6/ed02a/20) example
sql server lead - problems with date
[ "", "sql", "sql-server", "date", "lead", "" ]
i have a table 'DEMO' like below, I need some specified result in my select query ``` PID Is_Viewed 1 False 1 False 1 False 1 False 2 True 2 False ``` Now i need to select only those record which if having even a single value 'True' then result will ...
Maybe something like this: ``` SELECT PId, MAX(CASE WHEN Is_Viewed='True' THEN 1 ELSE 0 END) AS Is_Viewed FROM DEMO GROUP BY PId ``` **Edit** Considering the data that you have supplied. ``` DECLARE @tbl TABLE(PID INT,Is_Viewed VARCHAR(10)) INSERT INTO @tbl VALUES (1,'False'), (1,'False'),...
I guess that `Is_Viewed` is defined as a `bit` type since SQL server doesn't have a BOOLEAN type. Then try this: ``` SELECT PID, MAX(CAST(Is_Viewed as INT)) as Is_Viewed FROM T GROUP BY PID ``` `SQLFiddle demo`
How to get only specified values record from multiple values of one Record in sql server
[ "", "sql", "sql-server", "database", "stored-procedures", "" ]
Good Afternoon! I'm having trouble list the last two records each idmicro Ex: ``` idhist idmicro idother room unit Dtmov 100 1102 0 8 coa 2009-10-23 10:40:00.000 101 1102 0 1 coa 2009-10-28 10:40:00.000 102 1102 0 2 ...
You can do the same thing with an imbricated `SELECT` statement. ``` SELECT * FROM ( SELECT row_number() OVER ( PARTITION BY idmicro ORDER BY idhist ) AS ind ,* FROM data ) AS initialResultSet WHERE initialResultSet.ind < 3 ``` Here is a sample [SQLFiddle](http://sqlfiddle....
``` WITH etc AS ( SELECT * ,row_number() OVER ( PARTITION BY idmicro ORDER BY idhist ) AS r ,count() OVER ( PARTITION BY idmicro ORDER BY idhist ) cfrom TABLE ) SELECT * FROM etc WHERE r > c - 2 ```
List the last two records for each id
[ "", "sql", "sql-server", "" ]
I have three temp tables in SQL: Temp1 ``` UserID Score_1 123 100 456 200 ``` Temp2 ``` UserID Score_2 456 300 ``` Temp3 ``` UserID Score_3 123 400 789 500 ``` I want to combine all these three tables into one as ``` UserID Score_1 Score_2 Score_3 123 ...
What you are looking for is a FULL OUTER JOIN: ``` SELECT COALESCE(t1.UserID, t2.UserID, t3.UserID) as UserID, t1.Score_1, t2.Score_2, t3.Score_3 FROM Temp1 t1 FULL OUTER JOIN Temp2 t2 ON t1.UserID = t2.UserID FULL OUTER JOIN Temp3 t3 ON COALESCE(t1.UserID, t2.UserID) = t3.UserID ``` SQL fiddle [here](http://www.sqlf...
Try this: ``` SELECT COALESCE(T1.UserID,T2.UserID,T3.UserID) as UserID,T1.Score_1,T2.Score_2,T3.Score_3 FROM Temp1 T1 FULL OUTER JOIN Temp2 T2 ON T1.UserID=T2.UserID FULL OUTER JOIN Temp3 T3 ON T1.UserID=T3.UserID ``` Result: ``` USERID SCORE_1 SCORE_2 SCORE_3 123 100 (null) 400 456 2...
Combine columns of three tables
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
Just a quick question which I need to ask, my MYSQL table is using MYISAM storage engine and looking at some previous questions they say queries under this engine are automatically committed (No transactions allowed only auto-commit). Now, does that mean, if I do the following query: ``` UPDATE `ExampleTable` SET `Ex...
> Basically what i'm asking: Is the code above one query which MYISAM will autocommit, or is that SQL treated as two queries? In MyISAM, the code you show is treated as two queries. Any concurrent client could see the data changed in progress. If you want *transaction isolation* so that no concurrent thread can see th...
Yes, you are right if you do this: ``` UPDATE `ExampleTable` SET `ExampleField` += '50' WHERE ...; UPDATE `ExampleTable2` SET `ExampleField2` -= '50' WHERE ...; ``` it is something like: ``` START TRANSACTION; UPDATE `ExampleTable` SET `ExampleField` += '50' WHERE ...; COMMIT; START TRANSACTION; UPDATE `ExampleTa...
MySQL Transaction/Commit Query
[ "", "mysql", "sql", "myisam", "" ]
I've been struggling with altering my query for days now and I just can't get the result I want. I kind of hoping someone can help me out how to change my query. Having the following query now: ``` SELECT t.tId, t.tName, a.aId, a.aName, u.uId, u.uName FROM tableT t LEFT JOIN t_a ta US...
If I'm not mistaken the query I need is as follows: ``` SELECT t.tId, t.tName, a.aId, a.aName, u.uId, u.uName FROM tableT t LEFT JOIN t_a ta USING (tId) LEFT JOIN t_u ti USING (tId) LEFT JOIN tableA a USING (aId) LEFT JOIN tableU u USING (uId) UNION SELECT t.tId, t.t...
I think what you want is to start with all the `tid`s from `tableT` and `t_a`: ``` FROM ((SELECT t.tID from tableT) UNION (SELECT ta.tID from tableA t_a) ) ids left outer join tableT t USING (tId) LEFT JOIN t_i ti USING (tId) LEFT JOIN tableA a ON a.aId = ta.aId LEFT JOIN ...
mysql combine multiple joins
[ "", "mysql", "sql", "join", "" ]
I have data in a **table A** as shown below. I want to group memberID as one set and sort the Date\_Time in each set as shown in snapshot below ``` Date_Time PersonID Status 4/2/14 10:15 AM ghi Closed 4/1/14 9:15 AM ghi Cancelled 4/1/14 11:00 AM abc Cancelled 4/2/14 8:12 AM ...
If I'm understanding your question correctly, you need to `join` the table back to itself using the `min` aggregate to establish a sort order: ``` select t.* from yourtable t join ( select personid, min(date_time) min_date_time from yourtable group by personid ) t2 on t.personid = t2.personid ...
Here's [another way](http://sqlfiddle.com/#!3/a0717/1): ``` SELECT Date_Time, PersonID, Status FROM dbo.atable ORDER BY MIN(Date_Time) OVER (PARTITION BY PersonID), PersonID, Date_Time ; ``` The approach, though, is same as in [sgeddes's answer](https://stackoverflow.com/a/23925821/297408), it just has ...
How to write a sql query to Sort or Group the dataset
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2005", "sql-server-2012", "" ]
Specifically, can I do this? ``` CREATE PROC AutoDestructiveStoredProcedure AS DROP PROC AutoDestructiveStoredProcedure PRINT 'Still alive.' GO ``` Is it a bad practice? What is the expected behavior? Does it change based on implementation? What would be the difference between executing this in SQL Server, MySQL and...
Yes, this will work -- at least in SQL Server 2008 R2. It continues executing until the end of the procedure and after that the procedure is gone. Is it bad practice? I think so. In my mind, the main reason is that it mixes DDL with DML, imposing unexpected side effects on what is normally a well-understood operation ...
Yes you can do this not sure why you would want to ``` CREATE PROC AutoDestructiveStoredProcedure AS PRINT 'Being killed' DROP PROC AutoDestructiveStoredProcedure PRINT 'Still alive.' exec createAutoDestruct print 'Alive Again' GO create proc createAutoDestruct as Exec sp_executesql N'CREATE PROC AutoDestructiveStor...
Can a SQL Stored Procedure drop itself and continue execution?
[ "", "sql", "" ]
I have a query where I am looking into three different tables and for the purposes of this post I only need to see three columns; RecordID, FieldType and Tranid. The Record ID can have multiple Field types and each field type will have a distinct tranid. ![enter image description here](https://i.stack.imgur.com/m61z0....
Your query does not work because it limits the rows selected from `Detail` to these with `fieldtype = 'CO'`, and inner joins to it. It looks like you are looking for a `WHERE EXISTS` query: ``` SELECT h.RecordID, d.FieldType, h.TranID FROM Branch b INNER JOIN Header h ON b.BranchID = h.BranchID INNER...
You can try including the below in the WHERE criteria: ``` SELECT RecordID, FieldType, TranID FROM Branch br, Header hr, Region rgn WHERE br.FieldType = 'CO' and hr.FieldType = 'CO' and rgn.FieldType = 'CO' ```
Grab all rows for a Records where a single instance occurs in a different row for the record
[ "", "sql", "sql-server-2008", "t-sql", "" ]
Getting error Invalid column name '@ColumnNames'. in the last line (insert clause), any idea why ? ``` Declare @ColumnNames varchar(2000) Declare @OrderId int set @OrderId = 110077 select @ColumnNames = COALESCE(@ColumnNames + ', ', '') + COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TAB...
`@ColumnNames` is a string of text, not a list of columns. As a result, when you try to use it as a list of column names in the insert query, it fails. You can use dynamic SQL to do what you desire, like so: ``` declare @insertquery nvarchar(1000) set @insertquery = N'insert into dbo.orderhistory(' + @ColumnNames + '...
You should use dynamic sql. And dont forget to perform data casting constructing query string! ``` Declare @ColumnNames varchar(2000) Declare @OrderId int set @OrderId = 110077 select @ColumnNames = COALESCE(@ColumnNames + ', ', '') + COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_N...
Selecting column name dynamically in an insert query
[ "", "sql", "sql-server", "t-sql", "dynamic-sql", "" ]
Why I got this message if the query seems right: **"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated. "** But when I try the query splitted it works fine, I mean, what could happen? ...
``` UPDATE llantas_dictamen_scrap SET clave_operador = RIGHT(clave_operador, CHARINDEX('-',REVERSE(clave_operador), 1) -1) WHERE CHARINDEX('-',clave_operador, 1) > 0 ``` This one adjusts the position of the call to RIGHT, excluding the '-' we found. There's no need to make a call to REPLACE, because once we know the p...
You are setting a single column value equal to more than one column value. If you want to update using the same query your using you have to specify which column you want to use. If you specify to select top 1... with order by that should give you a usable single subquery result for your update statement.
Subquery returned more than one value... in sql query, What that means?, and what is wrong?
[ "", "sql", "sql-server", "" ]
My db table is called transactions and is like this: ``` Name | Date (DateTime) | Type | Stock | Volume | Price | Total Tom 2014-05-24 12:00:00 Sell Barclays 100 2.2 220.0 Bob 2014-04-13 15:00:00 Buy Coca-Cola 10 12.0 120.0 varchar DateTime varchar va...
Your first query can be formulated as: `delete users from transactions where it does not exist a transaction for that user before ?. This is easy to transform to sql: ``` delete from transactions t1 where not exists ( select 1 from transactions t2 where t1.name = t2.name and t2.date < ? ) ``` mysql stil...
Alvin here is a simplified scenario from your fiddle with dates: ``` CREATE TABLE transactions ( id int(11) NOT NULL AUTO_INCREMENT , name varchar(30) NOT NULL , value datetime NOT NULL , PRIMARY KEY (id) ) ENGINE=InnoDB; INSERT INTO transactions (name, value) VALUES ('alex', '2011-01-01 12:00:00...
SQL query based on subquery. Retrieve transactions with data > threshold
[ "", "mysql", "sql", "datetime", "subquery", "conditional-statements", "" ]
I have postgres function in which i am appending values in query such that i have, ``` DECLARE clause text = ''; ``` after appending i have some thing like, ``` clause = "and name='john' and age='24' and location ='New York';" ``` I append above in where clause of the query i already have. While executing query...
You do not need regex: ``` clause = substr(clause, 5, 10000); clause = substr(clause, 5, length(clause)- 4); -- version for formalists ```
Instead of fixing `clause` after the fact, you could avoid the problem by using [`concat_ws`](http://www.postgresql.org/docs/9.1/static/functions-string.html) (concatenate with separator): ``` clause = concat_ws(' and ', "name='john'", "age='24'", "location ='New York'") ``` will make `clause` equal to ``` "name='jo...
How to use regex replace in Postgres function?
[ "", "sql", "regex", "postgresql", "postgresql-9.1", "plpgsql", "" ]