Search Results

Search found 763 results on 31 pages for 'union all'.

Page 1/31 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Whether to use UNION or OR in SQL Server Queries

    - by Dinesh Asanka
    Recently I came across with an article on DB2 about using Union instead of OR. So I thought of carrying out a research on SQL Server on what scenarios UNION is optimal in and which scenarios OR would be best. I will analyze this with a few scenarios using samples taken  from the AdventureWorks database Sales.SalesOrderDetail table. Scenario 1: Selecting all columns So we are going to select all columns and you have a non-clustered index on the ProductID column. --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR ProductID =709 OR ProductID =998 OR ProductID =875 OR ProductID =976 OR ProductID =874 --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 709 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 998 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 875 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 976 UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 874 So query 1 is using OR and the later is using UNION. Let us analyze the execution plans for these queries. Query 1 Query 2 As expected Query 1 will use Clustered Index Scan but Query 2, uses all sorts of things. In this case, since it is using multiple CPUs you might have CX_PACKET waits as well. Let’s look at the profiler results for these two queries: CPU Reads Duration Row Counts OR 78 1252 389 3854 UNION 250 7495 660 3854 You can see from the above table the UNION query is not performing well as the  OR query though both are retuning same no of rows (3854).These results indicate that, for the above scenario UNION should be used. Scenario 2: Non-Clustered and Clustered Index Columns only --Query 1 : OR SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR ProductID =709 OR ProductID =998 OR ProductID =875 OR ProductID =976 OR ProductID =874 GO --Query 2 : UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 709 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 998 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 875 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 976 UNION SELECT ProductID,SalesOrderID, SalesOrderDetailID FROM Sales.SalesOrderDetail WHERE ProductID = 874 GO So this time, we will be selecting only index columns, which means these queries will avoid a data page lookup. As in the previous case we will analyze the execution plans: Query 1 Query 2 Again, Query 2 is more complex than Query 1. Let us look at the profile analysis: CPU Reads Duration Row Counts OR 0 24 208 3854 UNION 0 38 193 3854 In this analyzis, there is only slight difference between OR and UNION. Scenario 3: Selecting all columns for different fields Up to now, we were using only one column (ProductID) in the where clause.  What if we have two columns for where clauses and let us assume both are covered by non-clustered indexes? --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR CarrierTrackingNumber LIKE 'D0B8%' --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE CarrierTrackingNumber  LIKE 'D0B8%' Query 1 Query 2: As we can see, the query plan for the second query has improved. Let us see the profiler results. CPU Reads Duration Row Counts OR 47 1278 443 1228 UNION 31 1334 400 1228 So in this case too, there is little difference between OR and UNION. Scenario 4: Selecting Clustered index columns for different fields Now let us go only with clustered indexes: --Query 1 : OR SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 OR CarrierTrackingNumber LIKE 'D0B8%' --Query 2 : UNION SELECT * FROM Sales.SalesOrderDetail WHERE ProductID = 714 UNION SELECT * FROM Sales.SalesOrderDetail WHERE CarrierTrackingNumber  LIKE 'D0B8%' Query 1 Query 2 Now both execution plans are almost identical except is an additional Stream Aggregate is used in the first query. This means UNION has advantage over OR in this scenario. Let us see profiler results for these queries again. CPU Reads Duration Row Counts OR 0 319 366 1228 UNION 0 50 193 1228 Now see the differences, in this scenario UNION has somewhat of an advantage over OR. Conclusion Using UNION or OR depends on the scenario you are faced with. So you need to do your analyzing before selecting the appropriate method. Also, above the four scenarios are not all an exhaustive list of scenarios, I selected those for the broad description purposes only.

    Read the article

  • SQL SERVER – UNION ALL and ORDER BY – How to Order Table Separately While Using UNION ALL

    - by pinaldave
    I often see developers trying following syntax while using ORDER BY. SELECT Columns FROM TABLE1 ORDER BY Columns UNION ALL SELECT Columns FROM TABLE2 ORDER BY Columns However the above query will return following error. Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword ‘ORDER’. It is not possible to use two different ORDER BY in the UNION statement. UNION returns single resultsetand as per the Logical Query Processing Phases. However, if your requirement is such that you want your top and bottom query of the UNION resultset independently sorted but in the same resultset you can add an additional static column and order by that column. Let us re-create the same scenario. First create two tables and populated with sample data. USE tempdb GO -- Create table CREATE TABLE t1 (ID INT, Col1 VARCHAR(100)); CREATE TABLE t2 (ID INT, Col1 VARCHAR(100)); GO -- Sample Data Build INSERT INTO t1 (ID, Col1) SELECT 1, 'Col1-t1' UNION ALL SELECT 2, 'Col2-t1' UNION ALL SELECT 3, 'Col3-t1'; INSERT INTO t2 (ID, Col1) SELECT 3, 'Col1-t2' UNION ALL SELECT 2, 'Col2-t2' UNION ALL SELECT 1, 'Col3-t2'; GO If we SELECT the data from both the table using UNION ALL . -- SELECT without ORDER BY SELECT ID, Col1 FROM t1 UNION ALL SELECT ID, Col1 FROM t2 GO We will get the data in following order. However, our requirement is to get data in following order. If we need data ordered by Column1 we can ORDER the resultset ordered by Column1. -- SELECT with ORDER BY SELECT ID, Col1 FROM t1 UNION ALL SELECT ID, Col1 FROM t2 ORDER BY ID GO Now to get the data in independently sorted in UNION ALL let us add additional column OrderKey and use ORDER BY  on that column. I think the description does not do proper justice let us see the example here. -- SELECT with ORDER BY - with ORDER KEY SELECT ID, Col1, 'id1' OrderKey FROM t1 UNION ALL SELECT ID, Col1, 'id2' OrderKey FROM t2 ORDER BY OrderKey, ID GO The above query will give the desired result. Now do not forget to clean up the database by running the following script. -- Clean up DROP TABLE t1; DROP TABLE t2; GO Here is the complete script used in this example. USE tempdb GO -- Create table CREATE TABLE t1 (ID INT, Col1 VARCHAR(100)); CREATE TABLE t2 (ID INT, Col1 VARCHAR(100)); GO -- Sample Data Build INSERT INTO t1 (ID, Col1) SELECT 1, 'Col1-t1' UNION ALL SELECT 2, 'Col2-t1' UNION ALL SELECT 3, 'Col3-t1'; INSERT INTO t2 (ID, Col1) SELECT 3, 'Col1-t2' UNION ALL SELECT 2, 'Col2-t2' UNION ALL SELECT 1, 'Col3-t2'; GO -- SELECT without ORDER BY SELECT ID, Col1 FROM t1 UNION ALL SELECT ID, Col1 FROM t2 GO -- SELECT with ORDER BY SELECT ID, Col1 FROM t1 UNION ALL SELECT ID, Col1 FROM t2 ORDER BY ID GO -- SELECT with ORDER BY - with ORDER KEY SELECT ID, Col1, 'id1' OrderKey FROM t1 UNION ALL SELECT ID, Col1, 'id2' OrderKey FROM t2 ORDER BY OrderKey, ID GO -- Clean up DROP TABLE t1; DROP TABLE t2; GO I am sure there are many more ways to achieve this, what method would you use if you have to face the similar situation? Reference: Pinal Dave (http://blog.sqlauthority.com)   Filed under: Best Practices, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • SyFy Channel Original Movie Title Generator

    - by Most Valuable Yak (Rob Volk)
    Saw this linked on reddit today and couldn't resist going through all the combinations: create table #pre(name varchar(20))create table #post(name varchar(20), pre varchar(10))insert #pre select 'Dino' union all select'Alien' union all select'Shark' union all select'Raptor' union all select'Tractor' union all select'Arachno' union all select'Cyber' union all select'Robo' union all select'Choco' union all select'Chupa' union all select'Grizzly' union all select'Mega' union all select'Were' union all select'Sabre' union all select'Man' insert #post select 'dactyl','a' union all select'pus','to' union all select'conda','a' union all select'droid',null union all select'dile','o' union all select'bear',null union all select'vampire',null union all select'squito',null union all select'saurus','a' union all select'wolf',null union all select'ghost',null union all select'viper',null union all select'cabra','a' union all select'yeti',null union all select'shark',null select a.name +case when right(a.name,1) not like '[aeiouy]' and b.pre is not null then b.pre else '' end +b.namefrom #pre a cross join #post bwhere a.name<>b.name -- optional, to eliminate the "SharkShark" optionorder by 1  Which one is your favorite?  I like most of the -squito versions, especially Chupasquito and Grizzlysquito.

    Read the article

  • Referencing a union inside a structure using union tag gives incorrect address

    - by AlanKley
    I had a need to declare a union inside a structure as defined below: struct MyStruct { int m_DataType; DWORD m_DataLen; union theData { char m_Buff [_MAX_PATH]; struct MyData m_myData; } m_Data; }; Initially, I tried accessing the union data as follows (before I added the m_Data declaration): MyStruct m_myStruct; char* pBuff = m_myStruct.theData::m_Buff; This compiles but returns to pBuff a pointer to the beginning of the MyStruct structure which caused me to overwrite the m_DataType & m_DataLength members when I thought I was writing to the m_Buff buffer. I am using Visual Studio 2008. Can anyone explain this unexpected behavior? Thanks.

    Read the article

  • Union on two tables with a where clause in the one

    - by Lostdrifter
    Currently I have 2 tables, both of the tables have the same structure and are going to be used in a web application. the two tables are production and temp. The temp table contains one additional column called [signed up]. Currently I generate a single list using two columns that are found in each table (recno and name). Using these two fields I'm able to support my web application search function. Now what I need to do is support limiting the amount of items that can be used in the search on the second table. the reason for this is become once a person is "signed up" a similar record is created in the production table and will have its own recno. doing: Select recno, name from production UNION ALL Select recno, name from temp ...will show me everyone. I have tried: Select recno, name from production UNION ALL Select recno, name from temp WHERE signup <> 'Y' But this returns nothing? Can anyone help?

    Read the article

  • Play Framework: Error getting sequence nextval using H2 in-memory database

    - by alexhanschke
    As the title suggests, I get an error running Play 2.0.1 Tests using a FakeApplication w/ H2 in memory. I set up a basic unit test: public class ModelTest { @Test public void checkThatIndustriesExist() { running(fakeApplication(inMemoryDatabase()), new Runnable() { public void run() { Industry industry = new Industry(); industry.name = "Some name"; industry.shortname = "some-name"; industry.save(); assertThat(Industry.find.all()).hasSize(1); } }); } Which yields the following exception: [info] test.ModelTest [error] Test test.ModelTest.checkThatIndustriesExist failed: Error getting sequence nextval [error] at com.avaje.ebean.config.dbplatform.SequenceIdGenerator.getMoreIds(SequenceIdGenerator.java:213) [error] at com.avaje.ebean.config.dbplatform.SequenceIdGenerator.loadMoreIds(SequenceIdGenerator.java:163) [error] at com.avaje.ebean.config.dbplatform.SequenceIdGenerator.nextId(SequenceIdGenerator.java:118) [error] at com.avaje.ebeaninternal.server.deploy.BeanDescriptor.nextId(BeanDescriptor.java:1218) [error] at com.avaje.ebeaninternal.server.persist.DefaultPersister.setIdGenValue(DefaultPersister.java:1304) [error] at com.avaje.ebeaninternal.server.persist.DefaultPersister.insert(DefaultPersister.java:403) [error] at com.avaje.ebeaninternal.server.persist.DefaultPersister.saveEnhanced(DefaultPersister.java:345) [error] at com.avaje.ebeaninternal.server.persist.DefaultPersister.saveRecurse(DefaultPersister.java:315) [error] at com.avaje.ebeaninternal.server.persist.DefaultPersister.save(DefaultPersister.java:282) [error] at com.avaje.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1577) [error] at com.avaje.ebeaninternal.server.core.DefaultServer.save(DefaultServer.java:1567) [error] at com.avaje.ebean.Ebean.save(Ebean.java:538) [error] at play.db.ebean.Model.save(Model.java:76) [error] at test.ModelTest$1.run(ModelTest.java:24) [error] at play.test.Helpers.running(Helpers.java:277) [error] at test.ModelTest.checkThatIndustriesExist(ModelTest.java:21) [error] ... [error] Caused by: org.h2.jdbc.JdbcSQLException: Syntax Fehler in SQL Befehl "SELECT INDUSTRY_SEQ.NEXTVAL UNION[*] SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL "; erwartet "identifier" [error] Syntax error in SQL statement "SELECT INDUSTRY_SEQ.NEXTVAL UNION[*] SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL UNION SELECT INDUSTRY_SEQ.NEXTVAL "; expected "identifier"; SQL statement: [error] select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval union select industry_seq.nextval [42001-158] [error] at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) [error] at org.h2.message.DbException.get(DbException.java:169) [error] at org.h2.message.DbException.getSyntaxError(DbException.java:194) [error] at org.h2.command.Parser.readColumnIdentifier(Parser.java:2777) [error] at org.h2.command.Parser.readTermObjectDot(Parser.java:2336) [error] at org.h2.command.Parser.readTerm(Parser.java:2453) [error] at org.h2.command.Parser.readFactor(Parser.java:2035) [error] at org.h2.command.Parser.readSum(Parser.java:2022) [error] at org.h2.command.Parser.readConcat(Parser.java:1995) [error] at org.h2.command.Parser.readCondition(Parser.java:1860) [error] at org.h2.command.Parser.readAnd(Parser.java:1841) [error] at org.h2.command.Parser.readExpression(Parser.java:1833) [error] at org.h2.command.Parser.parseSelectSimpleSelectPart(Parser.java:1746) [error] at org.h2.command.Parser.parseSelectSimple(Parser.java:1778) [error] at org.h2.command.Parser.parseSelectSub(Parser.java:1673) [error] at org.h2.command.Parser.parseSelectUnion(Parser.java:1518) [error] at org.h2.command.Parser.parseSelect(Parser.java:1506) [error] at org.h2.command.Parser.parsePrepared(Parser.java:405) [error] at org.h2.command.Parser.parse(Parser.java:279) [error] at org.h2.command.Parser.parse(Parser.java:251) [error] at org.h2.command.Parser.prepareCommand(Parser.java:217) [error] at org.h2.engine.Session.prepareLocal(Session.java:415) [error] at org.h2.engine.Session.prepareCommand(Session.java:364) [error] at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1119) [error] at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:71) [error] at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:267) [error] at com.jolbox.bonecp.ConnectionHandle.prepareStatement(ConnectionHandle.java:820) [error] at com.avaje.ebean.config.dbplatform.SequenceIdGenerator.getMoreIds(SequenceIdGenerator.java:193) [error] ... 80 more My model looks like this: @Entity @Table(name = "industry") public class Industry extends Model { @Id public Long id; public String name; public String shortname; // called in the view to trigger lazy-loading public String getName() { return name; } public static Finder<Long, Industry> find = new Finder<Long, Industry>(Long.class, Industry.class); } ... and finally the relevant part from my initial evolution: create table industry ( id bigint not null, name varchar(255), shortname varchar(255), constraint pk_industry primary key (id) } create sequence industry_seq start with 1000; Everything works fine running on my PostgreSQL DB, and from my point of view the code is not any different from the Play2.0 Computer Database Sample. I am happy for any help - thanks! Regards, Alex

    Read the article

  • rank on two dates - each date iteratively

    - by Abhi
    How to query for rank over 'value' for each day in the below table? Ex: IT should list out the 'mydate', 'value', 'rank' for all values on 20th and then do a fresh rank() for all values on 21st? Thanks... create table tv (mydate,value) as select to_date('20/03/2010 00','dd/mm/yyyy HH24'),98 from dual union all select to_date('20/03/2010 01','dd/mm/yyyy HH24'),124 from dual union all select to_date('20/03/2010 02','dd/mm/yyyy HH24'),140 from dual union all select to_date('20/03/2010 03','dd/mm/yyyy HH24'),138 from dual union all select to_date('20/03/2010 04','dd/mm/yyyy HH24'),416 from dual union all select to_date('20/03/2010 05','dd/mm/yyyy HH24'),196 from dual union all select to_date('20/03/2010 06','dd/mm/yyyy HH24'),246 from dual union all select to_date('20/03/2010 07','dd/mm/yyyy HH24'),176 from dual union all select to_date('20/03/2010 08','dd/mm/yyyy HH24'),124 from dual union all select to_date('20/03/2010 09','dd/mm/yyyy HH24'),128 from dual union all select to_date('20/03/2010 10','dd/mm/yyyy HH24'),32010 from dual union all select to_date('20/03/2010 11','dd/mm/yyyy HH24'),384 from dual union all select to_date('20/03/2010 12','dd/mm/yyyy HH24'),368 from dual union all select to_date('20/03/2010 13','dd/mm/yyyy HH24'),392 from dual union all select to_date('20/03/2010 14','dd/mm/yyyy HH24'),374 from dual union all select to_date('20/03/2010 15','dd/mm/yyyy HH24'),350 from dual union all select to_date('20/03/2010 16','dd/mm/yyyy HH24'),248 from dual union all select to_date('20/03/2010 17','dd/mm/yyyy HH24'),396 from dual union all select to_date('20/03/2010 18','dd/mm/yyyy HH24'),388 from dual union all select to_date('20/03/2010 19','dd/mm/yyyy HH24'),360 from dual union all select to_date('20/03/2010 20','dd/mm/yyyy HH24'),194 from dual union all select to_date('20/03/2010 21','dd/mm/yyyy HH24'),234 from dual union all select to_date('20/03/2010 22','dd/mm/yyyy HH24'),328 from dual union all select to_date('20/03/2010 23','dd/mm/yyyy HH24'),216 from dual union all select to_date('21/03/10 00','dd/mm/yyyy HH24'),224 from dual union all select to_date('21/03/10 01','dd/mm/yyyy HH24'),292 from dual union all select to_date('21/03/10 02','dd/mm/yyyy HH24'),264 from dual union all select to_date('21/03/10 03','dd/mm/yyyy HH24'),132 from dual union all select to_date('21/03/10 04','dd/mm/yyyy HH24'),142 from dual union all select to_date('21/03/10 05','dd/mm/yyyy HH24'),328 from dual union all select to_date('21/03/10 06','dd/mm/yyyy HH24'),184 from dual union all select to_date('21/03/10 07','dd/mm/yyyy HH24'),240 from dual union all select to_date('21/03/10 08','dd/mm/yyyy HH24'),224 from dual union all select to_date('21/03/10 09','dd/mm/yyyy HH24'),496 from dual union all select to_date('21/03/10 10','dd/mm/yyyy HH24'),370 from dual union all select to_date('21/03/10 11','dd/mm/yyyy HH24'),352 from dual union all select to_date('21/03/10 12','dd/mm/yyyy HH24'),438 from dual union all select to_date('21/03/10 13','dd/mm/yyyy HH24'),446 from dual union all select to_date('21/03/10 14','dd/mm/yyyy HH24'),426 from dual union all select to_date('21/03/10 15','dd/mm/yyyy HH24'),546 from dual union all select to_date('21/03/10 16','dd/mm/yyyy HH24'),546 from dual union all select to_date('21/03/10 17','dd/mm/yyyy HH24'),684 from dual union all select to_date('21/03/10 18','dd/mm/yyyy HH24'),568 from dual union all select to_date('21/03/10 19','dd/mm/yyyy HH24'),504 from dual union all select to_date('21/03/10 20','dd/mm/yyyy HH24'),392 from dual union all select to_date('21/03/10 21','dd/mm/yyyy HH24'),256 from dual union all select to_date('21/03/10 22','dd/mm/yyyy HH24'),236 from dual union all select to_date('21/03/10 23','dd/mm/yyyy HH24'),168 from dual

    Read the article

  • Union with LINQ to XML

    - by Ryan Riley
    I need to union two sets of XElements into a single, unique set of elements. Using the .Union() extension method, I just get a "union all" instead of a union. Am I missing something? var elements = xDocument.Descendants(w + "sdt") .Union(otherDocument.Descendants(w + "sdt") .Select(sdt => new XElement( sdt.Element(w + "sdtPr") .Element(w + "tag") .Attribute(w + "val").Value, GetTextFromContentControl(sdt).Trim()) ) );

    Read the article

  • Trying to speed up a SQLITE UNION QUERY

    - by user142683
    I have the below SQLITE code SELECT x.t, CASE WHEN S.Status='A' AND M.Nomorebets=0 THEN S.PriceText ELSE '-' END AS Show_Price FROM sb_Market M LEFT OUTER JOIN (select 2010 t union select 2020 t union select 2030 t union select 2040 t union select 2050 t union select 2060 t union select 2070 t ) as x LEFT OUTER JOIN sb_Selection S ON S.MeetingId=M.MeetingId AND S.EventId=M.EventId AND S.MarketId=M.MarketId AND x.t=S.team WHERE M.meetingid=8051 AND M.eventid=3 AND M.Name='Correct Score' With the current interface restrictions, I have to use the above code to ensure that if one selection is missing, that a '-' appears. Some feed would be something like the following SelectionId Name Team Status PriceText =================================== 1 Barney 2010 A 10 2 Jim 2020 A 5 3 Matt 2030 A 6 4 John 2040 A 8 5 Paul 2050 A 15/2 6 Frank 2060 S 10/11 7 Tom 2070 A 15 Is using the above SQL code the quickest & efficient?? Please advise of anything that could help. Messages with updates would be preferable.

    Read the article

  • SQL UNION ALL problem after using UNION ALL more than 10 times

    - by VBGKM
    I'm getting a formatting problem if I use more than 10 UNION ALL statements in my VBA Code. If I use 10 or less everything works great. What I'm trying to do is combine 12 worksheets (Excel 2007). I have a numerical column called SC that turns into string and date if I have more than 10 UNION ALL. If I try to use ROUND with more than 10 UNION ALL my last selection will change all the records by one unit. I'm using Microsoft.ACE.OLEDB.12.0 as my provider and my connection string has worked for several things in my code so far. Is there any limit for UNION ALL statements when using OLEDB? Here is my code. Dim StrOr As String Dim i As Variant Dim Cnt As ADODB.Connection Dim Rs As ADODB.Recordset For i = 1 To 12 StrOr = StrOr & " " & "SELECT SC FROM [" & MonthName(i, True) & "$" & "] UNION ALL" Next StrOr = Left(StrOr, Len(StrOr) - 9) & ";" Call GetADOCnt Call ADORs

    Read the article

  • Handle Union of List in C# with duplicates

    - by user320587
    Hi, I am trying to understand how to handle union or merge of two lists that can have duplicates. For example, List1 has { A, B, C} and List2 has { B, C, D }. I tried to use the Union operation and got a new list with values (A, B, C, D}. However, I need the B & C values from the second list, not first one. Is there a way to specify the union method, which duplicate value to use. The code I am using now is var newList = List1.Union<Object>(List2).ToList(); Thanks for any help. Javid

    Read the article

  • mysql true row merge... not just a union

    - by panofish
    What is the mysql I need to achieve the result below given these 2 tables: table1: +----+-------+ | id | name | +----+-------+ | 1 | alan | | 2 | bob | | 3 | dave | +----+-------+ table2: +----+---------+ | id | state | +----+---------+ | 2 | MI | | 3 | WV | | 4 | FL | +----+---------+ I want to create a temporary view that looks like this desired result: +----+---------+---------+ | id | name | state | +----+---------+---------+ | 1 | alan | | | 2 | bob | MI | | 3 | dave | WV | | 4 | | FL | +----+---------+---------+ I tried a mysql union but the following result is not what I want. create view table3 as (select id,name,"" as state from table1) union (select id,"" as name,state from table2) table3 union result: +----+---------+---------+ | id | name | state | +----+---------+---------+ | 1 | alan | | | 2 | bob | | | 3 | dave | | | 2 | | MI | | 3 | | WV | | 4 | | FL | +----+---------+---------+ First suggestion results: SELECT * FROM table1 LEFT OUTER JOIN table2 USING (id) UNION SELECT * FROM table1 RIGHT OUTER JOIN table2 USING (id) +----+---------+---------+ | id | name | state | +----+---------+---------+ | 1 | alan | | | 2 | bob | MI | | 3 | dave | WV | | 2 | MI | bob | | 3 | WV | dave | | 4 | FL | | +----+---------+---------+

    Read the article

  • Union and If Exists - not working together - Please help

    - by needshelp
    I need to get dummy values if they do no rows returned from table. The If exists works by itself, but gives error with a Union. Can someone please guide me with a solution or a workaround? create table test1 (col1 varchar(10)) create table test2 (col1 varchar(10)) create table test3 (col1 varchar(10)) insert test1 values ('test1-row1') insert test1 values ('test1-row2') insert test2 values ('test2-row1') insert test2 values ('test2-row2') select col1 from test1 union select col1 from test2 union if exists (select * from test3) select col1 from test3 else select 'dummy'

    Read the article

  • SPARQL UNION - Result set incomplete

    - by jplevac
    I have two queries: query 1: SELECT DISTINCT ?o COUNT(?o) WHERE { ?s1 ?somep1 <predicate_one-uri>. ?s1 ?p ?o} query 2: SELECT DISTINCT ?o COUNT(?o) WHERE {?s2 ?somep2 <predicate_two-uri>.?s2 ?p ?o.} Each query gives me a different result set (as expected). I need to make a union of these two sets, from what I understand the query below should give me the set I want: SELECT DISTINCT ?o COUNT(?o) WHERE { { ?s1 ?somep1 <predicate_one-uri>.?s1 ?p1 ?o} UNION {?s2 ?somep2 <predicate_two-uri>.?s2 ?p2 ?o.} } The problem is that some results from query 1 are not in the union set and vice-versa for query 2. The union is not working properly as it does not incorporate all results of query 1 and query 2. Please advise on the proper structure of the sparql query for achieving the desired result set. Thanks in advance! JP Levac

    Read the article

  • Implementing a c/c++ style union as a column in MySQL

    - by user81338
    Friends, I have a strange need and cannot think my way through the problem. The great and mighty Google is of little help due to keyword recycling (as you'll see). Can you help? What I want to do is store data of multiple types in a single column in MySQL. This is the database equivalent to a C union (and if you search for MySQL and Union, you obviously get a whole bunch of stuff on the UNION keyword in SQL). [Contrived and simplified case follows] So, let us say that we have people - who have names - and STORMTROOPERS - who have TK numbers. You cannot have BOTH a NAME and a TK number. You're either BOB SMITH -or- TK409. In C I could express this as a union, like so: union { char * name; int tkNo; } EmperialPersonnelRecord; This makes it so that I am either storing a pointer to a char array or an ID in the type EmperialPersonnelRecord, but not both. I am looking for a MySQL equivalent on a column. My column would store either an int, double, or varchar(255) (or whatever combination). But would only take up the space of the largest element. Is this possible? (of course anything is possible given enough time, money and will - I mean is it possible if I am poor, lazy and on a deadline... aka "out of the box")

    Read the article

  • Implementing union of Set using basic java array

    - by lupindeterd
    Note: This is an assignment. Hi, Continuing with my Set implementation using Java basic array, I'm now struggling with the 3 to last function namely the union. import java.io.*; class Set { private int numberOfElements = 0; private String[] setElements = new String[5]; private int maxNumberOfElements = 5; // constructor for our Set class public Set(int numberOfE, int setE, int maxNumberOfE) { int numberOfElements = numberOfE; String[] setElements = new String[setE]; int maxNumberOfElements = maxNumberOfE; } // Helper method to shorten/remove element of array since we're using basic array instead of ArrayList or HashSet from collection interface :( static String[] removeAt(int k, String[] arr) { final int L = arr.length; String[] ret = new String[L - 1]; System.arraycopy(arr, 0, ret, 0, k); System.arraycopy(arr, k + 1, ret, k, L - k - 1); return ret; } int findElement(String element) { int retval = 0; for ( int i = 0; i < setElements.length; i++) { if ( setElements[i] != null && setElements[i].equals(element) ) { return retval = i; } retval = -1; } return retval; } void add(String newValue) { int elem = findElement(newValue); if( numberOfElements < maxNumberOfElements && elem == -1 ) { setElements[numberOfElements] = newValue; numberOfElements++; } } int getLength() { if ( setElements != null ) { return setElements.length; } else { return 0; } } String[] emptySet() { setElements = new String[0]; return setElements; } Boolean isFull() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == maxNumberOfElements ){ return True; } else { return False; } } Boolean isEmpty() { Boolean True = new Boolean(true); Boolean False = new Boolean(false); if ( setElements.length == 0 ) { return True; } else { return False; } } void remove(String newValue) { for ( int i = 0; i < setElements.length; i++) { if ( setElements[i].equals(newValue) ) { setElements = removeAt(i,setElements); } } } int isAMember(String element) { int retval = -1; for ( int i = 0; i < setElements.length; i++ ) { if (setElements[i] != null && setElements[i].equals(element)) { return retval = i; } } return retval; } void printSet() { for ( int i = 0; i < setElements.length; i++) { System.out.println("Member elements on index: "+ i +" " + setElements[i]); } } String[] getMember() { String[] tempArray = new String[setElements.length]; for ( int i = 0; i < setElements.length; i++) { if(setElements[i] != null) { tempArray[i] = setElements[i]; } } return tempArray; } Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } } // This is the SetDemo class that will make use of our Set class class SetDemo { public static void main(String[] args) { //get input from keyboard BufferedReader keyboard; InputStreamReader reader; String temp = ""; reader = new InputStreamReader(System.in); keyboard = new BufferedReader(reader); try { System.out.println("Enter string element to be added" ); temp = keyboard.readLine( ); System.out.println("You entered " + temp ); } catch (IOException IOerr) { System.out.println("There was an error during input"); } /* ************************************************************************** * Test cases for our new created Set class. * ************************************************************************** */ Set setA = new Set(1,10,10); setA.add(temp); setA.add("b"); setA.add("b"); setA.add("hello"); setA.add("world"); setA.add("six"); setA.add("seven"); setA.add("b"); int size = setA.getLength(); System.out.println("Set size is: " + size ); Boolean isempty = setA.isEmpty(); System.out.println("Set is empty? " + isempty ); int ismember = setA.isAMember("sixb"); System.out.println("Element six is member of setA? " + ismember ); Boolean output = setA.isFull(); System.out.println("Set is full? " + output ); setA.printSet(); int index = setA.findElement("world"); System.out.println("Element b located on index: " + index ); setA.remove("b"); setA.emptySet(); int resize = setA.getLength(); System.out.println("Set size is: " + resize ); setA.printSet(); Set setB = new Set(0,10,10); Set SetA = setA.union(setB,setA); } } Ok the method in question will be the implementation of union. As such this: Set union(Set x, Set y) { String[] newtemparray = new String[x.getLength]; newtemparray = x.getMember; return x; } I got this error: symbol : variable getLength location: class Set String[] newtemparray = new String[x.getLength]; ^ d:\javaprojects\Set.java:122: cannot find symbol symbol : variable getMember location: class Set newtemparray = x.getMember; ^ 2 errors My approach for union would be: *) create temporary array of string with size of the object x length. *) store object x members to temporary array by looping the object and calling the getMember *) loop object y members and check if element exist against temporary array. *) discard if it exist/add if it is not there *) return obj x with the union array. thanks, lupin

    Read the article

  • union on the same table

    - by StupidDeveloper
    I have a table: ID | Id1 | Id2 1 | 100 | 12 2 | 196 | 140 3 | 196 | 141 4 | 150 | 140 5 | 150 | 199 I want to write a query that will give me a table containing records with the same ID2 and with id1 equal to 196 or 150. I thought about union: select * from table where itemId = 196 union select * from table where itemId = 150 but that doesn't cover the ID2 requirement. How should I do that?

    Read the article

  • how to convert sql union to linq

    - by lowlyintern
    I have the following Transact SQL query using a union. I need some pointers as to how this would look in LINQ i.e some examples wouldbe nice or if anyone can recommend a good tutorial on UNIONS in linq. select top 10 Barcode, sum(ItemDiscountUnion.AmountTaken) from (SELECT d.Barcode,SUM(AmountTaken) AmountTaken FROM [Aggregation].[dbo].[DiscountPromotion] d GROUP BY d.Barcode UNION ALL SELECT i.Barcode,SUM(AmountTaken) AmountTaken FROM [Aggregation].[dbo].ItemSaleTransaction i group by i.Barcode) ItemDiscountUnion group by Barcode

    Read the article

  • Union Distinct rows but order them by number of occurrences in mysql

    - by Baversjo
    Hi I have the following query: SELECT o.id,o.name FROM object o WHERE ( o.description LIKE '%Black%' OR o.name LIKE '%Black%' ) UNION ALL SELECT o2.id,o2.name FROM object o2 WHERE ( o2.description LIKE '%iPhone%' OR o2.name LIKE '%iPhone%' ) Which procude the following: id name 2 New Black iPhone 1 New White iPhone 2 New Black iPhone I would like to UNION DISTINCT, but I would also like the result ordered by the number of occurrences of each identical row (primary: id).

    Read the article

  • Problem in Union Join For MySQL Query

    - by Mac Taylor
    hey guys i managed to select from a table that saves my latest posts but i need to have double condition in selection here is my code : $sql_query = "SELECT b.*,u.username AS MY_Sender FROM TABLE_users u,TABLE_blogs b Where b.reciever = '0' AND u.user_id = b.sender UNION SELECT b.*,u.username AS MY_reciever FROM TABLE_users u,TABLE_blogs b Where b.reciever != '0' AND u.user_id = b.reciever ORDER BY bid DESC LIMIT 0,7 "; but MY_reciever is Null and empty Am i wrong in using UNION for this need ?!

    Read the article

  • mySQL query: How to insert with UNION?

    - by Industrial
    Hi everybody, I am kind of new to mySQL:s union functions, at least when doing inserts with them. I have gotten the following to work based upon a example found on the net: INSERT INTO tableOne(a, b) SELECT a, $var FROM tableOne WHERE b = $var2 UNION ALL SELECT $var,$var Ok, nothing strange about that. But what happens when I want to insert a third value into the database that has nothing to do with the logic of the Select being done? Like : INSERT INTO tableOne(a, b, c ) How could that be done?

    Read the article

  • Do programmers need a union?

    - by James A. Rosen
    In light of the acrid responses to the intellectual property clause discussed in my previous question, I have to ask: why don't we have a programmers' union? There are many issues we face as employees, and we have very little ability to organize and negotiate. Could we band together with the writers', directors', or musicians' guilds, or are our needs unique? Has anyone ever tried to start one? If so, why did it fail? (Or, alternatively, why have I never heard of it, despite its success?) later: Keith has my idea basically right. I would also imagine the union being involved in many other topics, including: legal liability for others' use/misuse of our work, especially unintended uses evaluating the quality of computer science and software engineering higher education programs -- unlike many other engineering disciplines, we are not required to be certified on receiving our Bachelor's degrees evangelism and outreach -- especially to elementary school students certification -- not doing it, but working with the companies like ISC(2) and others to make certifications meaningful and useful continuing education -- similar to previous conferences -- maintain a go-to list of organizers and other resources our members can use I would see it less so as a traditional trade union, with little emphasis on: pay -- we tend to command fairly good salaries outsourcing and free trade -- most of use tend to be pretty free-market oriented working conditions -- we're the only industry with Aeron chairs being considered anything like "standard"

    Read the article

  • Anonymous union definition/declaration in a macro GNU vs VS2008

    - by Alan_m
    I am attempting to alter an IAR specific header file for a lpc2138 so it can compile with Visual Studio 2008 (to enable compatible unit testing). My problem involves converting register definitions to be hardware independent (not at a memory address) The "IAR-safe macro" is: #define __IO_REG32_BIT(NAME, ADDRESS, ATTRIBUTE, BIT_STRUCT) \ volatile __no_init ATTRIBUTE union \ { \ unsigned long NAME; \ BIT_STRUCT NAME ## _bit; \ } @ ADDRESS //declaration //(where __gpio0_bits is a structure that names //each of the 32 bits as P0_0, P0_1, etc) __IO_REG32_BIT(IO0PIN,0xE0028000,__READ_WRITE,__gpio0_bits); //usage IO0PIN = 0x0xAA55AA55; IO0PIN_bit.P0_5 = 0; This is my comparable "hardware independent" code: #define __IO_REG32_BIT(NAME, BIT_STRUCT)\ volatile union \ { \ unsigned long NAME; \ BIT_STRUCT NAME##_bit; \ } NAME; //declaration __IO_REG32_BIT(IO0PIN,__gpio0_bits); //usage IO0PIN.IO0PIN = 0xAA55AA55; IO0PIN.IO0PIN_bit.P0_5 = 1; This compiles and works but quite obviously my "hardware independent" usage does not match the "IAR-safe" usage. How do I alter my macro so I can use IO0PIN the same way I do in IAR? I feel this is a simple anonymous union matter but multiple attempts and variants have proven unsuccessful. Maybe the IAR GNU compiler supports anonymous unions and vs2008 does not. Thank you.

    Read the article

  • python union of 2 nested lists with index

    - by sbas
    I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 elements are equal to a sublist in A. In this example I want to get B[0] returned ([1,2,3,4]) because its first three elements are equal to A[0]. In addition, I also want the index to A[0] in this example, that is I[0]. I tried different things, but nothing worked so far :( First I tried this: Common = [] for i in range(len(B)): if B[i][:3] in A: id = [I[x] for x,y in enumerate(A) if y == B[i][:3]][0] ctdCommon.append([int(id)] + B[i]) But that takes ages, or never finishes Then I transformed A and B into sets and took the union from both, which was very quick, but then I don't know how to get the corresponding indices Does anyone have an idea?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >