Transact SQL :: Show Particular Records Within Same Group?

Aug 13, 2015

I have a table with 5 columns, let say ID,PersionID, Date, Type,Qty  and source data looks like this

ID   PersonID    Date            Type       Qty  

1      1        01/01/2011       Accept      5          
2      1        01/01/2011       Accept      5  
3      2        02/01/2010       Accept      10             
4      2        02/01/2010       Deny        20  
5      3        02/01/2012       Accept      15

[Code] .....

Output should look like this..look for only Type=Accept until deny is reached. After Deny,if there is a Accept ignore it.

ID  PersonID    Date            Type         Qty
1    1        01/01/2011       Accept        5      (show only one Accept row=1 becoz Type is Accept and date is same,Qtyis
same)
3    2        02/01/2010       Accept        10     (show Accept row=3,ignore deny row)

5    3        02/01/2012       Accept        15     (show Accept row=5)

6    4        05/05/2012       Accept        25     (show Accept rows=6,7 and ignore Deny & Accept rows = 8,9)

7    4        07/08/2012       Accept        20
        
11   6        01/01/2011       Accept        5      (show Accept rows=11,12 because Qty is different)  

12   6        01/01/2011       Accept        15

Create Sample Table (ID int null, PersonID Int null, Date Datetime null , Type varchar(10) null, Qty int null)

Insert into sample values (1 ,1,'01/01/2011','Accept',5),

(2,1,'01/01/2011','Accept',5),  
(3,2,'02/01/2010','Accept',10),             
(4,2,'02/01/2010','Deny',20),  
(5,3,'02/01/2012','Accept',15),  
(6,4,'05/05/2012','Accept',25),  
(7,4,'07/08/2012','Accept',20), 
(8,4,'07/08/2012','Deny',5),
(9,4,'09/23/2012','Accept',23),
(10,5,'09/08/2012','Deny',12),
(11,6,'01/01/2011','Accept',5),          
(12,6,'01/01/2011','Accept',15)

View 4 Replies


ADVERTISEMENT

Transact SQL :: How To Show Value In Only One Group

Nov 3, 2015

I have a table with "Project", "Demo" and "Value". Here is a sample. Is there a way to show the "Value" in just one Demo after a I use group by?

Project  Demo Value

Project1 Adult 100
Project1 Kids 100
Project1 Adult 100
Project2 Adult 200
Project2 Adult 200
Project2 Kids 200
Project2 Kids 200

That is after I ran the SQL: I will get only: (see Project1's Kids's value is null now.

Project  Demo Value

Project1 Adult 100
Project1 Kids
Project2 Adult 200
Project2 Kids 200

View 12 Replies View Related

Transact SQL :: Adding Case When Statement With Group By Query Doesn't Aggregate Records

Aug 28, 2015

I have a a Group By query which is working fine aggregating records by city.  Now I have a requirement to focus on one city and then group the other cities to 'Other'.  Here is the query which works:

Select [City]= CASE WHEN [City] = 'St. Louis' THEN 'St. Louis' ELSE 'Other Missouri City' END, SUM([Cars]) AS 'Total Cars' 
From [Output-MarketAnalysis]
Where [City] IN ('St. Louis','Kansas City','Columbia', 'Jefferson City','Joplin') AND [Status] = 'Active'
Group by [City]

Here is the result:

St. Louis 1000
Kansas City 800
Columbia 700
Jefferson City 650
Joplin 300

When I add this Case When statement to roll up the city information it changes the name of the city to 'Other Missouri City' however it does not aggregate all Cities with the value 'Other Missouri City':

Select [City]= CASE WHEN [City] = 'St. Louis' THEN 'St. Louis' ELSE 'Other Missouri City' END, SUM([Cars]) AS 'Total Cars' 
From [Output-MarketAnalysis]
Where [City] IN ('St. Louis','Kansas City','Columbia', 'Jefferson City','Joplin') AND [Status] = 'Active'
Group by [City]

Here is the result:

St. Louis 1000
Other Missouri City 800
Other Missouri City 700
Other Missouri City 650
Other Missouri City 300

What I would like to see is a result like:

St. Louis 1000
Other Missouri City 2450

View 5 Replies View Related

Any Way To Show A Group Detail Header Row Once For Each Group In A Table?

Nov 21, 2007

I have a need to show a row inside a table group to simulate a header row for the data rows inside the group. The table will not have a real header or footer. Thanks for the help.

View 1 Replies View Related

How To Show Records With JOIN?

Apr 5, 2007

Hi ,

I've got two tables.. the first table carried a ProductID, and amongst other things a TradePrice



The other tbl carries a ProductID, a IndivPrice and a CustomerID



The second tbl lists prices for products for indiv Customers.





My Query needs to bring back ALL the products from the first tbl...

It also needs to show the TradePrice for that product.



I need to join my query to the second tbl...



And finally, if the second tbl has a price for that product AND the customerID is the same as one I pass into the query.. show that price also..



So here's my first query:

SELECT dbo.Products.ProductID, ProductName, ProductTradePrice, IndivPrice, dbo.Trade_PriceLists.CustomerID AS PLCustomerID FROM dbo.Products LEFT OUTER JOIN dbo.Trade_PriceLists ON dbo.Products.ProductID = dbo.Trade_PriceLists.ProductID WHERE (ProductType = 'Trade' OR ProductType = 'Both') AND (Replace(Lower(ProductBrand),' ','') = 'brandname') AND (CustomerID IS NULL OR CustomerID = 'teste' OR CustomerID = '') ORDER BY TradeOrder



I thought that would work, but what happens is that, if that particular customer has no indiv prices set.. then it only shows the ones that have no records at all in that second tbl..



So unless there is a record for a particular product in that second tbl and it doesn't have a CustomerID assigned to (which would never happen as that tbl is only every for indiv customer prices) then it doesn't show.





Examples:



First Tbl

ProductID Name TradePrice

1 Jumper £1.00

2 Jeans £3.00

3 Shoes £5.00

4 Hat £2.00



Second Tbl

ProductID CustomerID IndivPrice

1 teste £0.50

2 othercustomer £2.50

3 teste £4.50



What I want in the results is:



ProductID ProductName TradePrice IndivPrice CustomerID (PLCustomerID)

1 Jumper £1.00 £0.50 teste

2 Jeans £3.00

3 Shoes £5.00 £4.50 teste

4 Hat £2.00



See? - The 2nd product should not get an indiv price as although it's in that second tbl, the customerID assigned to it is different. The 4th product should not get an indiv price as it's not in that second tbl at all.



however, with my query above I'd only get Products 1and 3... and if I did a query on a customer with no indiv prices I'd only get product 4 as it's not in the indiv at all...



HELP!!!!!









View 11 Replies View Related

Programatically Show/hide Group Headers/footers In Reports

May 2, 2008

I have a report that has three levels of grouping including headers (containing titles) and footers (containing summary values). I would like to programatically show/hide these header/footer sections based on a Show/Hide paramter. Is that possible? Currently I work around the problem by just having two physical reports (one with the header/footers, one without)

View 6 Replies View Related

Transact SQL :: Show Total For Each Name

Sep 23, 2015

I tried my syntax below, but it said that the field were not in the group by.  This is syntax and for each of the 2 names (only small subset of real data) I need a Total column to display between each different person like so:

Total, 29, 150, 2400/60
Total, 25, 143, 2400/60

Here is syntax:

Create Table #Farquard
(
empID varchar(50),
fullname varchar(500),
break1 int,
break2 int,
dailytotal int,
workday date
)

[Code] ......

View 8 Replies View Related

Show All Records If SQL Parameter Is Blank?

Jan 1, 2008

 Hi:I have written a SQL statement that accepts a letter and then prints out all the records in a table starting with that letter.  I was wondering if there is a way that I could change the query so that if prints out all records if a blank or empty value is passed in?Here's my query: ALTER PROCEDURE [dbo].[GetMediaListByFirstLetter] (  @firstLetter char(1))AS    SELECT Media_ID, OrgName        FROM         Media         WHERE UPPER(SUBSTRING(Media.OrgName,1,1)) = @firstLetterAny help doing this would be greatly appreciated.Roger 

View 5 Replies View Related

Unable To Show 0 To Many Records With Inner Join

May 2, 2008

I am having problem  with Inner joining of tables
 
my query is..
 Select j.jobSubject,e.eOrganization ,jv.JobClick,j.jobID from dbo.tbl_Jobs jinner join  dbo.tbl_Employer e on e.mId=j.jobCreatedByIDinner join dbo.tbl_JobView jv on jv.JobID=j.jobID
order by jv.JobClick desc This query returns 1 to many records
 
But I need the query should return  0 to many record . .yes I have already know inner join does not handle my problem so plz suggest me which type of join would solve my problem
 

View 3 Replies View Related

How To Show All The Accounts Even If They Don't Have Records For This Period

Aug 5, 2013

I have three tables Accounts, History and Dates . What I need to do is display all the accounts from History (900) records and compare them to the accounts in Accounts table pull all the matching records based on a certain date range , but If there is no record in the History table for this period I still need to display the account from Accounts and some text saying that there is no record matching for this period.

Account History
11
22
33
4NO information for this month
55
SELECT C.ACCOUNT, CASE WHEN C.ACCOUNT = LEFT(H.NUMBER,8)
THEN LEFT(H.NUMBER,8) END FROM ACCTS C
LEFT OUTER JOIN HISTORY H ON C.ACCOUNT = LEFT(H.NUMBER,8)
INNER JOIN DATES D ON h.PERIOD = D.CUR_PERIOD
GROUP BY C.ACCOUNT, H.NUMBER

This will give me all the matching records for the period but I need somehow to show all the accounts even if they don't have records for this period.

View 5 Replies View Related

Show All Records From One Table Regardless Of WHERE Clause

Feb 15, 2007

I have two tables, Employee and Calls. They are joined on an Employee field. In my where clause I have a value specified that only returns specific calls. What I would like to have happen is to have the query return all Employee records regardless if any records from the Calls table is present for that employee. I want something that looks like this:Employee # of Calls
Employee A 5
Employee B 0
Employee C 10

When I apply a WHERE clause to the Calls table I get this:Employee # of Calls
Employee A 5
Employee C 10

I tried a LEFT OUTER JOIN without success. Any suggestions?

View 4 Replies View Related

Make Tablix Column Group Show When Filter Returns No Rows

May 20, 2008

I'm running SQL Server 2008 Feb08 CTP and I've got a tablix with column groupings and row groupings which works nicely, I'm a becomming a big fan of the tablix.

However sometimes the filter I have on a column group returns no records and the whole column group disappears.
Is there any way to make this column appear with but with empty cells as I have another tablix down the page with the same columns and I want the columns to all line up on the multiple tablix.

In Version 2005 I used to achieve the equivalent of a column group within a table by adding a list with filter to the cell, this meant the column always was shown, the tablix allows does this much more elegantly but I'll have to go back to the old method if I can't make the column remain.

Am I just missing a simple option?

Nathan

View 1 Replies View Related

Transact SQL :: Query To Show Totals

Aug 28, 2015

This is a query that produces a table with garbage data, but (I think) will get the point across of what I need. SQL Server 2008

Create Table SanitationGarbage
(
saleid int
,projectname varchar(200)
,typeofsale varchar(200)

[code]....

Now my select query below does not group the data like I need it to, nor does it show a total row like I need it to.  How does this need to be written so the data is displayed in the proper formatting?

Select
projectname
,Count(saleID) As [Total Sales]
,Count(case when typeofsale = 'Final' then saleID else null end) As [Final Sales]
,Count(case when typeofsale = 'Pending' then saleID else null end) As [Pending Sales]
FROM SanitationGarbage
GROUP BY projectname
order by projectname asc

[code]....

View 4 Replies View Related

Transact SQL :: Hours To Show In A Column?

Jun 19, 2015

i'm trying to capture data for every hour and would like to display the hours of the day in a column.

select
case when (datepart(hh,calldate) between 0 and 7AM then 1 else 0 end as [12-7AM],
case when (datepart(hh,calldate) = 8 then 1 else 0 end as [8AM]
from table1
where cast(calldate as date) = cast(calldate as date)

My desired result should display

12-7 am
8 am
9 am
10 am

View 4 Replies View Related

Filtering SqlDataSource To Show All Vs. Non-null Records

Aug 29, 2006

Hi -- I'm starting an ASP.NET 2.0 application which contains a page with a checkbox and gridview control on it.  In its default state the gridview displays all the records from a table pulled from a SQL Server database (via a SqlDataSource object).  When the user checks the checkbox, I want the gridview to display only the records where one of the columns is not null.  But I've been unable to construct the WHERE clause of the SQLDataSource object correctly.  I see that I can hard-code the SqlDataSource object so that the column to be filtered is always NULL or always NOT NULL. But I want this filtering to be more dynamic such that the decision to show all or non-null records happens at run-time.  Should I be using two SqlDataSource objects -- one for the NOT NULL condition and one for the "all records" condition?  Then when the user checks the checkbox, the gridview would be configured to point to the appropriate SqlDataSource object. (???)  Seems like a bit of overhead with that approach.  I'm hoping there's a more elegant way to get this done.  Please let me know if you need more information.  Thanks in advance. Bill

View 2 Replies View Related

How To Show Only Records That Belong To The Logged In User.

Sep 28, 2007

Hello.I realize that this question has been asked before, but I still can't get it to work. Below are some links that might be of help:http://forums.asp.net/p/1159666/1913519.aspx#1913519http://forums.asp.net/p/1161930/1924264.aspxhttp://forums.asp.net/p/1116601/1732359.aspx#1732359http://forums.asp.net/t/1104718.aspxhttp://forums.asp.net/p/1096290/1655706.aspx#1655706http://forums.asp.net/p/1110162/1707952.aspx#1707952 Basically, I need a DropDownList to display only projects for which the logged in user is assigned as leader. The [Projects] table contains an integer ProjectId, a string ProjectName, a uniqueidentifier ProjectLeader, and other fields. Can someone help me with the SQL query and code?  * Here is the definition of the SqlDataSource: <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDB.MDFConnectionString %>" SelectCommand="SELECT [ProjectId], [ProjectName] FROM [Projects] WHERE ([ProjectLeader] = @Leader)" OnSelecting="SqlDataSource5_Selecting"> <SelectParameters> <asp:Parameter Name="Leader" Type="Object" /> </SelectParameters> </asp:SqlDataSource>  * Here is the definition of the SqlDataSource5_Selecting method:   protected void SqlDataSource5_Selecting(object sender, SqlDataSourceSelectingEventArgs e) { e.Command.Parameters("@Leader").Value = loggedInUserId; } where loggedInUserId is a global variable of type System.Guid. It has been evaluated in the Page_Load event to as: loggedInUserId = (System.Guid)Membership.GetUser().ProviderUserKey; Now the first problem I encounter is that when I run the page, the compiler complains and says, "error CS0118: 'System.Data.Common.DbCommand.Parameters' is a 'property' but is used like a 'method'." The second problem is when I insert the line: SqlDataSource5.SelectParameters("Leader").DefaultValue = loggedInUserId; in page_Load. The compiler again says, "error CS0118: 'System.Data.Common.DbCommand.Parameters' is a 'property' but is used like a 'method'." I've spent a long time trying to figure it out, but could not solve it. I would appreciate it if someone can help me out. Thank you very much. 

View 11 Replies View Related

T-SQL (SS2K8) :: Displaying Sum Of Records And Show Row Even If It Is Blank Or Zero

Mar 10, 2015

I am creating a report on an asp.net webpage to show how many times a coupon has been used from a set list of items.There are two tables I am using for this query.Table 1 has the list of items or coupons. Table 2 has a column for the item id from Table 1 and a value.

Example:
Table 1
id Name
1 Coupon1
2 Coupon2
3 Coupon3

[code]...

My current query will only show coupon1 and coupon2 and the number and value. It will not show coupon2 since it hasn't been used. I would still like to show coupon2 with a number of zero and a value of zero.

Current query is:
SELECT Table1.Name, COUNT(Table2.ID) AS CNum, SUM(Table2.Value) AS CValue FROM Table2 JOIN Table1 ON Table2.ID = Table1.ID GROUP BY Table1.Name

View 5 Replies View Related

SQL Server 2008 :: Only Show Duplicated Records

Aug 4, 2015

I have a query below to show all the records with joining these two tables.

SELECT DISTINCT B.BF_ORGN_CD, B.LEV5, A.BF_ACTY_CD
FROM BF_ORGN A
INNER JOIN BF_ORGN_CNSL_TBL B
ON A.CD=B.BF_ORGN_CD
WHERE A.BF_ACTY_CD IS NOT NULL
ORDER BY B.BF_ORGN_CD,A.BF_ACTY_CD

My goal is only to show all the duplicate records.

Bf_ORGN_CD LEV5 BF_ACTY_CD
AC_21234_2 AC_21200_1 402
AC_21236_2 AC_21200_1 402
AC_21238_2 AC_21200_1 402
AC_29000_1 AC_29000_1 802 ---> NOT SHOW (ONLY 1 RECORD)
AC_29988_1 AC_29988_1 801 ---> NOT SHOW (ONLY 1 RECORD)

[code]...

View 9 Replies View Related

Show Number Of Values As % Of Total Records..?

Feb 15, 2007

HiI'm migrating from Access til MySQL.Works fine so far - but one thing is nearly killing me:I got the count of total records in a variabel - (antalRecords)I got the count for the Field Q1 where the value value is = 'nej'Now I just need to calculate how many % of my records have the value 'nej'I access this worked very fine - but with MySQL ( and ASP) I just cant getit right!!! I go crazy ....My code looks like this :strSQL="SELECT COUNT(Q1) AS Q1_nej FROM Tbl_evaluering " &_"WHERE Q1 = 'NEJ' "set RS = connection.Execute(strSQL)antal_nej = RS("Q1_nej")procent_nej = formatNumber((antal_nej),2)/antalrecords * 100Hope ...praying for help ...Please ;-)best wishes -Otto - Copenhagen

View 3 Replies View Related

Show Multiple Order Records In Single Row

Mar 13, 2006

I have two tables CompanyTab and OrderTab .CompanyTab table contain one record for each client while OrderTab table contain multiple orders for clients.

I have data in both table like

CompanyTable
ID Name
1 name1
2 name2

OrderTable

OrderId CompanyTabID
1 1
2 1
3 1
4 1

In my query I want to show all orders in single row.

ID Name Orders
1 name1 1,2,3,4
2 name2 null

Is anybody can help on it.

Thanks
Arvind

View 5 Replies View Related

Transact SQL :: How To Show Sum Of Columns To New Column In Server

Jul 8, 2015

I made a select query which shows following output as shown in picture . 

Now I want to add one more column in this query to show current bags  and Bags in these 2 columns i want to show calculation like    in first rows currentbags column (Receivedbags-DeleiveredBags) and in currentWeight column RecivedWeight+loss-gain-Deliverdweight) which is 1400 and  697.5 after that in secound row i want to add frist rows currentbags value+ second rows (Receivedbags-DeleiveredBags) and same in weight like daily stock register so output looked like below image

There is one more column common date according to which i have to make calculation like

rid     commondate   recdate   recbags        recweight             loss gain   delbags    delwght

101215109    01/01/2015   07/01/2015       1400                  697.5                0                  0            0             0
101215110   02/01/2015      08/01/2015         560                    279.64             0              0         0               0

View 7 Replies View Related

Transact SQL :: Show Customized Error To Clients?

Jun 16, 2015

I don't want show the DBMS error to my clients. I want show a simple error instead of SQL error.

View 3 Replies View Related

Show Records That Have Sub-records?

Mar 5, 2007

Hi,

I have one table which holds an ID, a name, and a parentID (which can either the same as the main ID or it's one of the other ID in that tbl)

At the moment I do a select on the records whos main ID is the same as the ParentID. This gives me an initial list of records who are the "Main" parent records (i.e they are not the child of any other record..

so far so good.

However, what I need to do is for each record work out if they themselves have any Child records. (only some have).

so at the mo I end up with a results set as this:

1 Boats

2 Jumpers

3 Trousers

4 Ships

What I want to end up is something like

1 Boats True

2 Jumpers False

3 Trousers True

4 Ships True



Where the true or false is if the record has any child records..

Any ideas?





View 6 Replies View Related

Simple Count Function - Show All Records For SSN In A Table

Jul 9, 2013

I want my query to list all SSNS that have more than one record in the table. I have this query:

Code:

SELECT SSN, name4, count(*) from [1099_PER]
group by SSN, name4
having count(SSN) > 1

It does retrieve the right SSNS and tells me how many times the SSN occurs in the table. However, I want my query results to display their full records.

For example

SSN NAME4 COUNT
123445555 WALTER - 4

I want the query to show me all four records for this SSN. I thought removing the count field would do this, but it still gives me only one instance of each SSN.

View 6 Replies View Related

Looping Query Results - Show All Duplicate Records

Feb 4, 2015

Query should only return less than 3000 records but its returning over 4M. It needs to show all duplicates records.... All the info are on the same table VENDFIl, so I used a self join but it seems to be looping..

SELECT A.FEDTID, B.VENDOR, C.NPI_NUMBER
FROM VENDFIL A, VENDFIL B, VENDFIL C
GROUP BY A.FEDTID, B.VENDOR

View 5 Replies View Related

Transact SQL :: Show N Number Of Column As Per No Of Days In Month

Aug 26, 2015

I want to show this kind of output

UserID UserName 1 2 3 30
OR
UserID UserName 1 2 3 31

user data saved in db select distinct UserID,Name from Userss Where IsActive=1 and order by UserID and i want to just calculate no of days in month based on year and month name supplied by user. one way i can do it. first i will create a temporary table and in loop add many columns to that table and later dump user data to specific column.

View 10 Replies View Related

Table Set Of Records - Show Purchase Time When It Crossed 1000

Feb 10, 2014

I have a table set of records. Its contains some customerID,SportsGoods,Price in different datetime. I want to add customer spent. If crossed 1000 means i have to show purchase time when it is crossed 1000. I need query without while and looping.

Example:

Customer NameGoodsPriceDatePurchased
ABat2501/31/2014
ABall221/31/2014
BCarrom Board4752/2/2014
CTennis Ball502/1/2014
AFootball1502/2/2014
DBat2501/31/2014
BBall221/31/2014
AHockey Bat1252/4/2014
CChess552/4/2014
AVolley Ball552/4/2014

View 9 Replies View Related

Transact SQL :: Query To Show Most Recent Value Based On Date Field

Jun 18, 2015

I simply need to list the most recent value for each employee here... the value at each person's maximum date

Sample Detail Data:

EmpID                   Date                      Value
1                              1/1/14                  27
1                              2/12/15                333
2                              5/5/15                   255
3                              5/4/15                   110  
3                              1/1/13                   67                          
3                              3/2/14                   80

[Code] ....

What is the most efficient way to display the most recent value for each employee ID via MS SQL.?

View 4 Replies View Related

First And Last Records In A Group

Feb 11, 2012

I have a group of records like this;

NAME| RUN START| RUN END| LK1| LK2| DESC
Graeme Brown|2012-02-23 07:20:00|2012-02-23 07:50:00|2213|2244|AK1/4/PI2
Graeme Brown|2012-02-23 08:00:00|2012-02-23 09:25:00|2244|2052|AK1/4/PI2
Graeme Brown|2012-02-23 09:30:00|2012-02-23 11:05:00|2052|917|AK1/4/PI2
Graeme Brown|2012-02-23 12:15:00|2012-02-23 13:55:00|917|2052|AK1/4/PI2
Graeme Brown|2012-02-23 14:05:00|2012-02-23 15:40:00|2052|1111|AK1/4/PI2

They are grouped on the last column [DESC].

I want to get;

NAME| RUN START| RUN END| LK1| LK2| DESC
Graeme Brown| 2012-02-23 07:20:00| 2012-02-23 15:40:00| 2213| 1111| AK1/4/PI2

So what it needs to do is combine the ;

earliest RUN START and corresponding LK1 with
latest RUN END and corresponding LK2.

I've tried creating temp tables with the mins and maxs - but then I can't combine them with the LK1 and Lk2 fields...

View 3 Replies View Related

Group Records

Jun 21, 2007

sample query results:
cid cno cvalue
--- --- -------
835201add edit
835201add edit
836202with VAT
836202with VAT

how can i filter this more into this:
835201add edit
836202with VAT

View 3 Replies View Related

Need Help To Group By Top 2 Records

Nov 7, 2007

Hi,
can anyone help me to group by Top 2 records by ID and Date?
My table contains following data


create table #test (id int, code varchar(10),TestDate datetime)
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (12,'BC','02/18/2007')
insert into #test (id,code,TestDate) values (12,'BC','02/18/2007')
insert into #test (id,code,TestDate) values (12,'BC12','10/01/2007')
insert into #test (id,code,TestDate) values (12,'BC11','10/11/2007')
insert into #test (id,code,TestDate) values (12,'BC11','01/25/2007')
insert into #test (id,code,TestDate) values (12,'ABC','01/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/12/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/12/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
insert into #test (id,code,TestDate) values (14,'YZ123','02/11/2007')
select * from #test order by TestDate









--Result Set
id code TestDate
12 ABC 2007-01-11 00:00:00.000
12 ABC 2007-01-11 00:00:00.000
12 ABC 2007-01-11 00:00:00.000
12 BC11 2007-01-25 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-11 00:00:00.000
14 YZ123 2007-02-12 00:00:00.000
14 YZ123 2007-02-12 00:00:00.000
12 BC 2007-02-18 00:00:00.000
12 BC 2007-02-18 00:00:00.000
12 BC12 2007-10-01 00:00:00.000
12 BC11 2007-10-11 00:00:00.000



--I want to get only duplicate records, so SQL should eliminate uniq recod.Total will --get total number of records per ID and date, but want to display only two reacords by --Id and Testdate.
--my result set should contain following data


--Total of first byID and by Date
----id code TestDate Total
----12 ABC 2007-01-11 00:00:00.000 3
----12 ABC 2007-01-11 00:00:00.000

----14 YZ123 2007-02-11 00:00:00.000 3
----14 YZ123 2007-02-11 00:00:00.000

----14 YZ123 2007-02-12 00:00:00.000 2
----14 YZ123 2007-02-12 00:00:00.000

----12 BC 2007-02-18 00:00:00.000 2
----12 BC 2007-02-18 00:00:00.000


If anyone have any idea,, plz help me out..

Thanks....

View 2 Replies View Related

Transact SQL :: Retrieve All Records From Parent Table And Any Records From Child Table

Oct 21, 2015

I am trying to write a query that will retrieve all students of a particular class and also any rows in HomeworkLogLine if they exist (but return null if there is no row). I thought this should be a relatively simple LEFT join but I've tried every possible combination of joins but it's not working.

SELECT
Student.StudentSurname + ', ' + Student.StudentForename AS Fullname,
HomeworkLogLine.HomeworkLogLineTimestamp,
HomeworkLog.HomeworkLogDescription,
ROW_NUMBER() OVER (PARTITION BY HomeworkLogLine.HomeworkLogLineStudentID ORDER BY

[Code] ...

It's only returning two rows (the students where they have a row in the HomeworkLogLine table). 

View 3 Replies View Related

Get Group And Multiply Records

Dec 20, 2013

1.Create the tables with insert queries
2. provide the result as required in an temp table
3. Display the expected result

======================================================================
CREATE TABLE and Insert Data
======================================================================
use master
CREATE TABLE [dbo].[Travel_Master](
[Load_Id] [int] NULL,
[Mode_Id] [nchar](2) NULL,
[Mode_Info] [nchar](10) NULL,
[Has_Nodes] [nchar](3) NULL
) ON [PRIMARY]

[Code] .....

View 14 Replies View Related







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