Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have these three tables in SQL Server 2012. ``` CREATE TABLE [dbo].[ClientInfo] ( [ClientID] [int] IDENTITY(1,1) NOT NULL, [ClientName] [varchar](50) NULL, [ClientAddress] [varchar](50) NULL, [City] [varchar](50) NULL, [State] [varchar](50) NULL, [DOB] [date] NULL, [Country] [varchar](50)...
Try this one using `ROW_NUMBER`: ``` select a.ClientID, a.ClientName, a.TypeName from ( select distinct ClientInfo.ClientID, ClientInfo.ClientName, TypeInfo.TypeName, ROW_NUMBER() over(partition by ClientInfo.ClientID order by case when TypeName is null then 1 else 0 end) as rn from ClientInfo left join ClientInsur...
Just remove your `where` clause and change join condition slightly ``` select distinct ClientInfo.ClientID, ClientInfo.ClientName, TypeInfo.TypeName from ClientInfo left join ClientInsuranceInfo on ClientInfo.ClientID = ClientInsuranceInfo.ClientID and ClientInsuranceInfo.InsTypeID = 2 left jo...
SQL Server query help needed for joining
[ "", "sql", "sql-server", "database", "t-sql", "" ]
From the following table, I would like to return the set of all books that have topic 3 but do not have topic 4. ``` id book topic 10 1000 3 11 1000 4 12 1001 2 13 1001 3 14 1002 4 15 1003 3 ``` The correct table should be: ``` book 1001 1003 ``` I made a SQL Fiddle with this for tes...
Since you're using SQL Server (at least in the fiddle) you could use the `except`set operator: ``` SELECT DISTINCT book FROM TOPICS WHERE topic = 3 EXCEPT SELECT DISTINCT book FROM TOPICS WHERE topic = 4 ``` This would return 1001 and 1003.
You're almost there. The `not exists` condition is definitely the right idea, you just need to apply another one of these for checking the existence of topic 3: ``` SELECT DISTINCT a.book FROM topics a WHERE EXISTS (SELECT * FROM topics b WHERE a.book = b.book AND b.topic = 3) AND ...
Select values in SQL that have a colum value in one row and not a specific other column value in another
[ "", "mysql", "sql", "sql-server", "select", "" ]
Can someone suggest how to add a condition in `WHERE` clause of my stored procedure? ``` CREATE Procedure getAllEmployeesByDeptAndFlag @Dept int, @sal int, @Flag int AS if @flag = 1 select * from employee where Department = @dept and @sal < 10000 else select * ...
You could use the `or` logical operator to unify both branches of the `if` statement: ``` select * from employee where Department = @dept AND (@flag != 1 OR @sal < 10000) ```
You could define that if you pass in `NULL` for `@sal`, then the salary is not being checked. No need for an extra `@flag` parameter... ``` CREATE Procedure getAllEmployeesByDeptAndFlag @Dept int, @sal int AS SELECT (list of columns) FROM dbo.employee WHERE Department = ...
Condition based where clause SQL Server stored procedure
[ "", "sql", "sql-server", "select", "if-statement", "stored-procedures", "" ]
I have a table `itemsInShippment` with the following data: ``` itemid shippmentid qty 10 1 100 20 1 200 10 2 300 10 3 1000 ``` and table `shippments` ``` shippmentid date shippmentstatus supplierid 1 2015-01-12 OK 5000...
You want to exclude canceled items only from sums. So, do not filter them with where, just filter them on sums: ``` SUM(case when b.shippmentstatus <> 'cancelled' then a.qty end) OVER (PARTITION BY ... ``` Sum does not take in consideration null, that's why the above works. (When status is canceled the case expressio...
A more efficient variant of Florian's answer exists for PostgreSQL 9.4, the `filter` clause for an aggregate. ``` SUM (a.qty) FILTER (WHERE b.shippmentstatus <> 'cancelled') OVER (PARTITION BY ... ``` See [`FILTER`](http://www.postgresql.org/docs/current/static/sql-expressions.html) in the docs for aggregates. It's b...
How to exclude rows from sum but still show them?
[ "", "sql", "postgresql", "" ]
I'm trying to make this SQL statement simpler, and am looking for a way to change ONLY the `WHERE` clause if no results so I don't have to repeat the other part. I've already tried with the `OR` and it's not what I need. It searches first for a record that exactly matches the `ID` field. If there is no result, it wil...
`OR` will work, you just have to get all the conditions right: ``` SELECT StockDetalles.ID, Negocios.NombreNegocio AS [Nombre Local], StockDetalles.Nombre, Stock.[Precio de Venta], Stock.Cantidad, Stock.[Fecha Actualizacion de Precio], Stock.[Fecha Actualizacion de Cantidad], StockDeta...
One more way with window functions: ``` ;with cte1 as(select StockDetalles.ID, Negocios.NombreNegocio AS [Nombre Local], StockDetalles.Nombre, Stock.[Precio de Venta], Stock.Cantidad, Stock.[Fecha Actualizacion...
Use a different WHERE in no results
[ "", "sql", "sql-server", "" ]
I want to get `NULL` when the number in my table is 0. How can I achieve this using SQL? I tried ``` SELECT ID, Firstname, Lastname, CASE Number WHEN 0 THEN NULL END FROM tPerson ``` But this results in an error: > At least one of the result expressions in a CASE specifica...
As others have mentioned you forgot to tell your CASE statement to return the number in case the number is not null. However in SQL Server you can use NULLIF, which I consider more readable: ``` select id, firstname, lastname, nullif(number, 0) as number from tperson; ``` If you want to stick to standard...
``` SELECT ID, Firstname, Lastname, CASE WHEN Number!=0 THEN Number END FROM tPerson ```
SQL case 0 then NULL
[ "", "sql", "case", "" ]
Hi im looking to get how many users that use one app use that app ``` ╔════════════════════════════════════════════════════════════════════════╗ ║ username clientname date time publishedapp ║ ╠════════════════════════════════════════════════════════════════════════╣ ║ akirk hplaptop1 ...
Here is one method that doesn't require a join: ``` select publishedapp, count(*) as NumberOfUsers from (select username, min(publishedapp) as publishedapp from table t group by username having count(*) = 1 ) u group by publishedapp order by count(*) desc; ``` If a user only has one app, then t...
Try this ``` SELECT publishedapp, COUNT(*) as cnt FROM ( select username from tbl_name group by username having count(*)=1 ) as t1 inner join tbl_name as t2 on t1.username=t2.username GROUP BY publishedapp ORDER BY cnt DESC ```
mysql count having distinct
[ "", "mysql", "sql", "" ]
I want to drop all the entries from the field `customers_fax` and then move all numbers beginning `07` from the `customers_telephone` field to the `customers_fax` field. The table structure is below ``` CREATE TABLE IF NOT EXISTS `zen_customers` ( `customers_id` int(11) NOT NULL, `customers_gender` char(1) NOT NULL D...
Try something like this: ``` UPDATE zen_customers SET customers_fax = customers_telephone WHERE customers_telephone like '07%' ```
This should work: ``` UPDATE zen_customers SET customers_fax = customers_telephone WHERE customers_telephone LIKE '07%'; ``` But if you want to test on one customer to be sure it does what you expect, you can always run this update query on a specific user that have a '07' telephone number: ``` UPDATE zen_customer...
Update a column using values from another column that match a specific criteria
[ "", "mysql", "sql", "sql-update", "" ]
This is my table: ``` Column1 Column2 1 A 2 B 3 B 2 C 4 B ``` I have following SQL query to get all rows with column1 matching an input list with numbers, for example "1, 2, 3": ``` SELECT * FROM table WHERE column1 IN (1, 2, 3); ``` This query is generated by a program appending every...
This is what I would do. It generally would perform better than IN with OR's and is much more readable in my opinion. ``` SELECT * FROM TABLE INNER JOIN ( SELECT 1 AS col1, 'a' AS col2 UNION SELECT 2, 'b' UNION SELECT 4, 'b' ) AS tbl ON tbl.col1=TABLE.col1 AND tbl.col2=TABLE.col2 ```
Create a table or a table variable with the matching index. Load the user's filters, and join to the main table.
SQL IN-Operator: consider multiple columns
[ "", "sql", "sqlanywhere", "" ]
This is my first post, and I attempted to do a thorough search for this issue, so please accept my apologies if it has been posted elsewhere many times, but I'm wondering if anyone has encountered the following issue when attempting to remove NULLs from their result set: ``` case Occurrence when NULL then '0' ...
You should be using the ISNULL() or COALESCE() system function for handling nulls something like ``` SELECT ISNULL(Occurrence , 0) AS Occurrence ,ISNULL(Aggregate , 0) AS Aggregate FROM Table ``` OR ``` SELECT COALESCE(Occurrence , 0) AS Occurrence ,COALESCE(Aggregate , 0) AS Aggregate FROM Table ``` ...
You use [simple case](https://msdn.microsoft.com/en-us/library/ms181765.aspx): > The simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned. > > Allows **only an equ...
CASE logic when removing NULLs
[ "", "sql", "sql-server", "sql-server-2012", "" ]
Video table stores id and video data. Tag table stores id and tag\_name. video\_tag table connects video\_ids and tag\_ids to represent which video belongs to which tag. For example in query below, i can get videos which belong to tags with ids **both** 3 and 4 Also, i want to know how many rows are there. How shou...
Your query should be doing what you want. But, you can simplify it: ``` SELECT v.* FROM video v INNER JOIN video_tag vt ON v.id = vt.video_id WHERE vt.tag_id IN (3, 4) GROUP BY v.id HAVING COUNT(v.id) = 2 ORDER BY v.id DESC ; ``` The only time this would not work is when a video can have duplicate tags of t...
Here is the complete query. It will show you every video, with it's total number. Hope it helps. ``` SELECT v.id, COUNT(v.id) as [Number] FROM video AS v -- using alias INNER JOIN video_tag vt ON v.id = vt.video_id INNER JOIN tag t ON t.id = vt.tag_id WHERE vt.tag_id IN (3,4) -- this is...
SQL COUNT with 2 INNER JOINS
[ "", "mysql", "sql", "" ]
I have a table tbldeptdivision as follows: ``` ID DEPTID DIVISIONID FROMDATE TODATE REMARKS --- ------- ----------- ----------- ----------- -------- 21 21 5 31-AUG-99 01-JAN-80 NULL ``` I have the query ``` select * from tbldeptdivision where deptid = 21 and trunc(sysdate) betwe...
As your `todate` is a `date` your problem stems from the useless conversion of the column's value from a date to a varchar and back to a date: `to_date()` converts a **`VARCHAR`** to a `DATE` value. If the value you pass to that function is *already* a `DATE` Oracle will first implicitely convert your date to a varcha...
Assume `FROMDATE/TODATE` datatype is `varchar2` then when you do `to_date`; ``` select to_date('01-JAN-80','dd-mon-yyyy') from dual; OutPut: January, 01 0080 00:00:00 ``` So it wont be `'01-JAN-2080'` but `'01-JAN-0080'` Even if `FROMDATE/TODATE` datatype is `date` tusing `to_date` is not a good idea; ``` create ta...
Retrieve data within a date range in Oracle
[ "", "sql", "oracle", "date", "between", "date-range", "" ]
I have this stored procedure: ``` ALTER PROCEDURE spCertificationType @result nvarchar(15) output, @mode int AS BEGIN if @mode = 1 begin exec spGeneratedID 2, @result output print @result end END ``` but when I tried to execute it,it has this error > The formal parameter “@mode”...
the sequence of parameter in store procedure is that first use input parameter then use output parameter:- you can see this link for more knowledge of store procedure:- <http://www.codeproject.com/Articles/126898/Sql-Server-How-To-Write-a-Stored-Procedure-in-SQL> ``` ALTER PROCEDURE spCertificationType @mode i...
I fixed this error a different way. 1. I had removed the OUTPUT statement after a parameter in my SP. 2. I then got the error. 3. I then went back to the SQLDataSource Configure Data Source wizard and went through the steps again. I discovered that changing the SP made the wizard delete the settings associated with th...
The formal parameter “@mode” was not declared as an OUTPUT parameter, but the actual parameter passed in requested output
[ "", "sql", "sql-server-2008-r2", "" ]
I want to insert all the rows from the cursor to a table.But it is not inserting all the rows.Only some rows gets inserted.Please help I have created a procedure BPS\_SPRDSHT which takes input as 3 parameters. ``` PROCEDURE BPS_SPRDSHT(p_period_name VARCHAR2,p_currency_code VARCHAR2,p_source_name VARCHAR2) IS ...
Oracle uses two engines to process PL/SQL code. All procedural code is handled by the **PL/SQL engine** while all SQL is handled by the SQL statement executor, or **SQL engine**. There is an overhead associated with each **context switch** between the two engines. The entire **PL/SQL** code could be written in plain *...
First of all let me point out that there is a serious bug in the code you are using: that is the reason for which you are not inserting all the records: ``` BEGIN OPEN c_sprdsht; LOOP FETCH c_sprdsht BULK COLLECT INTO v_t_spr -- this OVERWRITES your array! -- it does n...
Bulk Collect with million rows to insert.......Missing Rows?
[ "", "sql", "oracle", "plsql", "" ]
I have column values as AVG,ABC, AFG, 3/M, 150,RFG,567, 5HJ Requirement is to sort as below: ABC,AFG,AVG,RFG,3/M,5HJ,150,567 Any help?
If you want to sort letters before numbers, then you can test each character. Here is one method: ``` order by (case when substr(col, 1, 1) between 'A' and 'Z' then 1 else 2 end), (case when substr(col, 2, 1) between 'A' and 'Z' then 1 else 2 end), (case when substr(col, 3, 1) between 'A' and 'Z' the...
This doesn't produce the requested output, but for lexicographic with numbers second `TRANSLATE` is a simple solution: <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions196.htm> ``` select value from ( select 'AVG' as value from dual union all select 'ABC' as value from dual union all select '...
Oracle Order By Sorting: Column Values with character First Followed by number
[ "", "sql", "oracle", "oracle-sqldeveloper", "" ]
I think I may be missing the obvious here but im trying to create a sql query to pull data out in a particular way but cant work it out. I have a table which is made up with the following columns: ``` Name, StageDate, Stage ``` I want to create in sql an output something like this: ``` Name, Stage, Stage1Date, Stag...
Try this: ``` DECLARE @Stages TABLE ( Name varchar(20), Stage int, StageDate datetime); INSERT INTO @Stages (Name, Stage, StageDate) VALUES ('Player 1', 1, '2015-04-01'), ('Player 1', 2, '2015-05-01'), ('Player 1', 3, '2015-06-01'), ('Player 2', 1, '2015-04-01'), ('Player 2', 2...
The only thing I could come up with for now is using `UNIONS`, as an alternatives to other answers using subqueries: ``` SELECT Name, stage, stagedate AS Stage1Date, NULL AS Stage2Date, NULL AS Stage3Date FROM details WHERE stage = 1 UNION SELECT d1.Name, d1.sta...
sql If statement or case
[ "", "sql", "if-statement", "case", "" ]
Example: ``` <root> <StartOne> <Value1>Lopez, Michelle MD</Value1> <Value2>Spanish</Value2> <Value3> <a title="49 west point" href="myloc.aspx?id=56" target="_blank">49 west point</a> </Value3> <Value4>908-783-0909</Value4> <Value5> <a title="...
Try to delete the anchor element first and then insert the new one. It does not matter if it is there or not for the delete statement. I also provided a better way to build your new anchor element. It takes care of creating entities for characters like `&`. ``` -- Delete the anchor node from the XML set @xml.modify('d...
i hope this will help you ``` Declare @locUrl varchar(255); Set @locUrl = 'xyz.aspx?id=' + '444' + ''; declare @xml xml; set @xml = '<root> <StartOne> <Value1>Lopez, Michelle MD</Value1> <Value2>Spanish</Value2> <Value3> <a title="49 west point" href="myloc.aspx?id=56" target="...
How to use IF/ELSE statement to update or create new xml node entry in Sql
[ "", "sql", "sql-server", "xml", "" ]
I am trying to retrieve all records between two dates and the MySQL query is bringing back records with a completely different date. My Query Is ``` SELECT datecreated FROM TABLE_COMPLAINTS WHERE datecreated BETWEEN '01/08/2015' AND '24/08/2015' ``` The result from that query is this: [![enter image description her...
Try this ``` SELECT datecreated FROM TABLE_COMPLAINTS WHERE datecreated BETWEEN to_date('01/08/2015','MM/DD/YYYY') AND to_date('24/08/2015','MM/DD/YYYY') ``` **Solution 2** ``` SELECT datecreated FROM TABLE_COMPLAINTS WHERE datecreated >='01/08/2015' AND datecreated <= '24/08/2015' ``` **Solution 3** ``` SELECT d...
Give this format a try: ``` SELECT datecreated FROM TABLE_COMPLAINTS WHERE datecreated BETWEEN '2015-08-01' AND '2015-08-24' SELECT datecreated FROM TABLE_COMPLAINTS WHERE datecreated BETWEEN STR_TO_DATE('01/08/2015','%d-%m-%Y') and STR_TO_DATE('24/08/2015','%d-%m-%Y'); ```
MySQL return All records between two dates
[ "", "mysql", "sql", "database", "" ]
Table: `parent_id, parent_name, child_id, child_gender` How to list `parent_id` who have at least one boy and one girl.
*Group by* the `parent_id` and take only those *having* children with at least 2 *distinct* genders ``` select parent_id from your_table group by parent_id having count(distinct child_gender) = 2 ```
To get the parents that have a boy: ``` select parent_id from table where child_gender = 'M' ``` To get the parents that have a girl: ``` select parent_id from table where child_gender = 'F' ``` So to get the parents that are in both result sets: ``` select parent_id from table where child_gender = 'M' intersect s...
select parent_id who have at least one boy and one girl
[ "", "sql", "" ]
I'm trying to return all rows which are associated with a user who is associated with ALL of the queried 'tags'. My table structure and desired output is below: ``` admin.tags: user_id | tag | detail | date 2 | apple | blah... | 2015/07/14 3 | apple | blah. | 2015/07/17 1 | gr...
The query in the derived table gets you the user ids for users that have all specified tags and the outer query gets you the details. ``` select * from "system.users" s join "admin.tags" a on s.id = a.user_id join ( select user_id from "admin.tags" where tag in ('apple', 'pear') group by user_id ...
Standard double-negation method for *must-have-them-all* kind of relational division problem: (I renamed `date` to `zdate` to avoid using a keyword as identifier) --- ``` -- For convenience: put search arguments into a temp table or CTE -- I cheat by extracting this from the admin_tags table -- (in fact, ...
Postgres exclusive tag search
[ "", "sql", "postgresql", "relational-division", "" ]
Suppose I have some data like: ``` id status activity_date --- ------ ------------- 101 R 2014-01-12 101 Mt 2014-04-27 101 R 2014-05-18 102 R 2014-02-19 ``` Note that for rows with id = 101 we have activity between 2014-01-12 to 2014-04-26 and 2014-05-18 to current date. Now I need to select...
If I understand correctly: **Step 1:** Convert the start and end date rows into columns. For this, you must join the table with itself based on this criteria: ``` SELECT dates_fr.id, dates_fr.activity_date AS date_fr, MIN(dates_to.activity_date) AS date_to FROM test AS dates_fr LEFT JOIN test AS dates_to ...
You can try ``` select id, status, activity_date from TABLE where status = "R" and activity_date = "2014-02-02" ``` where TABLE is name of your table
MySQL select rows where given date lies between the dates stored in table
[ "", "mysql", "sql", "date", "datetime", "" ]
I am trying to filter some row of a table with ssdt (left click on table, view data, sort and filter) Here I simply need to add `IS NULL` as a condition to an `nvarchar` field. But as soon as I apply filter I get the error: > Incorrect syntax near the keyword SET Looking at the query written by editor I see that t...
It seems to be a bug that IS (NOT) NULL expression is not supported in the filter.
This is a very ugly hack, but it may work for you. It seems like you need a column name on the left of the = sign to keep the filter parser from changing the query. In my case my column that I was looking for nulls in was an integer, so I needed to get an integer on the left hand side. I also needed a value for the c...
Visual Studio 2013 SSDT - Edit data - IS NULL not work as filter
[ "", "sql", "visual-studio", "sql-server-data-tools", "" ]
I have the data with users tracking time. The data is in segments and each row represent one segment. Here is the sample data <http://sqlfiddle.com/#!6/2fa61> How can I get the data on daily basis i.e. if a complete day is of 1440 minutes then I want to know how many minutes the user was tracked in a day. I also want...
Use [table of numbers](http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1). I personally have a permanent table `Numbers` with 100K numbers in it. Once you have a set of numbers you can generate a set of dates for the range that you need. In this query I'll take `MIN` and `MAX` dates from your data, but ...
you should group by the day value. you could get the day with the function DATEPART as in : DATEPART(d,[StartTime]) ``` SELECT cast([StartTime] as date) as date ,sum(datediff(n,[StartTime],[EndTime])) as "min" FROM [test].[dbo].[track] group by DATEPART(d,[StartTime]),cast([StartTime]as date) ```
How can I get aggregate values for all dates, even when missing data for some days?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table called `ClientUrls` that has the following structure: ``` +------------+----------------+----------+ | ColumnName | DataType | Nullable | +------------+----------------+----------+ | ClientId | INT | No | | CountryId | INT | Yes | | RegionId | INT |...
This is easy (if i understand you correctly). You can do it with very little code. Plus it would be easy to extend if needed. Here is a working example ``` --Make a table CREATE TABLE #ClientUrls (ClientId INT NOT NULL,CountryId INT NULL,RegionId INT NULL,LanguageId INT NULL,URL NVARCHAR(2048) NOT NULL) --Put some d...
Not tested but you could do something like this: ``` SELECT TOP 1 c.ClientId, c.CountryId, c.RegionId, c.LanguageId, c.URL FROM ClientUrls c ORDER BY CASE WHEN c.ClientId = @ClientId THEN 1000 ELSE 0 END + CASE W...
Stored proc to return data based on nullable columns by a priority
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have a query in `postgresql` which generates: ``` statusid,qty 17 25 30 17 45 18 20 ``` I want to remove all rows that `statuis` is `deleted` (`17`) and keep rows with `NULL`. What I did is: ``` WHERE statuid not in (select statusid from statuses where statusname='deleted') ``` What...
You cannot compare `NULL` with any value(`NOT IN` compares it), you have to use `IS NULL`: ``` WHERE statusid IS NULL OR statusid not in (select statusid from statuses where statusname='deleted') ``` `NULL` is neither equal nor unequal to any other value not even with `NULL`. It's undefined.
Add `is null` explicitly: ``` <your query> or statuid is null ```
How to handle NULL in Where?
[ "", "sql", "postgresql", "" ]
My SQL query needs to return a list of values alongside the date, but with my limited knowledge I have only been able to get this far. This is my SQL: ``` select lsu_students.student_grouping,lsu_attendance.class_date, count(lsu_attendance.attendance_status) AS count from lsu_attendance inner join lsu_students ON ls...
Just take out `and lsu_attendance.class_date="2015-02-09"` or change it to a range, and then add (at the end) `GROUP BY lsu_students.student_grouping,lsu_attendance.class_date`.
I think you just want a `group by`: ``` select s.student_grouping, a.class_date, count(a.attendance_status) AS count from lsu_attendance a inner join lsu_students s ON s.student_grouping = 'Central1A' and s.student_id = a.student_id where a.attendance_status = 'Present' group by s.student_grouping, a...
Complex SQL Select query with inner join
[ "", "mysql", "sql", "" ]
I have `SELECT` query below: ``` select * from table t Where t.policy_date = @var1 and t.insurer_id = @var2 ``` Here `@var1` could by empty and `@var2` also could be empty. If `@var1` is empty condition must be only `t.insurer_id = @var2`. if `@var2` is empty condition must be `t.policy_date = @var1`. Or they can...
use this ``` select * from table t Where (@var1 IS NULL OR t.policy_date = @var1) and (var2 IS NULL OR t.insurer_id = @var2) ``` when `@var` is null the first part of the where clause became `true` so we have just the second part to evaluate, and vice versa. **Note:** If you mean `''` by "empty", use `@var = ''` i...
``` select * from table t where (@var1 is null or t.policy_date = @var1) and (@var2 is null or t.insurer_id = @var2) ```
Condition in SQL statement
[ "", "sql", "sql-server-2014", "" ]
I need to query a table in order to return rows, but I'm not able to query the table correctly. Here is my table view: ``` Id Name Date Subject TrackingToken RegardingObjectId Type TypeName 1 XXXX 8/26/2015 RE: XXXXXX CRM:0030062 496BF810-4DBE-E311-9357-00505686395...
You can use the analytic version of COUNT to count records over a certain range (within the TrackingToken in your case). Then only keep those records where the count of different RegardingObjectId is greater than one. ``` select * from ( select mytable.* , count(distinct regardingobjectid) over (partition by tr...
You can count the distinct number of [RegardingObjectId]: ``` select TrackingToken from [TableX].[dbo].[Email] group by TrackingToken having count(distinct [RegardingObjectId]) > 1 ```
How to select rows based on column value is repeating and has different values in another column
[ "", "sql", "sql-server", "t-sql", "select", "" ]
i have a case statement in plsql , and the thing is for more than one case i am calling same procedure , so don't want to call the same function again and again and want to club the cases together which call same procedure. ``` LOOP FETCH cu_my_c...
Just Replace your `case` like below ``` CASE WHEN lr_my_rec.method_name in ('ProductName','ProductVersion','ProductType') THEN -- population record with product name , product version and product type p_required_det(pn_product_reference => pr_mi_exits.policy_reference ,pv_pro...
``` declare V_TEST varchar2(10) := 'a'; V_TEST2 varchar2(10) := 'a'; begin case when v_test in ('a','b','c')then null; when V_TEST2 in ('a','b','c')then null; else null; end case; end; ```
how to club multiple cases with OR in case statement in plsql
[ "", "sql", "oracle", "plsql", "" ]
I have a table with team names, the date the team was created, and the date the team was dissolved: ``` TeamName TeamStartDate TeamEndDate Business Analysis 2012-12-31 00:00:00.000 2013-06-30 00:00:00.000 Business Systems 2012-06-18 ...
The answer to your question is: **Unable to determine; not enough information.** You could have renamed "Business Analysis" to "Business Systems"... or renamed it to "Pie" for all we know. You need to an identifier that tells both names actually belong to the same team. If the data would include a team's unique ident...
``` SELECT TeamName, TeamStartDate, TeamEndDate FROM [TableName] WHERE '2015-08-01 00:00:00' BETWEEN TeamStartDate AND TeamEndDate ``` 01/08/2015 is the date you want to search on
How to select oldest item from records with overlapping dates
[ "", "sql", "sql-server", "" ]
I have a column in Oracle DB which is `varchar2` data type. Typical value stored in this column is like `06/16/2015 02:14:18 AM`. I am trying to get all records wherein this column is having records after 1st August 2015. ``` select * from MYTABLE where to_date(substr(MYCOLUMN,1,10),'dd-mm-yyyy') > to_date('01-08-20...
Respect the format in your VARCHAR ``` ....where to_date(substr(MYCOLUMN,1,10),'mm/dd/yyyy') ```
> I have a column in Oracle DB which is varchar2 data type. Typical value stored in this column is like 06/16/2015 02:14:18 AM. The first question is why do you store **DATE** as **string**? Using appropriate **data type** is one of the most important part of **database design** and **performance**. Understand that *...
ORA-01843: not a valid month error
[ "", "sql", "oracle", "date", "date-comparison", "" ]
``` select Date(createdOn) Date, count(createdOn) "No of Questions" from Questions group by Date(createdOn); ``` Date                  No of Questions 2015-08-25                 3 2015-08-26                 8 2015-06-27                 13 2015-06-28                 35 I am not an expert in mysql. Based on my re...
Instead of `Group By` use `where` condition like this: ``` select Date(createdOn) `Dated`, count(createdOn) "No of Questions" from Questions where Date(createdOn) = CURDATE(); ``` Do check if you have data specific to the CURDATE() ie, 2015-08-28 eles try like this: ``` select Date(createdOn) `Dated`, count(create...
Try this: ``` select Date(createdOn) Date, count(createdOn) "No of Questions" from Questions group by Date(createdOn) having Date(createdOn) = CURDATE(); ```
SQL query to find number of questions asked on a specific day
[ "", "mysql", "sql", "" ]
Hi i have String like This ``` 1;2;12;15;6;77; ``` which contain ids of table A and table A is ``` id setcolumn 1 false 2 false 3 false ... ``` and i want to set true each row have id in my input string. So can anyone Help me about this?
You can do something like this: --- **SAMPLE DATA** ``` CREATE TABLE #Test ( Id NVARCHAR(100) ) INSERT INTO #Test VALUES ('1;2;12;15;6;77') CREATE TABLE #Test2 ( Id NVARCHAR(100), Setcolumn NVARCHAR(100) ) INSERT INTO #Test2 VALUES (1, 'false'), (2, 'false'), (3, 'false'), (4, 'false') ``` --- **QUERY...
Here is an example ``` CREATE TABLE #tt(id INT, flag BIT) INSERT INTO #tt VALUES (1,0),(2,0),(3,0) DECLARE @S VARCHAR(max), @Split CHAR(1), @X XML SELECT @S = '1;2;3;4;5', @Split = ';' SELECT @X = CONVERT(xml,' <root> <s>' + REPLACE(@S,@Split,'</s> <s>') + '</s> </root> ') UPDATE tbl SET ...
Filter Columns which have id in splitted String in sqlserver 2008
[ "", "sql", "sql-server-2008", "" ]
I have a table #tmpName with just one column, [Name]. Without using a cursor, I would like to take each row of #tmpName (which is technically one name), do something with that name, and then delete from #tmpName. I began with something like this, but it's very slow and I eventually get an out of memory exception, whi...
-- once you have data in the temp table, you could something like this.... ``` -- populate temp table select Name INTO #tmpName from [Employees] group by Name DECLARE @Name VARCHAR(100); while EXISTS(SELECT * FROM #tmpName) BEGIN select top 1 @Name = Name From #tmpName -- do stuff with top 1 del...
``` drop table #tmpName ; select row_number() over(order by Name) as rn, Name into #tmpName From [Employees]; declare @count int = (select count(*) from #tmpName) declare @rn int = 1 while @count > 0 begin select Name From #tmpName where rn = @rn --do stuff with top 1 delete from #tmpName where rn = @rn set @coun...
Use top 1 and then delete?
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using postgresql... I need to implenet a function that merge two rows in the table. assume that I already have the id of the two rows and it's ok to merge them. **Example:** ``` id quantity isOK 5 20 FALSE 5 10 FALSE 6 30 TRUE 6 35 FALSE ``` after calling on id 5 the table will *...
`EXISTS()` yields a boolean, which can be used in the result ``` =-- The table CREATE TABLE t_test(id INTEGER,value INTEGER, fld Boolean); -- The data INSERT INTO t_test (id, value, fld) VALUES (1, 23, 'TRUE'), (1, 22, 'FALSE'), (2, 2, 'FALSE'), (2, 23, 'FALSE'); -- The query SELECT t.id , SUM(t.value) ...
First take the desired id as parameter: ``` create function myfunc(selectedid integer) returns integer as ``` Declare two local variables: ``` declare mergedquantity integer; mergedisOK boolean; ``` Then merge the records: ``` select sum(quantity), case when sum(isOK) > 0 then true else false end into mergedquanti...
How to implement a boolean OR update instraction?
[ "", "sql", "postgresql", "" ]
I have a table that contain a list of properties that will be visible to user. but I inserted data in wrong format,I want to swap values of `[ActionName]` with `[ControllerName]` name without creating a temporary table. ``` SELECT [MenuID] ,[MenuName] ,[MenuMasterID] ,[ActionName] ...
Use assigment/aliasing if you want to swap only when querying ``` SELECT t.[MenuID] ,t.[MenuName] ,t.[MenuMasterID] ,[ActionName] = t.[ControllerName] ,[ControllerName] = t.[ActionName] ,t.[ImageClassName] ,t.[MainOrderID] ,t.[SubOrderID] FROM [DEV_CMS_Medical].[dbo...
``` UPDATE [DEV_CMS_Medical].[dbo].[SEC_Menus] SET ActionNamec = ControllerName, ControllerName = ActionName ``` Or IF you want show the data with out any manipulation just use the alias name for required columns
swapping values of database table
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm trying to replace multiple white spaces and carriage return with a single white space in sql. I've come up with following so far: ``` select replace( replace( replace( replace( replace( replace( LTrim(RTrim(' 6 Spaces 6 Spaces. abcde ')),char(13),''),--Trim the field enter ...
Well I'll just put this out there as an alternative since I just finished it up the second an answer was accepted. This will also give you the results you desired by trimming and replacing in the correct orders: ``` Select Replace(replace(replace(replace( RTRIM(LTRIM(this)), ...
This type of problem is tricky to solve with simple replace functionality but becomes very easy with a regex function. Sadly Microsoft haven't included this as a built in function for SQL Server but with some SQLCLR work it can be available. [SQL Server Regular expressions in T-SQL](https://stackoverflow.com/question...
How to replace multiple white spaces and carriage return with a single white space in sql
[ "", "sql", "sql-server", "t-sql", "" ]
I have to separate select queries I'm looking to combine in to one query. Meaning I'd like my out put formatted like: col 1 | col2 252 ---- 05 One idea is to write a CTE and while these two are small queries I have about 4 more like this for date ranges which I thought to avoid using one or more CTES to get the data...
Add `0` column to each query then `sum` over `union` of them: ``` SELECT SUM(pastDueRepl) as pastDueRepl, sum(pastDueInsp) as pastDueInsp FROM( SELECT count(*) as pastDueRepl , 0 as pastDueInsp FROM TBLPTS_APPDATA WHERE APPV_PTSSTATUS = '2' AND (APPD_NEXTREPLDATE IS NOT NULL) AND APPD_NEX...
This can be a good way to minimize the repetition and reduce the amount of times you have to hardcode your date range boundaries: ``` with DateRangeBoundaries as (select DATEADD(Day,-30,GETDATE()) as LowerBoundDate, GETDATE() as UpperBoundDate) select count(case when t.APPD_NEXT...
Rewrite into single query
[ "", "sql", "sql-server-2012", "subquery", "correlated-subquery", "" ]
These are my tables: ``` Product: ID PRICE NAME DESCRIPTION 1 100 laptop laptop_desc 2 200 mouse mouse_desc Product_Translations: PID LANG NAME DESCRIPTION 1 ch 伊吾 伊吾伊吾 ``` Please don't worry about name and description in the Product table. We are keeping it to avoid join if default language is se...
``` SELECT p.ID, p.Price, COALESCE(pt.Name, p.Name) Name, COALESCE(pt.Description, p.Description) Description FROM Product p INNER JOIN User u on u.ID = @MyUserID LEFT JOIN Product_Translations pt ON pt.PID = p.ID AND pt.LANG = u.LANG ```
Use LEFT OUTER JOIN: ``` SELECT p.id ,p.price ,ISNULL(t.name, p.name) AS translation ,ISNULL(t.description, p.description) AS description FROM Product p LEFT JOIN Translations t ON p.id = t.pid AND t.lang = ? ``` This will work on SQL Server if you use other DB change to COALESCE().
SQL query to get default values if translations are not found
[ "", "sql", "hsqldb", "" ]
Here is my statement for create view and related error message, using MySQL/MySQL WorkBench. I tried the select -- from -- where works. Any hints are appreciated. :) ``` CREATE VIEW [Products Above Average Price] AS SELECT ProductName,Price FROM Products WHERE Price>(SELECT AVG(Price) FROM Products) ``` >...
You have to use *ANSI standard* double quotes `""` instead of `[]` brackets. ``` CREATE VIEW "Products Above Average Price" AS SELECT ProductName,Price FROM Products WHERE Price>(SELECT AVG(Price) FROM Products) ```
Here is how view creation is supposed to look like in MySQL ``` Create View `MyViewName` as Select col1, col2, col3 From myTable T ``` In your case, the problem occures because of `[]` which aren't used in MySQL. Replace your query with ``` CREATE VIEW `Products Above Average Price` AS ...
MySQL create view error
[ "", "mysql", "sql", "" ]
I am trying to remove the text between the square brackets, however it only seems to remove the brackets. ``` SELECT Replace(Replace(aud_desc, '[', ''), ']', '') from _audit ``` `aud_desc` is `This is [a] test` however with the above I have got it to show `This is a test`, I am not sure why its not removing the text ...
Use the `REPLACE`, `LENGTH`, `LOCATE`, `REVERSE` & `SUBSTRING`functions. ``` SELECT REPLACE(aud_desc, SUBSTRING(aud_desc, LOCATE('[', aud_desc), LENGTH(aud_desc) - LOCATE(']', REVERSE(aud_desc)) - LOCATE('[', aud_desc) + 2), '') AS aud_desc FROM _audit ``` Input: aud\_desc ``` word [brakcet] word [brakcet] word wor...
Here's a user-defined function that does it and works with multiple bracket pairs in the string: ``` DELIMITER // CREATE FUNCTION REMOVE_BRACKETS(input TEXT CHARACTER SET utf8 COLLATE utf8_bin) RETURNS TEXT CHARACTER SET utf8 COLLATE utf8_bin BEGIN DECLARE output TEXT CHARACTER SET utf8 COLLATE utf8_bin DEFAUL...
remove text between square brackets
[ "", "mysql", "sql", "" ]
I have a result as follows ``` DATE EID TIME TYPE 2015-07-26 1 10:01:00 IN 2015-07-26 1 15:01:00 OUT 2015-07-26 1 18:33:00 IN 2015-07-26 1 23:11:00 OUT ``` I want to split IN, OUT into different columns `ORDER BY date, eid, time`. expected result should be as follows ``` DAT...
I have written a query for you. I am hoping it will solve your problem : **SQL FOR TABLE SCHEMA** ``` CREATE TABLE `attendance` ( `date` date DEFAULT NULL, `eid` int(11) DEFAULT NULL, `time` time(6) DEFAULT NULL, `type` varchar(5) DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) EN...
Assuming the data are valid (there is not more than one `IN` between two `OUT`), using window functions: ``` SELECT DATE, EID, `IN`, `OUT` FROM (SELECT date AS 'DATE', eid AS 'EID', (SELECT MAX(TIME) from attendance where DATE = a.DATE AND TIME <= a.TIME AND TYPE = 'IN' AND EID = a.EID) as 'IN', ...
MySQL: splitting result into two different columns
[ "", "mysql", "sql", "" ]
In my Employee table, I wanted to find the 3rd highest salary. Someone provided me with the following query to do this: ``` SELECT * FROM employee C1 WHERE 3 = (SELECT Count(DISTINCT( C2.salary )) FROM employee C2 WHERE C2.salary >= C1.salary) ``` This query works, but I don't how it...
As others have said, this type of query is called a correlated sub-query. It's a sub-query because there is a query within a query and it's correlated because the inner query references the outer query in its definition. Consider the inner query: ``` SELECT Count(DISTINCT( C2.salary )) FROM employee C2 WHERE C2....
Maybe a better solution would have been ``` SELECT TOP 1 * FROM ( SELECT TOP 3 * FROM employee ORDER BY Salary DESC ) t ORDER BY Salary ASC ``` Easier to read and more efficient than a correlated sub-query.
What kind of query is this?
[ "", "sql", "sql-server", "" ]
I have a table, `Contacts: Contact_ID (int) ContactName (nvarchar)` I am given a list of contact IDs to select from. Usually, i would just do ``` SELECT * FROM Contacts WHERE IN (List of contact ID) ``` The problem is, the list of contact IDs could potentially get very big, like 50k or more. So my question is, Is ...
I'd create a table type with a single column and a clustered primary key. ``` CREATE TYPE dbo.ContactId AS TABLE ( ContactId INT NOT NULL PRIMARY KEY ); ``` Pass the values into the query using a table valued parameter. Change your query to ``` SELECT * FROM Contacts WHERE contactID IN (SELECT y.contactID FRO...
If you want performance, I would use the EXISTS clause. ``` SELECT c.Contact_ID, c.ContactName FROM Contacts c WHERE EXISTS (List of contact ID) ```
SQL, trying to get rid of large IN cluase
[ "", "sql", "sql-server", "sql-in", "" ]
Here is my table "puntos": ``` Equipo Liga Puntos --------------------------- At. Madrid 1 68 Espanyol 1 64 Barcelona 1 63 Real Madrid 1 61 Castellón 1 48 Murcia 2 78 Elche 2 70 Sevilla 2 60 Valladolid 2 57 ``` I j...
Another option is to use [9.4 User-Defined Variables](http://dev.mysql.com/doc/refman/5.6/en/user-variables.html): ``` SELECT `der`.`Equipo`, `der`.`Liga`, `der`.`Puntos` FROM ( SELECT `p`.`Equipo`, `p`.`Liga`, `p`.`Puntos`, IF(@`prev_liga` != `p`.`Liga`, @`rownum` := 1, @`rown...
First, this solution will only work if `Equipo` is unique across all leagues. If not - you should add `equipoID` and use it instead. Now, we first select the leader of each league. Then create a union with the same select again, only using the WHERE to filter out the teams that we've already got on our first union. Th...
How to select more than one row per group in MySQL?
[ "", "mysql", "sql", "greatest-n-per-group", "" ]
I am fairly new to using joins and selecting from multiple tables. I have successfully figured out how to get data from 2 tables based on a number of conditions. Now my issue is that I need to return a count only if another condition is also met. The idea is like this: I have a query that returns the number of items in...
You can adjust the subselect as needed, but this will return a row if another value is found in the database. I don't like subselects, but this should work. I have not tested the syntax. ``` select count(*), e.campus_id, e.course_id FROM statuses_history as sh, enrolments as e WHERE sh.date_added > '2015-08-01 00:00:...
I assume that the primary key is item\_id? You just have to join the same tables by the primary key and the status\_id = 50. For this case I will use INNER JOIN (my preference) but you can use FROM/WHERE CLAUSE. ``` select count(*), e.campus_id, e.course_id FROM statuses_history as sh, enrolments as e INNER JOIN ...
SQL query with multiple criteria and sub selects
[ "", "mysql", "sql", "" ]
I have two queries, but I want the results to be in the same return table. The first query returns a list of all posts with their comments as a list. The comments are stored in a different table. ``` SELECT E.id, E.time, E.title, E.body, E.type, C.comments FROM elements E LEFT JOIN( SELECT elementID, GROUP_CONCAT...
Well, why can't you `JOIN` both the query like you have already done for other query ``` SELECT E.id, E.time, E.title, E.body, E.type, C.comments, E.googleID, L.likeCount FROM elements E LEFT JOIN( SELECT elementID, GROUP_CONCAT(body SEPARATOR '|-|') AS comments FROM comments GROUP BY elementID ) C on C.el...
You can "stack" joins of the same level together, like this: ``` SELECT E.id , E.time , E.title , E.googleID , E.body , E.type , C.comments , L.likeCount FROM elements E LEFT JOIN( SELECT elementID, GROUP_CONCAT(body SEPARATOR '|-|') AS comments FROM comments GROUP BY elementID ) C on C.e...
How to use two LEFT JOINs on one query?
[ "", "mysql", "sql", "database", "database-design", "" ]
I have a database table of that I have used to store the data returned from a web spider. I have a column that contains ticket prices for different events all in the varchar type (as the scrapy spider has to scrape the data in unicode). I'm trying to return the min price of the column and since the min() function only ...
You have decimal places in the string, so a simple cast is not going to work. You *can* do a double conversion: ``` cast(cast(ticketprice as decimal(10, 2)) as int) ``` or: ``` (ticketprice::decimal(10, 2))::int ``` (The parens are not strictly necessary.) EDIT: Or, as Erwin points out, just use `numeric`: ``` (...
I'm going to bet on your column have wrong characters. Also you may want use float or numeric because you will lose decimals if convert to integers. You need create a function to check if a text is numeric like this [*isnumeric-with-postgresql*](https://stackoverflow.com/questions/16195986/isnumeric-with-postgresql) ...
Can't convert postgresql table column from type varchar to int
[ "", "sql", "postgresql", "scrapy", "" ]
How should HTML Entities be stored on SQL server? Should they be stored as the entity or as the character. Which is correct and does it really matter? For example **Storage Solution 1** ``` &amp; &gt; &lt; ``` **Storage Solution 2** ``` & < > ```
I feel like storage solution 1 is more secure, as it helps to drastically cut down on your risk of accidentally executing some script unintentionally if you have someone embedding javascript or the like in their input. Which, granted, you should be stripping out, but it's a best practice kind of thing to store the ent...
Whenever storing any kind of data, you should consider this guideline that: * Data/info should not be tampered or changed from it's original form * It should be independent from any processing/conversion logic This may not be applicable always, espeically when storing sensitive info like passowrds, credit card or any...
How should HTML Entities be stored on SQL server?
[ "", "sql", "sql-server", "html-entities", "" ]
I wrote the following query ``` SELECT UNIQUE CITY FROM STATION WHERE (CITY LIKE '%A' OR CITY LIKE '%E' OR CITY LIKE '%I' OR CITY LIKE '%O' OR CITY LIKE '%U') ORDER BY CITY; ``` What is wrong with this?
If you want it to work with lower/upper letters, you could use `UPPER(CITY)`, otherwise it's all good.
I think you can use `REGEXP_LIKE` like this: ``` SELECT UNIQUE CITY FROM STATION WHERE REGEXP_LIKE(CITY, '[AaEeIiOoUu]$') ORDER BY CITY; ```
In SQL I want to display the names of all those cities which end with an vowel
[ "", "sql", "oracle", "" ]
I've the following code ``` select * from weeks where case when wet>1000 then wenumber=1 when wet>500 then wenumber=2 when wet>100 then wenumber=3 else wenumber= 22 end ``` it gives me the result of both ( when > 1000 and else ) through my search I understood that it is search case, but I need to make it a simple ...
Try this: ``` SELECT * FROM weeks WHERE wenumber = CASE WHEN wet > 1000 THEN 1 WHEN wet BETWEEN 500 AND 1000 THEN 2 WHEN wet BETWEEN 100 AND 500 THEN 3 ELSE 22 END; ```
Better way of doing it ``` select * from weeks where ( wet>1000 and wenumber = 1 ) or wenumber = 22 ```
Convert searched case to simple case else
[ "", "mysql", "sql", "select", "case", "" ]
I'm trying to return a set of rows after doing `UPDATE`. Something like this. ``` UPDATE Notis new_noti SET notis = '{}'::noti_record_type[] FROM (SELECT * FROM Notis WHERE user_id = 2 FOR UPDATE) old_noti WHERE old_noti.user_id = new_noti.user_id RETURNING unnest(old_noti.notis); ``` but postgres complains, right...
Use [WITH statement](http://www.postgresql.org/docs/9.4/static/queries-with.html): ``` WITH upd AS ( UPDATE Notis new_noti SET notis = '{}'::noti_record_type[] FROM (SELECT * FROM Notis WHERE user_id = 2 FOR UPDATE) old_noti WHERE old_noti.user_id = new_noti.user_id RETURNING old_noti.notis ) SELECT ...
Use a [data-modifying CTE](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-MODIFYING). You *can* use a set-returning function in the `SELECT` list, but it is cleaner to move it to the `FROM` list with a `LATERAL` subquery since Postgres **9.3**. Especially if you need to extract *multiple* colu...
RETURNING rows using unnest()?
[ "", "sql", "database", "postgresql", "set-returning-functions", "sql-returning", "" ]
In my table i have two file one is **id** another is **strNum**. I want to order the **strNum** like as ``` One Two Three ``` My table data ``` id strNum ------ ------------ 1 Two 2 One 3 Five 4 Nine ``` I want to get output without any extra field add. ...
You can use this query : ``` SELECT strNum FROM your_table ORDER BY FIELD(strNum,'One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten') ASC ```
You can use `Case`: ``` select strNum from A order by case when strNum='one' then 1 when strNum='two' then 2 when strNum='three' then 3 when strNum='four' then 4 when strNum='five' then 5 when strNum='six' then 6 ...
SQL order by string order
[ "", "mysql", "sql", "" ]
Hey Stackoverflow community! I currently use a temporary table to store the list of arrays are compare which ones don't exist within the table and insert those but I'm hoping there is a quicker more optimized way. My goal is to get this down to one query 1.) I have an array of c\_no INTs (1,2,3,4,5) I would like to ...
I cannot comment due to rep, but in response to your comment on Didier's answer, instead of `INSERT` you can use `INSERT IGNORE` after you've created your `unique index`. When you use `INSERT IGNORE` MySQL will not insert the value, but will also suppress the error thrown due to attempting to insert a duplicate `unique...
I guess you are looking for the `IN` Keyword. ``` SELECT * FROM myTable WHERE field IN (myList) ``` If you want the g\_no field to have unique values, why do you don't add the `unique` index ? [MySQL Document - Create Index](https://dev.mysql.com/doc/refman/5.0/en/create-index.html)
Check if list is in table
[ "", "mysql", "sql", "" ]
I want to join these tables and count if the Status is 'Y' ``` table1(date, status) 8/23/2015 Y 8/24/2015 Y 8/24/2015 N table2(date, status) 8/23/2015 Y 8/23/2015 Y table3(date, status) 8/23/2015 Y 8/25/2015 N 8/25/2015 Y ``` The result I expect is like . . . ``` DATE count(table1.sta...
Perhaps the easiest way is to `union all` the tables together and then aggregation: ``` select date, sum(status1) as status1, sum(status2) as status2, sum(status3) as status3 from ((select date, 1 as status1, 0 as status2 , 0 as status3 from table1 where status = 'Y') union all (select date,...
Here's another alternative: ``` with table1 as (select to_date('23/08/2015', 'dd/mm/yyyy') dt, 'Y' status from dual union all select to_date('24/08/2015', 'dd/mm/yyyy') dt, 'Y' status from dual union all select to_date('25/08/2015', 'dd/mm/yyyy') dt, 'N' status from dual), table2 a...
How to join three tables and count the record with UNION one column
[ "", "sql", "oracle", "" ]
I have two database tables - `Categories` and `LocalizedCategories`. The `Categories` table has `Name` and `Description` columns for all categories in the default language. The `LocalizedCategories` table also has these columns which contain translations of these columns into other languages (every content language has...
Your table design seems fine. To get data only when it exists, is done with an **outer join**. Then use COALESCE to get one value or the other. ``` select coalesce(lc.name, c.name), coalesce(lc.description, c.description) from categories c left outer join localizedcategories lc on lc.categoryid = c.categoryid ...
simple, just do a left join : ``` select Description = coalesce(lc.Description, c.Description ) , Name = coalesce(lc.Name, c.Name) , Lang = coalesce(lc.Lang, DefaultContentLanguageId ) from Categories c left join LocalizedCategories lc on c.CategoryId=lc.CategoryId and lc.ContentLanguageId = ?...
Conditional SQL query column mapping
[ "", "sql", "sql-server", "database", "join", "" ]
There is a table with four columns: ``` SrNo Descript item1 item2 1 | AA | 45 | 25 2 | BB | 25 | 51 3 | CC | 41 | 22 ``` I want get results like this: ``` SrNo| Descript| item1 |item2| totalitems 1 | AA | 45 | 25 | 70 2 | BB | 25 | 51 | 76 3 | CC | 41 | 22 | ...
Try; ``` select SrNo, Descript, item1, item2, item1+item2 as totalitems from tbl ORDER BY SrNo union all select max(SrNo) + 1, 'Total', sum(item1), sum(item2), sum(item1+item2) as totalitems from tbl ```
Something like this ``` select SrNo, Descript, item1, item2, item1+item2 as totalitems from yourtable Union all select max(SrNo)+1, 'Total', sum(item1), sum(item2), sum(item1)+sum(item2) as totalitems from yourtable ``` **Note :** If the data type of `item1` and `item2` is `varchar` then you may have to `cast` it to ...
How do I get the sum of a column as a new row with column data
[ "", "sql", "" ]
I have a table of items with some values, among them cost and purchase date. I'm trying to get a list of the most expensive items, one per item type, ordered by the purchase date of that specific item, *without* the purchase date in the results. My table (simplified): ``` CREATE TABLE Purchases (ItemType varchar(...
Use window functions: ``` select ItemType, Cost MostExpensivePerType from (select p.*, row_number() over (partition by itemtype order by cost desc) as seqnum from purchases p ) t where seqnum = 1 order by PurchaseDate; ``` SQLFiddle [here](http://sqlfiddle.com/#!6/9668a/38).
``` SELECT ItemType, MAX(Cost) AS MostExpensivePerType FROM Purchases GROUP BY ItemType ORDER BY Max(PurchaseDate) DESC ```
How to GROUP BY one column and ORDER BY another in T-SQL
[ "", "sql", "t-sql", "ssms", "sql-server-2014", "" ]
this seems like it should be extraordinarily simple, so I apologize in advance if this information is easily accessible on the transact-sql documentation pages. I searched myself, but couldn't seem to find anything. I'm trying to modify a transact-sql statement that currently runs on our Windows server 2000 box. I wan...
Try doing the following: ``` DECLARE @dbName NVARCHAR(MAX) = 'master', @TableName NVARCHAR(MAX) = N'spt_monitor'; DECLARE @sql NVARCHAR(MAX) = N'SELECT * FROM [' + @dbName + N'].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''' + REPLACE(@TableName,N'''',N'''''') + N''''; SET NOCOUNT OFF; EXEC(@sql); IF @@ROWCOUNT > ...
The below code should do what you want. As was mentioned previously, the account running the query would need the privilege to query the INFORMATION\_SCHEMAs in the target database. To future-proof your stored procedure, I'd also suggest increasing the length of the database name parameter and declaring it as an nchar...
Using variables in Transact-sql exists subquery
[ "", "sql", "t-sql", "subquery", "" ]
I am trying to compare a column `col1` and a variable `@myvar` in a `WHERE` clause. Both usually contain GUIDs, but may also have NULL values. I thought I could get around the fact that `NULL=NULL` evaluates to FALSE by using `WHERE ISNULL(col1, '')=ISNULL(@myvar, '')`. That would compare two empty strings instead, and...
Since the first argument you are passing `isnull` is not a **literal `null`**, it will determine the return type of that call, a `uniqueidentifier` in your case. The second argument, `''`, cannot be cast to this type, hence the error you're getting. One way around this is just to explicitly check for `null`s: ``` WHE...
I think below expression can be used to check if the GUID column is empty ``` CAST(0x0 AS UNIQUEIDENTIFIER) ``` some thing like ``` ...WHERE GuidId <> CAST(0x0 AS UNIQUEIDENTIFIER) ```
SQL Server: ISNULL on uniqueidentifier
[ "", "sql", "sql-server", "null", "uniqueidentifier", "isnull", "" ]
I have tried looking around for this issue and couldn't find much. I was wondering the best method of removing duplicate parent/child rows in an SQL table. For example I have a table like so: ``` Id | CompanyId | DuplicateId 1 | 1 | 2 2 | 2 | 1 <------ CompanyId 2 is already a duplicate o...
Here is one method, that works in most databases: ``` delete from sqltable where duplicateid > companyid and exists (select 1 from sqltable st2 where st2.duplicateid = sqltable.companyid and st2.companyid = sqltable.duplicateid ...
Try this ``` SELECT * FROM tablename t1 where CompanyId not IN (SELECT Duplicateid from tablename WHERE CompnayId<>t1.CompanyId and duplicateid > companyid) ```
SQL Remove duplicate parent child entries
[ "", "sql", "sql-server", "" ]
Unfortunately I am not very strong when it comes to SQL and not very strong when it comes to explaining myself. I will try my best and hopefully someone can help. I have a table called soc\_stat which has a lot of colums. One of those is "timestamp" which is just a timestamp, and the other one is a date\_of\_post whic...
Try: ``` SELECT date(t.date_of_post) AS date, hour(t.date_of_post) as hour, count(*) as entries FROM `soc_stat` t WHERE t.date_of_post > DATE_SUB(CURDATE(), INTERVAL 1 DAY) GROUP BY date(t.date_of_post), hour(t.date_of_post) ``` OR: ``` SELECT DATE_ADD(date(t.date_of_post), INTERVAL hour(t.date_of_pos...
This is for per day and per hour ``` SELECT date(soc_stat.date_of_post) as date,hour(soc_stat.date_of_post) as hour, count(*) FROM `soc_stat` WHERE soc_stat.date_of_post > DATE_SUB(CURDATE(), INTERVAL 1 DAY) group by date(soc_stat.date_of_post),hour(soc_stat.date_of_post) ```
Fetching entries by hours from MySQL
[ "", "mysql", "sql", "database", "" ]
I have two tables messages and users I want to find out which users received the messages however the query is only returning one message. My Schemas are as follow **Messages** ``` msg_id | msg_content | recipients | ----------------------------------- 1 | Hello world | 1,2,3,4,5 2 | Test | 1,3,5 3 ...
I think you have to use a alternative way for create tables Messages ``` msg_id | msg_content | ---------------------- 1 | Hello world | 2 | Test | 3 | Welcome | ``` Users ``` uid | fname | lname | --------------------------- 1 | John |Doe | 2 | Jane |Doe | ...
Okay, so this schema isn't the best (using comma separated lists of IDs is not a great idea, and the performance of any joins will get pretty bad pretty quick). Best bet is to have a third table mapping uid's to msg\_id's as mentioned by @Thilina. That said, this query will do probably what you're after: ``` SELECT m...
MySQL Select use IN and GROUP BY
[ "", "mysql", "sql", "" ]
Please help me with this problem, I've been searching couple hours and can't solve it. Here is my code : ``` Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click connectionString = "Data Source=MININT-BJDM4MI;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSE...
When you create the SqlDataAdapter, you should be passing in your command object instead of the SQL string. ``` Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click connectionString = "Data Source=MININT-BJDM4MI;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERV...
It would be even better though if you used a stored procedure rather than to pass sql in your code, but the reason for your exception is because the @SOURCE variable isn't declared in your SQL statement. Try this: `sql = "DECLARE @SOURCE varchar(50);SELECT * FROM PRODUCT WHERE SAMPLE_SOURCE = @SOURCE"`
Must declare the scalar variable (SQL)
[ "", "sql", "vb.net", "" ]
I have an Oracle database with many tables that have identical structure (columns are all the same). The table names are similar also. The names of the tables are like table\_1, table\_2, table\_3... I know this isn't the most efficient design, but I don't have the option of changing this at this time. In this case, ...
You can use `dbms_xmlgen` to query tables using a pattern, which generates an XML document as a CLOB: ``` select dbms_xmlgen.getxml('select * from ' || table_name || ' where some_col like ''%Test%''') as xml_clob from user_tables where table_name like 'TABLE_%'; ``` You said you wanted a condition, so I've included...
This is kind of messy and best performed in a middle-tier, but I suppose you could basically loop over the tables and use [`EXECUTE IMMEDIATE`](http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems017.htm) to do it. Something like: ``` for t in (select table_name from all_tables where table_name like 'table_...
one query for many similar tables
[ "", "sql", "oracle", "union", "" ]
The logical error here is that the output displays like this: ``` +-----------------+-------+----------+-------+ | registration_no | color | producer | count | +-----------------+-------+----------+-------+ | X23-234 | green | VW | 2 | | BC-343 | red | BMW | 2 | | TW-435 ...
order by count(\*) and then limit at the first row ``` SELECT registration_no, color, producer, COUNT(*) as count FROM car, car_type, booking WHERE car.car_type_id = car_type.car_type_id and booking.car_id =car.car_id GROUP BY car.car_id ORDER BY COUNT(*) ASC LIMIT 1; ``` this works if you only want just one row. ...
you can use this query in order to select the min count: ``` select min(count) from (select COUNT(*) as count FROM car, car_type, booking WHERE car.car_type_id = car_type.car_type_id and booking.car_id = car.car_id GROUP BY car.car_id); ```
MySQL: How to display only the minimum count without the use of limit?
[ "", "mysql", "sql", "count", "output", "min", "" ]
Is it possible to run all opened scripts in SSMS. Would be any shortcut for that? Just like `F5` runs only active one script. The reason I want it is a temporary change in all scripts with `CTRL+H`. I want to run all scripts without saving changes. That is why I do not want the idea of running all scripts in a director...
You can do this : `Ctrl` + (`E` `F6` `E` `F6` `E` ...)
You can kind of do this with SQLCMD mode. 1. Create a new Query. Make sure Query -- > SQLCMD Mode is enabled. 2. In the new query, enter `:r` followed by the path to the scripts. So: `:r C:\Path\To\Script\1.sql` `:r C:\Path\To\Script\2.sql` `:r C:\Path\To\Script\3.sql` `:r C:\Path\To\Script\4.sql` `:r C:\Path...
How to run all scripts in SSMS
[ "", "sql", "sql-server", "ssms", "" ]
I want to sum the weight of rows with the same id1 and then computes the ratio for each of that row (sort of like a probability) in a column prob. Table data: ``` id1 weight id2 1 0.1 3 1 0.2 4 1 0.3 5 1 0.8 6 2 0.5 7 2 0.6 8 2 0.7 9 ``` Output should be: ...
This can easily be solved with a window function which is typically faster than any solution with a sub-query or derived table: ``` select id1, weight, id2, weight / sum(weight) over (partition by id1) as prob from items order by id1, id2; ``` SQLFiddle example: <http://sqlfiddle.com/#!15/6445...
Try this ``` SELECT t.*,t.wieght/t1.Weight AS Prob FROM TABLE_NAME t INNER JOIN ( SELECT id1,SUM(weight) AS Weight FROM TABLE_NAME GROUP BY id1 )t1 ON t.id = t1.id ```
postgres alter table and insert row probabilities
[ "", "sql", "database", "postgresql", "calculated-columns", "" ]
I have this code which is currently returning 0 regardless if the string contains the substring or not. It should return 1 if the substring is found. ``` CREATE FUNCTION dbo.checkLetters (@MESSAGE VARCHAR) RETURNS INTEGER WITH RETURNS NULL ON NULL INPUT AS BEGIN DECLARE @value INTEGER; IF @MESSAGE LIKE '%findM...
use `(@MESSAGE VARCHAR(max))` as a input parameter. or instead of max specify the length, currently in your function it is only 1. That is the issue.
Modify your function as given below: ``` ALTER FUNCTION dbo.checkLetters (@MESSAGE VARCHAR(max)) RETURNS INTEGER WITH RETURNS NULL ON NULL INPUT AS BEGIN DECLARE @value INTEGER; DECLARE @ExpressionToFind VARCHAR(50) SET @ExpressionToFind = 'findme' IF @MESSAGE LIKE '%' + @ExpressionToFind + '%' SET @...
User Defined Function to determine whether string contains a substring
[ "", "sql", "sql-server", "" ]
How to get the sum from both the tables? 1. `res_transactions` 2. `TRANS_ADD` Queries: ``` select tranid, Qty, Price from res_transactions where order_no = '16104' and tranid = '506060' order by tranid asc select FTRN, Qty, Price from TRANS_ADD where FTRN = '506060' ``` ...
``` select sum(result) as sumresult from (select Qty * Price as result from res_transactions where order_no='16104' and tranid='506060' union all select Qty * Price as result from TRANS_ADD where FTRN='506060' )t ```
To get sum from res\_transactions: ``` SELECT TRANID AS ID, SUM(QTY*PRICE) AS TOTAL FROM RES_TRANSACTIONS WHERE ORDER_NO='16104' AND TRANID='506060' GROUP BY TRANID ``` Same for TRANS\_ADD: ``` SELECT FTRN AS ID, SUM(QTY*PRICE) AS TOTAL FROM TRANS_ADD WHERE FTRN='506060' GROUP BY FTRN ``` So if you want to find su...
How to get the sum of from this table?
[ "", "sql", "sql-server", "" ]
In EXCEL/VBA I can program my way out of a thunderstorm, but in SQL I am still a novice. So apologies, after much Googling I can only get partway to a solution which I presume ultimately will be pretty simple, just not wrapping my head around it. I need to create an INSERT script to add multiple rows in a 3-column tab...
You can use `into` to insert into the target table. To generate itemid's you will have to use `union all` with your values and `cross join` on the `divisions` table. ``` select d.storeid, x.itemid, 27 as somecolumn into targettablename from Directory.Divisions d cross join (select 123 as itemid union all select 456...
Firstly you need your array of item ids in a table of some sort. Either a permanent table, table variable or temporary table. For example using a temporary table, which you prefix with a hash symbol: ``` CREATE TABLE #ItemIds (item_id int) INSERT INTO #ItemIds VALUES (1) INSERT INTO #ItemIds VALUES (2) ... INSERT INTO...
INSERT multiple rows with SELECT and an array
[ "", "sql", "arrays", "sql-server", "bulkinsert", "" ]
I'm trying the following and as expected, I get two columns with the values. ``` declare @aa varchar(10) = 'bb' declare @bb varchar(10) = 'aa' select @aa, @bb ``` Then I tried the following and I can't explain the result. I see nothing, except the command executed successfully. ``` declare @aa varchar(10) = 'bb' dec...
To do comparison in a query: ``` select case when @aa = @bb then 'MATCH' else 'NOT MATCH' end ``` With what you were doing: ``` select @aa, @bb ``` The above selects both values stored in the variables as separate "columns". ``` select @aa = @bb ``` The above sets the variable `@aa` equal...
`select @aa = @bb` is assignment like `SET @aa = @bb` Compare using [IIF](https://msdn.microsoft.com/en-us/library/hh213574.aspx) `SELECT IIF(@aa = @bb, 'Same', 'Different')` **[SqlFiddleDemo](http://sqlfiddle.com/#!6/9eecb7/1918/0)** Inequality `SELECT IIF(@aa <> @bb, 'Different', 'Same')` In General `SELECT IIF((...
What does the comparison mean and why isn't it showing true nor false?
[ "", "sql", "sql-server", "" ]
I have a example query(fully modified) as below: ``` with projects as ( select * from projectdetails ) select * from projects ``` when I run the above query, it is running fine. But when i put one more select query..it is throwing error. ``` select * from ( with projects as ( select * from projectdetails ) ...
The query which you are trying to execute is called `Common Table Expression` and the the syntax which you are using is not the proper way of using it ie, you cannot use the `WITH` clause inside the `select` statement. ``` with projects as ( select * from projectdetails ) select * from projects ``` The above query ...
SQL Server and Oracle have different syntax requirements for common table expressions. In Oracle, these can come before any `SELECT`. In SQL Server, they need to come at the beginning of the query. Hence, you cannot have a subquery with `WITH` in it. Usually, you can just move the `WITH` statement before the first `S...
Query on WITH Clause in SQL Server
[ "", "sql", "sql-server", "oracle", "common-table-expression", "" ]
I usually code a join query as follows: ``` Select 'field' from 'table' join 'references' on 'table'.'id' = 'references'.'reference' ``` Now suddenly I wondered, does the order in which you do `on 'table'.'id' = 'references'.'reference'` have an impact on execution speed or not? I mainly use sqlserver, mysql and sql...
There's no difference in execution if you write the SQL-Statement ``` Select 'field' from 'table' join 'references' on 'table'.'id' = 'references'.'reference' ``` or ``` Select 'field' from 'table' join 'references' on 'references'.'reference' = 'table'.'id' ``` You also could write it as a cross join (only p...
There is no difference in that order. Join condition `ON (..here..)` is just а logical expression, nothing else.
Is the order of comparisant important in a join query?
[ "", "mysql", "sql", "sql-server", "sqlite", "" ]
in sql server i have one table (userMessageTbl) with this struct ``` User UserMessage UserMessageDate AdminMessage AdminMessageDate ``` now i want Select `UserMessage` and `AdminMessageDate` from this table by date `DES`. For exmple ``` User UserMessage UserMessageDate AdminMessage AdminMessageDate test hi ...
``` ; WITH MD AS ( SELECT UserMessage AS [Message], UserMessageDate AS [Date] FROM userMessageTbl UNION ALL SELECT AdminMessage AS [Message], AdminMessageDate AS [Date] FROM userMessageTbl ) SELECT [Message], [Date] FROM MD ORDER BY [Date] DESC ```
Do a `UNION ALL` in a derived table. Then order the result. ``` select msg from ( select UserMessage as msg, UserMessageDate as msgdate from table union all select AdminMessage as msg, AdminMessageDate as msgdate from table ) as dt order by msgdate ```
select message from two column date
[ "", "sql", "sql-server", "stored-procedures", "" ]
I have a robot script which inserts some sql statements from a sql file; some of these statements contain utf8 characters. If I insert this file manually into database using navicat tool, everything's fine. But when I try to execute this file using database library of robot framework, utf8 characters go crazy! This is...
As @Yu Zhang suggested, I read discussion in this [link](https://community.oracle.com/thread/502949) and I found out that I should set an environment variable `NLS_LANG` in order to have a `UTF-8` connection to the database. So I've added below line in my test setup: ``` os.environ["NLS_LANG"] = "AMERICAN_AMERICA.AL32...
There can be several problems in here... The first problem might be that you don't save the test files using UTF-8 encoding. Robot framework expects plain text test files to be saved using UTF-8 encoding, yet most text editors will not save by default using UTF-8. Verify that your editor saves that way - for example...
how to insert utf8 characters into oracle database using robotframework database library
[ "", "sql", "database", "utf-8", "robotframework", "" ]
I am stuck with a query that is using recursive and wondering if you guys can help me out. I have this query below and it is based on the ShipQuantity, then it lists the number of records. For example, mfgPN "ABC123" has a ShipQuantity of 4, it will list 4 records with a number 1,2,3, 4. ``` WITH feedInfo AS ( SE...
Looks like you're trying to match up the LinkID and Number from the recursive query to the LinkID and a Row Number in the `EXT_DistributorFeedDetail` table ``` WITH feedInfo AS ( SELECT df1.RecID, MfgPN, LinkID, ShipQuantity, 1 AS Number FROM EXT_DistributorFeed df1 WHERE 1 = 1 AND df1.mfgPN IN ('ABC1...
It looks like you want to join the SerialNo in descending order for the number. You can do this by changing the last part of the query to this: ``` with feedinfo as ( .... ) select f.*, e.* from feedinfo f left join ( select *, rn = row_number() over (partition by linkid order by serialno desc) from ext_d...
Recursive Query and INNER JOIN
[ "", "sql", "sql-server-2008", "" ]
I have a SQL Server table with call records and I'd like to get the number of calls in total and the total calls answered. Here is what the table looks like: ``` Extension | Status ----------------------- 300 Answered 200 Not Answered .... ... ``` What's the most efficient way to write a que...
By using a `case` statement inside the `count` aggregate function for the total answered calls, you can keep your query very simple with a `group by`. ``` select extension, count(*) as total, count(case when status = 'answered' then 'X' end) as totalAnswered from calls group by extension ``` I am ass...
``` SELECT Extention, COUNT(*) as total, SUM(answered) OVER (PARTITION BY Extention) as answered FROM ( SELECT Extention, CASE WHEN Status = 'answered' THEN 1 ELSE 0 END as answered ) T ```
Sql Server Join to Sub Query
[ "", "sql", "sql-server", "" ]
I have table with following data . ``` 1 AAAAA01 AAAAA01 AAAAA01 B21 AAAAAA1 B3 AB100 ``` and I want to sort data in following order ``` AAAAAA1 AAAAA01 AAAAA01 AAAAA01 AB100 B21 B3 1 ``` I wrote a statement but not give me correct result. ``` Select * from dbo.Section order by ...
Please try: ``` Select * from dbo.Section order by REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE (REPLACE ([Section], '0', 'ZZ0'), '1', 'ZZ1'), '2', 'ZZ2'), '3', 'ZZ3'), '4', 'ZZ4'), '5', 'ZZ5'), '6', 'ZZ6'), ...
This is another way. Assuming your number strings are greater than -100000000. ``` SELECT YourString FROM YourTable ORDER BY CASE WHEN YourString LIKE '[0-9]%' THEN CONVERT(int, YourString) ELSE -100000000 END, YourString ```
Sort data in varchar alphabet order
[ "", "sql", "sql-server-2008", "sql-server-2008-r2", "" ]
I'm after a CTE which I want to return two columns, one with the total number of 1's and one with the total number of 0's. Currently I can get it to return one column with the total number of 1's using: ``` WITH getOnesAndZerosCTE AS ( SELECT COUNT([message]) AS TotalNo1s FROM dbo.post WHERE dbo.checklett...
Using conditional aggregation: ``` WITH getOnesAndZerosCTE AS( SELECT TotalNo1s = SUM(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 ELSE 0 END), TotalNo0s = SUM(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 ELSE 0 END) FROM post ) SELECT * FROM getOnesAndZerosCTE; ```
For using COUNT() directly just be aware that it counts any NON-NULL values. You can omit the ELSE condition which implicitly returns NULL if not stated ``` SELECT COUNT(CASE WHEN dbo.checkletters([message]) = 1 THEN 1 END) TotalNo1s , COUNT(CASE WHEN dbo.checkletters([message]) = 0 THEN 1 END) TotalNo0s FROM p...
Count rows for two columns using two different clauses
[ "", "sql", "sql-server", "common-table-expression", "" ]
I have an events table that has a start and end date columns (events do not overlap), sample data ``` if object_id('tempdb..#SourceTable') is not null begin drop table #SourceTable end create table #SourceTable ( Id int identity(1,1) not null, WindowRange varchar(15) not null, StartDatetime datetime n...
``` DECLARE @WindowRange varchar(15), @StartDatetime datetime, @EndDatetime datetime, @StartDate date, @EndDate date, @NextStartDatetime datetime, @NextEndDatetime datetime DECLARE yourCursor CURSOR FORWARD_ONLY READ_ONLY FOR SELECT StartDatetime, EndDatetime...
``` ;with myCTE as ( select row_number() over (order by EndDatetime desc) as SeqNo, StartDatetime, EndDatetime from #SourceTable ) select ROW_NUMBER() over (order by T1Start DESC), * from ( select t1.StartDatetime as [T1Start], t1.EndDatetime as [T1End] from myCTE t1 UNI...
Filling gaps with date ranges in SQL
[ "", "sql", "sql-server", "sql-server-2008", "gaps-and-islands", "" ]
Really hard to even explain this question. I have data sets in SQL Server 2008 that contain rows with a start and end date which can overlap dates by rows. I am trying to figure out a simple query without the use of a cursor to group these into distinct possible ranges. I have a query that will handle some situations ...
How about: ``` >WITH dates (dt) as >( >SELECT start [dt] from product >UNION >SELECT [end] [dt] from product) > >SELECT d1.dt [start_on], >> (select min(d2.dt) from dates d2 where d2.dt > d1.dt) [end_on] >FROM dates d1 >WHERE not (select min(d2.dt) from dates d2 where d2.dt > d1.dt) is NULL >ORDER BY [dt] ```
I think this is what you need. ``` DECLARE @t TABLE (PRODUCT CHAR(1) ,START DATE ,[END] DATE ) INSERT INTO @t VALUES ('A','09/02/2015','10/01/2015') ,('B','09/02/2015','08/31/2016') ,('C','09/02/2015','12/31/2016') ,('D','09/02/2015','10/21/2017') ...
SQL to group by date range of various rows
[ "", "sql", "sql-server", "t-sql", "" ]
I don't know how to format?!, but I believe it's easy to understand. I have the following table, lets call it "sales" ``` |Item| |Price| |PriceDate| ItemA 801.36 09/23/2011 ItemA 800.64 09/23/2011 ItemA 803.55 09/22/2011 ItemB 4701.36 ...
One way to go about it is to calculate the difference between the row's data and the given date by using [`datediff`](https://msdn.microsoft.com/en-us/library/ms189794.aspx), assign a [`rank`](https://msdn.microsoft.com/en-us/library/ms176102.aspx) to each row accordingly and filter by it. Here I'm using `?` as a plac...
``` DECLARE @theTable TABLE (Item VARCHAR(10), price DECIMAL(10,2), priceDate DATE) INSERT @theTable ( Item, price, priceDate ) VALUES ('ItemA',801.36,'2011-09-23'), ('ItemA',800.64,'2011-09-23'), ('ItemA',803.55,'2011-09-22'), ('ItemB',4701.36,'2011-09-22'), ('ItemB',1101.36,'2011-09-22'), ('ItemB',4801.36,'2011-09-...
How to get distinct closest date in SQL Server?
[ "", "sql", "sql-server", "select", "sql-server-2012", "" ]
The project is using Postgres 9.3 I have tables (that I have simplified) as follows: ``` t_person (30 million records) - id - first_name - last_name - gender t_city (70,000 records) - id - name - country_id t_country (20 records) - id - name t_last_city_visited (over 200 million records) - person_id - city_id - co...
Hint: What you want to do here is to find the females for whom there EXISTS a visit to the UK, but where NOT EXISTS a visit to the US. Something like: ``` select ... from t_person where ... and exists (select null from t_last_city_visited join t_country on (...) ...
Could you please run analyze and execute this query? ``` -- females who visited UK with uk_person as ( select distinct person_id from t_last_city_visited t inner join t_person p on t.person_id = p.id and 'F' = p.gender where country_id = (select id from t_country where name = 'UK') ), -- females who visited U...
PostgreSQL Select Join Not in List
[ "", "sql", "postgresql", "join", "" ]
There are tables `Employees` ``` CREATE TABLE Employees ( id int NOT NULL IDENTITY(1, 1) PRIMARY KEY, name nvarchar(100) NOT NULL, depID int NOT NULL, salary money NOT NULL, FOREIGN KEY (depID) REFERENCES Departments(id) ); ``` and `Payments` ``` CREATE TABLE Payments ( id int NOT NULL IDENT...
People are way over-complicating things. I'm pretty sure this will get you what you want: ``` SELECT TOP 3 employees.id, Name, Sum([sum]) AS [TotalPayments] FROM Employees inner join Payments on employees.id = payments.userid WHERE createdDate BETWEEN '2013-09-01' and '2015-09-01' Group By employees.id, ...
This is one way to do it using `cte`s. [Demo](http://www.sqlfiddle.com/#!3/71773e/24) ``` with pymt as ( SELECT userid, sum(sum) as sumtotal FROM Payments WHERE createdDate BETWEEN '2013-09-01' AND '2015-09-01' group by userid ) , ename as ( select e.name, pymt.sumtotal, row_number() over(order by pymt.sumtotal des...
SELECT Employees with the top three salaries for the last two years
[ "", "sql", "sql-server", "" ]
I created 3 mysql tables: table 'city': contains cities ``` i.e | name | +========+ | Athens | +--------+ | Rome | +--------+ | Paris | +--------+ ``` table 'category': contains categories ``` i.e | name | +============+ | category_1 | +----...
Try this ``` select c.name, sum(case when s.category_name='category_1' then 1 else 0 end) as categoty_1, sum(case when s.category_name='category_2' then 1 else 0 end) as categoty_2 from city as c left join shops as s on c.name=s,city_name group by c.name ```
Look into this [SQL select data from multiple tables](https://stackoverflow.com/questions/32248980/sql-select-data-from-multiple-) tables/32249225?noredirect=1#comment52417831\_32249225
Special connection between 3 tables
[ "", "mysql", "sql", "" ]
I work on a software that allows users to manage estates they want to sell. I have a database like this (simple exemple) : ``` estates ------------- id price photos ------------- photoName estateId documents ------------- docName estateId ``` I'd like to get, in one request, all the informations of an estate (let...
It is a bit more complicated and it uses variables, but the answer is "yes": ``` select e.*, max(photoname) as photoname, max(docname) as docname) from estates e join ((select p.estateid, p.photoname, NULL as docname, (@rnp := @rnp + 1) as seqnum from photos p cross join (select @rnp := ...
You can even reduce this to one row per estate by simple aggregation. ``` SELECT e.*, group_concat(distinct p.photoname) as photonames, group_concat(distinct d.docname) as docnames FROM estates e LEFT OUTER JOIN photos p ON p.estateId = e.id LEFT OUTER JOIN documents d ON d.estateId = e.id WHERE e.id = 1 GROUP...
LEFT JOIN : is there a way to reduce the line numbers?
[ "", "mysql", "sql", "left-join", "" ]
EDIT: Thanks guys. It was truly just a formatting error of the single-quotation mark from the source code I copied. Thanks a lot! **Codes:** ``` USE Library; INSERT INTO myLibrary VALUES ( ‘SQL Bible’ ,‘Alex Kriegel’ ,‘Boris M. Trukhnov’ ,‘Wiley’ ,888 ,‘April 7,2008’ ,‘978-0470229064’ ...
In SQL, strings are defined with the `'` characters, not `‘` and `’`
Looks like you're using the wrong character to encapsulate your strings. Instead of the `‘` character, you need to use either a `'` or a `"`: ``` USE Library; INSERT INTO myLibrary VALUES ( "SQL Bible" ,"Alex Kriegel" ,"Boris M. Trukhnov" ,"Wiley" ,888 ,"April 7,2008" ,"978-0470229064" ...
SQL - populating table
[ "", "sql", "sql-server", "" ]
When user insert Russian word like 'пример' to database,database saves it like '??????'. If they insert with 'N' letter or I select it with 'N' letter, ie; exec Table\_Name N'иытание' there is no problem. But I don't want to use 'N' in every query, so is there any solution for this? I will use stored procedure by the w...
You have to use column's datatype `NVARCHAR` to insert unicode letters, also you have to use `N'value'` when inserting. You can test it in following: ``` CREATE TABLE #test ( varcharCol varchar(40), nvarcharCol nvarchar(40) ) INSERT INTO #test VALUES (N'иытание', N'иытание') SELECT * FROM #test ``` **OUTPUT...
it would very difficult to put in comment i would recommend this link [Info](https://dba.stackexchange.com/questions/12475/n-prefix-before-string-in-transact-sql-query) ``` declare @test TABLE ( Col1 varchar(40), Col2 varchar(40), Col3 nvarchar(40), Col4 nvarchar(40) ) INSERT INTO @test VALUES ('иытан...
Select cyrillic character in SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have the following SQL Server tables. ``` CREATE TABLE workingSchedule ( [workingDate] DATETIME NULL, [openTime] TIME (7) NULL, [closeTime] TIME (7) NULL ); INSERT INTO workingSchedule (workingDate, openTime, closeTime) VALUES ('10/1/2015','9:00','17:00'), ('10/2/2015','9:00','17:0...
In situations like this, I use ROW\_NUMBER (<https://msdn.microsoft.com/en-us/library/ms186734.aspx>) to help join splits inside a single day. I used a UNION, but I think you could use the same join logic I have, but get away with a SELECT statement. ``` SELECT workingDate as [date], openTime as [Start], COALESCE(bre...
``` You can try this DECLARE @Tab TABLE ( [Date] [datetime], [Time] [time], [Row] int ) DECLARE @Tab2 TABLE ( [Date] [datetime], [Row] int ) INSERT INTO @Tab2 SELECT DISTINCT(workingDate) , ROW_NUMBER() OVER(ORDER BY [workingDate]) FROM workingSchedule DECLARE @Count int; DECLARE @Num [int]; DECLARE @Dat [datetim...
SQL Server split time interval to multiple rows
[ "", "sql", "sql-server", "time", "split", "" ]
I have table with the following column: ``` [name_of_pos] varchar, [date_from] datetime, [date_to] datetime ``` Below is my sample data: ``` name_of_pos date_from date_to ---------------------------------------------------------------- Asystent 2015-08-26 08:57:49.000 2015-09-04 08:57:49.000 B...
Here's a solution using a `cte` to iterate over the rows (after they have been ordered) and check for consecutive days before grouping: ``` -- dummy table CREATE TABLE #TableA ( [name_of_pos] VARCHAR(11) , [date_from] DATETIME , [date_to] DATETIME ); -- insert dummy data INSERT INTO #TableA...
This is a **gaps and islands** issue. This is the *tuned [official](http://social.technet.microsoft.com/wiki/contents/articles/18399.t-sql-gaps-and-islands-problem.aspx)* way to accomplish it and this would be checked as solution: ``` ;with cte as ( SELECT *, dateadd( day, - (ROW_NUMBER() OV...
Grouping by consecutive dates in SQL Server
[ "", "sql", "sql-server", "t-sql", "gaps-and-islands", "" ]
I need to compare two tables and get the pn's that are not done or non existent. I cant seem to find an answer online anywhere for exactly what I need. Here are the tables and the example output that I need. Thank you so much to whom ever can help me out. Table1: ``` +------------+----------+------------+----+-------...
Clarification: One job can have multiple `pcmk` and comparision should be done for each `pcmk` ``` SELECT t1.cert,t2.job,t2.pcmk,t2.pn FROM table1 t1 join table2 t2 on (t1.pcmk=t2.pcmk) WHERE (t1.pn=t2.pn and (t1.stat="" or t1.stat is null)) or t2.pn NOT IN( SELECT pn FROM table1 WHERE table1.pcmk=t2.pcmk) gr...
If I rephrase your condition, you want the rows from `table2` that don't have a corresponding row in `table` with a non-`null` status. This sounds like an `exists` condition: ``` SELECT * FROM table2 WHERE NOT EXISTS (SELECT * FROM table1 WHERE table1.pn = table2.pn AND stat...
How to select records that are not in another table?
[ "", "mysql", "sql", "select", "" ]
I have this query: ``` SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question, t_ticket.code, t_ticket.priority, t_actionTicket.addedDateAction, t_actionTicket.title FROM t_actionTicket INNER JOIN t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID INNER JOIN ...
Problem in your query is ``` FROM t_actionTicket AS t_actionTicket_1 WHERE t_actionTicket.userID_FK <> @userid -- here ``` You cannot use `t_actionTicket` alias name inside `inner join` select query. You need to use `t_actionTicket_1`. It is possible only in `sub-query` Try this better way of doing...
You can write this logic using `row_number()` instead of additional nested queries: ``` SELECT t.ticketID, t.addedDate, t.question, t.code, t.priority, ta.addedDateAction, ta.title AS Expr1 FROM t_Ticket t INNER JOIN (SELECT ta.*, ROW_NUMBER() OVER (PARTITION BY ta.ticketID_FK ORDER BY ta.a...
Join two tables returning only one row from the second table
[ "", "sql", "sql-server", "join", "" ]
I have a table with data every hour: [![enter image description here](https://i.stack.imgur.com/Qb7qm.png)](https://i.stack.imgur.com/Qb7qm.png) and a table with data every 30 minutes: [![enter image description here](https://i.stack.imgur.com/9MOEZ.png)](https://i.stack.imgur.com/9MOEZ.png) I would like to join th...
``` SELECT * FROM HourTable t INNER JOIN HalfHourTable ht ON CAST(t.repDate AS Date) = CAST(ht.repDate AS Date) AND DATEPART(HOUR, t.repDate) = DATEPART(HOUR, ht.repDate) ``` ## Edit Your query should be ``` SELECT n.repDate , n.TA , a.batVolt FROM [DAP].[dbo].[ARRMet] AS n FULL JOIN [DAP].[dbo].[a...
I would do this slightly differently than M.Ali. This uses fewer functions and seems a bit simpler to me. ``` SELECT * FROM HourTable t INNER JOIN HalfHourTable ht on t.repDate = dateadd(hour, datediff(hour, 0, ht.repDate), 0) ```
Join data from hourly and 30 minute tables
[ "", "sql", "sql-server", "database", "" ]
Sql keeps throwing me a syntax error and I can't seem to figure out whats wrong. ``` ALTER TABLE `productList` ALTER COLUMN `ASIN` VARCHAR(32); ``` The error is the normal sql syntax error > ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for t...
Try this: ``` ALTER TABLE `productList` MODIFY COLUMN `ASIN` VARCHAR(32); ``` The syntax to [change the column name](http://dev.mysql.com/doc/refman/5.1/en/alter-table.html) is > ALTER TABLE tablename MODIFY COLUMN new-column-definition
You need to use MODIFY COLUMN instead of ALTER COLUMN if you want to change the column definition. <https://dev.mysql.com/doc/refman/5.1/en/alter-table.html>
Mysql syntax error in ALTER TABLE
[ "", "mysql", "sql", "" ]
I have a single SQL table that contains multiple entries for each customerID (some customerID's only have one entry which I want to keep). I need to remove all but the most recent entry per customerID, using the invoiceDate field as my marker. So I need to go from this: ``` +------------+-------------+-----------+ | ...
1. Write a query to select all the rows you want to delete: ``` SELECT * FROM t WHERE invoiceDate NOT IN ( SELECT MAX(invoiceDate) -- "FROM t AS t2" isn't supported by MySQL, see http://stackoverflow.com/a/14302701/227576 FROM (SELECT * FROM t) AS t2 WHERE t2.customerId = t.customerId GROUP BY t2.c...
Try out this one ``` with todelete as ( select CustomerId, InvoiceId, InvoiceDate, Row_Number() over (partition by CustomerId order by InvoiceDate desc) as Count from DeleteDuplicate ) delete from todelete where count > 1 ```
Deleting all but the most recent entry from single SQL table
[ "", "mysql", "sql", "" ]
I have a query like this: ``` select F_Exhibition_Name, F_dtFrom as startdate, F_dtTo as enddate from T_Exhibition ``` My output looks like this: ``` Exhibiton startdate enddate A 2015-05-04 2015-05-21 B 2015-06-10 2015-06-20 C 2015-07-10 2015-09-11 ``` I want to get exhibition name...
Below query will show events till 7 days in addition to enddate after checking current date using `Getdate()`: ``` select F_Exhibition_Name from T_Exhibition where Getdate() < = DATEADD(day,7,enddate ) ``` For example : **Case 1:** ``` Event end date : 7 Current date : 1 Show event till : 7 + 7 = 14 So it wil...
Please use below query ``` select F_Exhibition_Name,F_dtFrom as startdate,CASE WHEN CONVERT(date,F_dtTo)=CONVERT(DATE,GETDATE()) THEN DATEADD(DAY,7,F_dtTo) else F_dtTo end as enddate from T_Exhibition ```
Get data comparing endate with current date
[ "", "sql", "sql-server", "" ]
Using Postgres 8.4. I have a table of user activity that looks like kinda like this: ``` userid | timestamp | action --------------------------------------------- 0001 | 11/11/2015 9:00:02 | X 0001 | 11/11/2015 9:00:22 | Y 0002 | 11/11/2015 9:01:02 | Z 0002 | 11/11/2015 9:0...
The simplest solution will be probably to use `LEFT JOIN` to join the table with itself: ``` WITH actions(action) AS( VALUES ('X'),('Y'),('Z')) SELECT d.action ,Count(DISTINCT a.userid) FROM table1 as a LEFT JOIN table1 AS b ON a.userid = b.userid AND b.action = 'Y' AND a.timestamp < b.timestamp LEFT ...
Here is one rather brute force approach. Use `listagg()` to create the sequences, and then look for them: ``` select p.pattern, count(t.actions) from (select 'X' as pattern union all select 'XY' union all SELECT 'XYZ' ) p left join (select userid, listagg(action, '') within group (order by timestamp) actions...
SQL query time series data to find trend counts for user activity
[ "", "sql", "amazon-redshift", "" ]
I am getting error while executing below query in sql server 2012: ``` DECLARE @Id NVARCHAR(max) = 2147483648 DECLARE @Result BIGINT = 0 IF ( @Id = 0 OR @Id = '' ) BEGIN SET @Result = NULL END ELSE BEGIN SET @Result = convert(bigint,@id) END ``` Output: > Msg 248, Level 16, State 1, Line 3 T...
Converting `0` to `bigint` will work because by default 0 will be treated as `INT` ``` DECLARE @Id NVARCHAR(max) = 2147483648 DECLARE @Result BIGINT = 0 IF ( @Id = cast(0 as bigint) -- or = '0' OR @Id = '' ) BEGIN SET @Result = NULL END ELSE BEGIN SET @Result = CONVERT(BIGINT, @id) END ```
You have to use `''` when setting `@id = '0'` in following: ``` DECLARE @Id NVARCHAR(max) = 2147483648 DECLARE @Result BIGINT = 0 IF ( @Id = '0' OR @Id = '' ) BEGIN SET @Result = NULL END ELSE BEGIN SET @Result = convert(bigint,@id) END ```
Parsing/Conversion issue in sql server 2012?
[ "", "sql", "sql-server", "t-sql", "" ]
Here `f` refer to `air_flight` and `fp` refer to `air_flight_details`. As I'm beginner for sql I understand the concept except.... why they are mentioning `fp` after subquery and whyy not as `air_flight_details fp`? ``` SELECT f.flight_id, f.from_location, f.to_location, fp.Month_Name, fp.Average_Price FROM air_flig...
The subquery in your example has an *alias* called `fp`, which allows the results from that subquery to be referenced in the outer query. For example, the query selects `fp.Average_Price`, which is a column contained in the subquery. Also, the `WHERE` clause contains the condition `f.flight_id = fp.flight_id`, which al...
Just like the first `FROM` statement names the table `f`, the entire subquery is given the alias `fp`. The difference is that in the first `FROM` statement, the entire table `air_flight` is given the name `f`, while the subquery essentially creates an entire table to which `fp` refers.
Subqueries in SQL from airline management scheme
[ "", "mysql", "sql", "subquery", "" ]