Create A Query That Will Give Result Set Containing Primary Order On Type

May 14, 2012

I have a table with plant types and plant names. Certain plants are grouped on a custom field, currently called Field. I am trying to create a query that will give me a result set containing the primary order on Type, but need items with the same 'Field' value grouped by each other.For example, the following shows a standard query result with "order by Type", ie select * from plants order by Type

Code:
ID Type Name Field
1 Type1Name1(group1)
2 Type2Name2(group2) -group2
3 Type3Name3(group3)
4 Type4Name4(group4)
5 Type5Name5(group2) -group2
6 Type6Name6(group6)

But I want it to look like this, with fields of the same value located next to each other in the result set (but still initially ordered by Type)

Code:
1 Type1Name1(group1)
2 Type2Name2(group2) -group2
5 Type5Name5(group2) -group2
3 Type3Name3(group3)
4 Type4Name4(group4)
6 Type6Name6(group6)

View 7 Replies


ADVERTISEMENT

Transact SQL :: Create A Pivot Query That Will Give Result That Is Horizontal

Jul 8, 2015

I have some data which is vertical...I want to create a pivot query in SQL that will give me a result that is horizontal like this. I cannot find a way of doing it without lots of IF or CASE statements?

View 10 Replies View Related

Create A View That Will Give Most Current Status (by Statusdatetime) Of Each Order Number

Jan 20, 2015

We are having trouble figuring out how to create a view for this scenario:

We have a status log table that holds an order number, statusdatetime, and statuscode. This table will have multiple status' for the same order number. I want to create a view that will give me the most current status (by statusdatetime) of each order number. This view would show: order number, statusdatetime, and statuscode.

Here is a sample of the data:

Order numberStatusDateTimeStatusCode
1234512/15/2014 15:00CREATE
1234512/15/2014 16:30CONFIRMED
4567812/16/2014 08:00CREATE
9876412/18/2014 12:00CREATE
9876412/19/2014 08:00CONFIRMED
4567812/17/2014 09:30CONFIRMED
4567812/19/2014 15:30IN-TRANSIT

So my view should result in :

Order numberStatusDateTimeStatusCode
1234512/15/2014 16:30CONFIRMED
9876412/19/2014 08:00CONFIRMED
4567812/19/2014 15:30IN-TRANSIT

View 4 Replies View Related

Please Help Me To Optimize This Sql Query, It Takes 28 Seconds To Return Result. Please Give Me A Tips Where I Went Wrong?

Aug 21, 2006

SELECT * FROM
( SELECT TOP 15 * FROM
(SELECT TOP 15 CMDS.STOCKCODE AS CODE,CMDS.STOCKNAME AS NAME,CMDS.Sector AS SEC, CMD7.REFERENCE AS REF,T1.HIGHP AS HIGH,
T1.LOW,T1.B1_CUM AS 'B/QTY', T1.B1_PRICE AS BUY,T1.S1_PRICE AS SELL,
T1.S1_CUM AS 'S/QTY', T1.D_PRICE AS LAST,T1.L_CUM AS LVOL,T1.Chg AS CHG,T1.Chgp AS CHGP, T1.D_CUM AS VOLUME,substring(T1.ST,7,6) AS TIME,
CMDS.SERIAL as SERIAL FROM CMD7,CMDS,CMD4 AS T1 WHERE T1.ST IN
(SELECT max(T2.ST) FROM CMD4 AS T2 ,CMDS WHERE
T1.SERIAL=T2.SERIAL
AND CMDS.SERIAL=T2.SERIAL
AND T2.sd='20060821'
AND CMDS.sd='20060821'
AND T2.L_CUM < '1900'
AND CMDS.sector >='1'
AND CMDS.sector <='47')
AND CMDS.SERIAL=T1.SERIAL AND
CMDS.SERIAL=CMD7.SERIAL AND
CMDS.sd='20060821' AND
CMD7.sd='20060821' AND
T1.sd='20060821' AND
T1.L_CUM < '1900' AND
CMDS.sector >='1' AND
CMDS.sector <='47' ORDER BY T1.D_CUM desc)
AS TBL1 ORDER BY VOLUME asc) AS TBL1 ORDER BY VOLUME desc;

View 6 Replies View Related

Why Doesnt BETWEEN Give Me My Desired Result?

Dec 9, 2005

I am trying to select records based upon last name
WHERE     (Last_Name BETWEEN 'A%' AND 'C%')
When I run this I get only last names starting with A and B--no C. ?!?
This is confusing to me....I ran it with lastname >= 'A%' and lastname <='C%'and it returned only names starting with B. Why does SQL ignore the "="
I hope this isnt obvious :/
 
 

View 6 Replies View Related

CASE Does Not Give Correct Result

Aug 31, 2007

How do I automatically assign a new cardcode-number? (according to the following formula: highest existing number + 1)

Scenario:
-There are two types of business partners: Customers and Suppliers.
-Customers have the value 'C' in the colomn CardType.
-Suppliers have the value 'S' in the colomn CardType.
-Customers have the following syntax 'C123456' in the colomn CardCode.
-Suppliers have the following syntax 'S123456' in the colomn CardCode.
-Existing CardCode-values in the DB for the Customers: C000001 - C100599.
-Existing CardCode-values in the DB for the Suppliers: S000001 - S200199.

The idea is that when a user creates a new business partner, the CardCode should be automatically filled when a new assigned number (highest existing number + 1), according to the value that is selected in CardType (either the letter 'C' or 'S').


What's been done so far:
SELECT top 1
(CASE
WHEN CardType='C' THEN (SELECT top 1 'C' + '' + cast((substring(T0.CardCode, 2, 7) + 1) as varchar) as [nummer]
FROM OCRD T0
WHERE T0. CardCode like 'C%' AND T0. CardType='C'
order BY T0.CardCode desc FOR BROWSE)
WHEN CardType='S' THEN (SELECT top 1 'S' + '' + cast((substring(T0.CardCode, 2, 7) + 1) as varchar) as [nummer]
FROM OCRD T0
WHERE T0. CardCode like 'S%' AND T0. CardType='S'
order BY T0.CardCode desc FOR BROWSE)
END)
FROM OCRD T0


The current result:
The result that it gives is 'C100600'.
The problem however is that it always gives this result and does not take into account what has been selected in CardType.

When I add the following: "order BY T0.CardCode desc FOR BROWSE" it gives the result 'S200200'.

So, what does work is that it takes the highest existing value and adds 1. But what doesn't work is the taking account what value is selected in CardType.

Does anyone know how I can make this work?

View 4 Replies View Related

Create Union Query Result

Jun 20, 2008

Hi,I was wondering if someone can help me.  I have 4 tables in an SQL Server 2005 database, for purposes sake called 'table1', 'table2', 'table3' and 'table4'. They all have the same data structure between them.  The columns inside them have the exact same design.  For purposes sake called 'column1', 'column2', 'column3' and 'column4'.  Alot of these tables have duplicate records scattered between them, so basically I want to create 'table5' with the same column names but only unique records.  Can someone specify the syntax I need for this.  I'm pretty sure it's a union query I need so am scouring as I type this also.   Many Thanks Robert  

View 5 Replies View Related

SQL Query - Using Result Of Create Function

Aug 24, 2004

I created a function that will return
from OpenDataSource('.....') tablename
where ... is fully populated.

However, I can't figure out how to use it?

For example

select functiona (parameter) as data_src

this returns the "from" statement above

I then try to run

select * data_src

So how do I reference the contents of data_src in the select?

Thanks for any help

View 1 Replies View Related

Conditional Order By - Sort Result Set By Employee Number Ascending Order

Sep 24, 2012

In SQL sERVER 2008, I have two fields - Depatment and Employees. I need to sort the result set by employee number ascending order, with following exception

1)when department number = 50 - the preferred order is Employee # - 573 followed by 551-572 (employee # belong to Dept 50 = 551-573)

2)When Department number = 20 – the preferred sort order is Employee # 213-220, followed by Employee # 201-213 (employee # belong to Dept 20 = 201-220)

How shall I achieve this?

View 4 Replies View Related

Someone Can Give A Litgh? - Field Type

May 17, 2004

Hi Everybody,

In a table there´s a field for store real values,
so...in the database, using the SQL Server Enterprise Manager
and execute query as 'select * from' and it return the value
'15,35' just like stored before, why using Delphi via an ADO conection
in my result set there is a '15,3500003814697' value if in the record time
the inputed value was '15,35'?
What I have doing wrong?
Thanks for attention

Leonardo Almeida

View 2 Replies View Related

Report Model - How To Create A Unique Logical Primary Key In A Named Query

Apr 7, 2008



Hi,
Te following situtation is :

ReportModel is created ,there is only a named query in DSV ,it has a few tables in it(The relationship are inner joins and outer joins).

The question is how could I create a unique logical primary key to identify each unique row in the named query dataset, and also you cannt generate a model unless the named query has a logical primary key . how can I solve this problem,any help?


View 2 Replies View Related

Is There A Way To Give Someone The Right To Create Only Views And No Other Objects In A Database

Feb 25, 2008

Is there a way to give someone the right to create only views and no other objects in a database? Currently I have given the individual ddladmin database rose, but would rather be more restrictive?

View 1 Replies View Related

Transact SQL :: Create A Report Which Would Give Latest Transaction On Database

Jul 17, 2015

I'm trying to create a report which would give the latest transaction on a database, which all sit on different servers. I wanted to know if there is an a simple way tracking the latest transactions instead of getting the information from the database tables.

View 3 Replies View Related

SQL Security :: Create Database User And Give Grants To Few System Tables

Aug 12, 2015

Need to create a user in sql server provide grants to few system tables to the above user.

View 10 Replies View Related

SQL Security :: Give Access To Create Alter And Execute SPs In Server 2008R2

May 12, 2015

Is there a way i can grant a windows authenticated user say abcadam privilege:

-> to create, execute and alter the stored procedures that will be created by him only:

Point is we do not want the user to execute alter or modify other stored procedures out there for that DB

View 13 Replies View Related

DB Design :: Create Views From 2 Tables One Of Which Is Lookup Table That Will Give Column Names

Aug 5, 2015

I am trying a create views that would join 2 tables:

Table 1: Has all the columns need by a view (
Name: Product
Structure: ID, Attribute 1, Attribute 2, Attribute 3, Attribute 4, Attribute 5 etc
Table 2: Is a lookup table that provides the names of columns
Name: lookupTable
Structure: tableName, ColumnName, columnValue
Values: Product, Attribute1, Color
Product, Attribute2, Size
Product, Attribute3, Flavor
Product, Attribute4, Shape

I want to create a view that looks like

ID, Color, Size, Flavor, Shape

View 4 Replies View Related

Display Of A Result Set Without Order By

Apr 8, 2008

Hi all

If we don't specify any Order by clause, what is the default order of displaying the data .

Will SQL Server show the data in a consistent order?

Thanks.

View 6 Replies View Related

Query To Give All Table Sizes On A Database (was Query Help)

Mar 9, 2006

Hi,
Does anyone has query to give all table sizes on a database?
Appreciate your help.
Thanks

View 2 Replies View Related

Saving Query Result To A File , When View Result Got TLV Error

Feb 13, 2001

HI,
I ran a select * from customers where state ='va', this is the result...

(29 row(s) affected)
The following file has been saved successfully:
C:outputcustomers.rpt 10826 bytes

I choose Query select to a file
then when I tried to open the customer.rpt from the c drive I got this error message. I am not sure why this happend
invalid TLV record

Thanks for your help

Ali

View 1 Replies View Related

End Result Is Main Query Results Ordered By Nested Result

May 1, 2008

As the topic suggests I need the end results to show a list of shows and their dates ordered by date DESC.
Tables I have are structured as follows:

SHOWS
showID
showTitle

SHOWACCESS
showID
remoteID

VIDEOS
videoDate
showID

SQL is as follows:

SELECT shows.showID AS showID, shows.showTitle AS showTitle,
(SELECT MAX(videos.videoFilmDate) AS vidDate FROM videos WHERE videos.showID = shows.showID)
FROM shows, showAccess
WHERE shows.showID = showAccess.showID
AND showAccess.remoteID=21
ORDER BY vidDate DESC;

I had it ordering by showTitle and it worked fine, but I need it to order by vidDate.
Can anyone shed some light on where I am going wrong?

thanks

View 3 Replies View Related

Different Rows Order In Result Grid

Sep 20, 2001

Hello!
I have two similar servers (hardware) with
SQL Server 2000 (SP1) on Win2000 (SP2).
(sp_helpsort - default)

When I run the same SELECT statement from Query Analyzer on each machine
I get different rows order in result Grid
(the order of rows stays the same for each machine but different for
machine1 and machine2)

SELECT table1.a,
table1.b,
table1.c,
table1.d

FROM table2,
table1,
table3

WHERE table2.nTestDefnId = 1034
AND table2.nDefnId = table1.nDefnId
AND table3.szClinDiscType = 'X'
AND table2.nDiscId = table3.nDiscId

What is a reason for such behavior and how I can fix it?

Thank you in advance,
Elena.

View 1 Replies View Related

Trying To Join Within A Table - Get Result Sorted By Primary ID

Aug 27, 2014

So if an item is a bottle, it will have a unique BottleKey and Null for CaseKey and if an item is a Case, it will have a unique CaseKey and Null for BottleKey. However, the PrimaryIDs are the same for both the bottle and case. I get the results to look like this:

Bottlekey CaseKey PrimaryID
4754 NULL ABC-234
NULL 5465 ABC-234
.... .... .......

Is there a way to get the result sorted by Primary ID?

So that the rows are halved from what we have in the table above and the results look like

PrimaryID CaseKey BottleKey
ABC-234 5465 4754

View 1 Replies View Related

CREATE TYPE Failed Because It Could Not Find Type

Jul 28, 2006

Hello --

I am having a UDT problem. When I run the Create Type command. I receive the "could not find type" error. I have seen other posts on here related to the default namespace in VB.NET. When I add the namespace I receive "Incorrect syntax near '.'." What is the format of the EXTERNAL NAME parameter. Thanks for any help. Code below...

Incorrect Syntax Error:

DROP ASSEMBLY CadSqlUdtsCREATE ASSEMBLY CadSqlUdtsAUTHORIZATION [dbo]FROM 'E:CAD.NETCADUDTsReleaseCadSqlUdts.dll'WITH PERMISSION_SET = SAFEGOCREATE TYPE dbo.ReportingAreaUDTEXTERNAL NAME CadSqlUdts.[CadSqlUdts.CadSqlUdts].ReportingAreaUDT;GO

Could Not Find Type Error:

DROP ASSEMBLY CadSqlUdtsCREATE ASSEMBLY CadSqlUdtsAUTHORIZATION [dbo]FROM 'E:CAD.NETCADUDTsReleaseCadSqlUdts.dll'WITH PERMISSION_SET = SAFEGOCREATE TYPE dbo.ReportingAreaUDTEXTERNAL NAME CadSqlUdts.ReportingAreaUDT;GO
What's up??

View 3 Replies View Related

Compound Primary Key - Order Not As Expected

Apr 26, 2006

Hello,if you create this table:create table hello (int a, int bconstraint pk_hello primary key clustered ( a, b ))and then insert the following recordsa,b1,11,21,32,12,22,33,13,23,3and then doselect a,b from hellothe output seems to be:a,b1,12,13,11,22,23,21,32,33,3which is wrong and (i think) is reflecting the actual index orderand physical order on diskit should be:a,b1,11,21,32,12,22,33,13,23,3i have tested this on a table with 500,000 recordsand sure enough if you declare the clustered primary key fields inreverse order:constraint pk_hello primary key clustered ( b, a )two things happen:- the select with no order by returns the records in the expected order- queries relying on that order run MUCH FASTERhas anyone else seen / noticed this?

View 9 Replies View Related

Incorrect Order Result Set When Join Table

Mar 24, 2002

Hi all,
I faced a problem, I have two tables - part and partmaster
part : part_no, part_qty (no key)
partmaster : part_no, part_description (primary key : part_no )

I want to select table part.* and partmaster.part_description.

(run on mssql 2k)
select a.*, b.part_description
from part a, partmaster b where a.part_no *= b.part_no

I want to and expect to have the result order like table "part". However, after the join, the order is different. I try to run it on mssql 7.0, the order is ok.

Then I modify and run the statement select a.* from part a, partmaster b where a.part_no *= b.part_no on 2k again. The result order is ok.

can anyone tell me the reason?

Now I try to fix this problem is adding a sequence field "part_seq" into table "part" and run the statement by adding a order by part_seq.
It does work!

Regards,
Simon

View 1 Replies View Related

T-SQL (SS2K8) :: Display Result In Required Order

Jun 17, 2014

I have an issue while display the result in the required order. How to get the required output.

Code :

USE tempdb
GO

IF OBJECT_ID('tempdb..#VersionFormat_tbl') IS NOT NULL
DROP TABLE #VersionFormat_tbl
CREATE TABLE #VersionFormat_tbl
(
[FormatID] [smallint] NOT NULL,
[Description] [varchar](50) NULL,

[Code] ....

Present output :
fileExtension FormatID Description fileExtension versionFormatTypeId
txt 1 Text txt 1
html 2 HTML html 1
xml 3 XML xml 1
pdf 4 PDF pdf 1
xls 5 Excel xls 1
doc 6 Word doc 1

Required output:
fileExtensionFormatIDDescriptionfileExtensionversionFormatTypeId
html2HTMLhtml1
xls5Excelxls1
doc6Worddoc1
pdf4PDFpdf1
txt1Texttxt1
xml3XMLxml1

View 5 Replies View Related

Pivot Data Order By Result Time

Apr 17, 2015

I am querying a table with multiple rows

SELECT caseId, Name ,CompletedDate
FROM TableZ

the number of results per CaseID are varable some have 1 record others up to 36 records..I need to pivot the results based off of the competed date
Name has 20 distinct values but we can have diplicates...so something like

Case Name Date
1 This 2015-01-01
1 That 2015-01-03
2 That 2013-01-01
2 Then 2014-12-03
2 This 2015-01-01
2 There 2015-04-03
3 This 1999-01-01
3 That 2001-01-02
3 This 2006-01-01

looks like this

1 This That
2 That Then This There
3 This That This

View 2 Replies View Related

Can Anyone Give Me A Query For This ?

Jul 20, 2005

These are my table structures . Could you please suggest me analternative:tblArticles: ArticleID,Title,Summary,ContextSubTypeID,PostDatetblArticlePages: ArticlePageID,ArticleID,PageNum,ContenttblAuthors:AuthorID, NametblArticleAuthors:ArticleID,AuthorIDtblContextSubtype:ContextSubTypeID,NameI need to get Author,PostDate,Title,tblContextSubType.Name,PageN um,Content,- these have to grouped accordingly by the respective fields. Contentneed not be grouped by.

View 2 Replies View Related

Give Sql Query For This Illustrations

Mar 28, 2008

Hai friends
 i have table student with 2 fields s_id,s_name
s_id      s_name1            raja2           ramu3           vinoth4            muthu5            arun
i have another table test with s_id who wrote test...
s_id    25
now i have to display like below....give me sql query
s_id   s_name2        ramu5        arun
Thanks in Advance...pl Help me......  

View 2 Replies View Related

Give Me Sql Query For One Illustrations

Mar 28, 2008

Hai friends i have table
s_team
id           name       game
 1           raja         cricket
2            ravi          football
3            muthu     cricket
4           pravin      cricket
5          hurry       football
 I have to diplay the above table in the following ...pl give me sql query
game          totalplayers
cricket            3
football           2
 

View 2 Replies View Related

Shouldn't The Order Of Records Be Based On The Key Or Primary Index?

Jun 11, 2007

I upsized an access database with a key / index on ordernumber and linenumber.

However if I open the table in the Management Studio the records aren't ordered this way (same goes for select * from table) I get:










Ordernumber
Linenumber

200724001
37

200724004
3

200724006
33

200724001
3

200724011
19

200724014
5

200724006
37

200724011
19

200724006
28



Same goes for my crystal reports files, since the records aren't ordered by ordernumber / linenumber all my formulas go bezerk..



Am I wrong thinking the records should be ordered according to the prim. index?

Please help because I don't want to have to change all my 40+ reports to include an "ORDER BY"



Best regards,



Mike

View 7 Replies View Related

T-SQL (SS2K8) :: Joining Two Tables - Output Result In The Order By DivID

Mar 25, 2014

I have two tables to be joined

Doc:
ID, DivID

Division:
ID, Div
CREATE TABLE [dbo].[Doc](
[ID] [int] NULL,
[DivID] [int] NULL

[Code] ...

As you can see, some Divisions have no correspondents in Doc, I want to show the count(1) result as 0 for those Division, and output the result in the order by DivID

View 5 Replies View Related

Column Order/presentation In Virtual Table (result Set From Viewor UDF)

Sep 1, 2006

I was just messing around with some ad hoc views and table returningUDFs today so I could look at and print out data from a small tableand noticed something strange.If I stick my select statement into a View the columns are returned inthe order I specify in the SELECT, but if the same statement is in a UDF(so I can specify a parameter), the columns are not returned in theorder specified in statement.I know that relations don't have a specified column order, but it was myunderstanding that a SELECT statement could be used to define how youwant your data presented. Views seem to respect the order specified inthe SELECT, but functions don't.What am I missing? Is there some way to force the order of the columnsreturned from a SELECT?View:CREATE VIEW dbo.View1ASSELECT Ident, Text, Type, ParentStmt, ForStmt, IfStmt, ChildStmt,ThenStmt, ElseStmt, NextStmtFROM dbo.tblStmtWHERE (Ident LIKE '4.2.%')Column order from this view:Ident, Text, Type, ParentStmt, ForStmt, IfStmt, ChildStmt, ThenStmt,ElseStmt, NextStmtFunction:ALTER FUNCTION dbo.Function1(@SearchPrm varchar(255))RETURNS TABLEASRETURN ( SELECT Ident, Text, Type, ParentStmt, ForStmt, IfStmt,ChildStmt, ThenStmt, ElseStmt, NextStmtFROM dbo.tblStmtWHERE (Ident LIKE @SearchPrm) )Column order from this function:Type, Text, ElseStmt, NextStmt, IfStmt, ChildStmt, ThenStmt, Ident,ParentStmt, ForStmtTable:(I know that this table isn't entirely normalized, but it serves mypurposes to have a matrix instead of a fully normalized relation):CREATE TABLE dbo.tblStmt (StmtID INT IDENTITY(1,1) CONSTRAINT PK_Stmt PRIMARY KEY,Ident VARCHAR(255),Text TEXT,ErrorText TEXT,Type INT,ParentStmt VARCHAR(255),ChildStmt VARCHAR(255),IfStmt VARCHAR(255),ForStmt VARCHAR(255),ThenStmt VARCHAR(255),ElseStmt VARCHAR(255),NextStmt VARCHAR(255),FullName VARCHAR(255),LocalName VARCHAR(255),Method INT)INSERT INTO tblStmt Ident, Text, Type, ParentStmt, NextStmtVALUES('4.2.1', 'LineNumberOfResp := EMPTY' 64, '4.2', '4.2.2')INSERT INTO tblStmt Ident, Text, Type, ParentStmt, ChildStmt, ForStmt,NextStmtVALUES('4.2.2', 'FOR K:= 1 TO 2', 128, '4.2', '4.2.3','4.2.7')INSERT INTO tblStmt Ident, Text, Type ParentStmt, ChildStmt, ForStmt,NextStmtVALUES('4.2.3', 'Person[K].KEEP', 16, '4.2', '4.2.3.1', '4.2.2', '4.2.4')INSERT INTO tblStmt Ident, Text, Type, ParentStmt, NextStmtVALUES('4.2.3.1' 'AuxInterviewerName := DOSENV', 64, '4.2.3', '4.2.3.2')

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved