Grouping Datetime

Apr 11, 2000

Hello,
I am trying to group the date by minutes. The date is in
datetime format. My problem is when grouping the seconds
throws me off.
eg. id date
1 03-02-1999 10:23:12.000
2 03-02-1999 10:23:11.000
what I want is when I run count(date) and group by
date the above example should give me 2. In short it
should group 1 & 2 because I want to ignore the seconds.
How can I do that. Everything else is working except
this is kicking my brains. Any and all help aprreciated.
It is also sorts urgent.
Thanks in advance.
HP

View 3 Replies


ADVERTISEMENT

Grouping By The Date Portion Of A Datetime Datatype

Jul 13, 2000

Hi,

I have a requirement to be able to select and group records by the date portion of a datetime field. ie ignore the time when grouping so that all records lodged on a particular day are seen together.

I have been able to do this by

- converting the datetime data to the number of days since a given date
- inserting this into a temporary table
- retrieving the the data from the temporary table
- convert the data back to a date using DATEPART to display dd/mm/yy

This then gives me the data grouped as required but seems to be a very difficult solution - Is there an easier way??

Thanks in advance
jan

View 3 Replies View Related

Query Or Grouping Problem (some Kind Of Parallel Grouping?)

Nov 26, 2007

I'm really stumped on this one. I'm a self taught SQL guy, so there is probobly something I'm overlooking.

I'm trying to get information like this in to a report:

WO#
-WO Line #
--(Details)
--Work Order Line Detail #1
--Work Order Line Detail #2
--Work Order Line Detail #3
--Work Order Line Detail #etc
--(Parts)
--Work Order Line Parts #1
--Work Order Line Parts #2
--Work Order Line Detail #etc
WO#
-WO Line #
--(Details)
--Work Order Line Detail #1
--Work Order Line Detail #2
--Work Order Line Detail #3
--Work Order Line Detail #etc
--(Parts)
--Work Order Line Parts #1
--Work Order Line Parts #2
--Work Order Line Parts #etc

I'm unable to get the grouping right on this. Since the line details and line parts both are children of the line #, how do you do "parallel groups"?

There are 4 tables:

Work Order Header
Work Order Line
Work Order Line Details
Work Order Line Requisitions

The Header has a unique PK.
The Line uses the Header and a Line # as foreign keys that together are unique.
The Detail and requisition tables use the header and line #'s in addition to their own line number foreign keys. My queries ends up looking like this:

WO WOL WOLR WOLD
226952 10000 10000 10000
226952 10000 10000 20000
226952 10000 10000 30000
226952 10000 10000 40000
226952 10000 20000 10000
226952 10000 20000 20000
226952 10000 20000 30000
226952 10000 20000 40000
399999 10000 NULL 10000
375654 10000 10000 NULL
etc


Hierarchy:
WO > WOL > WOLD
WO > WOL > WOLR

It probobly isn't best practice, but I'm kinda new so I need some guidance. I'd really appreciate any help! Here's my query:

SELECT [Work Order Header].No_ AS WO_No, [Work Order Line].[Line No_] AS WOL_No,
[Work Order Requisition].[Line No_] AS WOLR_No, [Work Order Line Detail].[Line No_] AS WOLD_No
FROM [Work Order Header] LEFT OUTER JOIN
[Work Order Line] ON [Work Order Header].No_ = [Work Order Line].[Work Order No_] LEFT OUTER JOIN
[Work Order Line Detail] ON [Work Order Line].[Work Order No_] = [Work Order Line Detail].[Work Order No_] AND
[Work Order Line].[Line No_] = [Work Order Line Detail].[Work Order Line No_] LEFT OUTER JOIN
[Work Order Requisition] ON [Work Order Line].[Work Order No_] = [Work Order Requisition].[Work Order No_] AND
[Work Order Line].[Line No_] = [Work Order Requisition].[Work Order Line No_]

View 1 Replies View Related

Millisecond Values Missing When Inserting Datetime Into Datetime Column Of Sql Server

Jul 9, 2007

Hi,
I'm inserting a datetime values into sql server 2000 from c#

SQL server table details
Table nameate_test
columnname datatype
No int
date_t DateTime

C# coding
SqlConnection connectionToDatabase = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=SSPI");
connectionToDatabase.Open();
DataTable dt1 = new DataTable();
dt1.Columns.Add("no",typeof(System.Int16));
dt1.Columns.Add("date_t", typeof(System.DateTime));
DataRow dr = dt1.NewRow();
dr["no"] = 1;
dr["date_t"] = DateTime.Now;
dt1.Rows.Add(dr);
for(int i=0;i<dt1.Rows.Count;i++)
{
string str=dt1.Rows["no"].ToString();
DateTime dt=(DateTime)dt1.Rows["date_t"];
string insertQuery = "insert into date_test values(" + str + ",'" + dt + "')";
SqlCommand cmd = new SqlCommand(insertQuery, connectionToDatabase);
cmd.ExecuteNonQuery();
MessageBox.Show("saved");
}
When I run the above code, data is inserted into the table
The value in the date_t column is 2007-07-09 22:10:11 000.The milliseconds value is always 000 only.I need the millisecond values also in date_t column.
Is there any conversion needed for millisecond values?

thanks,
Mani

View 3 Replies View Related

Inserting Datetime Through Sqldatasource - String Was Not Recognized As A Valid DateTime

Dec 6, 2006

I'm getting error:
String was not recognized as a valid DateTime.
my insert parameter: 
<asp:Parameter Name="LastModified" Type="DateTime" DefaultValue= "<%=DateTime.Now.ToString() %>"
my insert command:
InsertCommand="INSERT INTO [Product] ([Enabled], [ProductCode], [ProductName], [ProductAlias], [CarrierId], [DfltPlanId], [DoubleRating], [DoubleRateProductId], [ConnCharges], [StartDate], [EndDate], [Contracted], [BaseProductId], [LastModified], [LastUser]) VALUES (@Enabled, @ProductCode, @ProductName, @ProductAlias, @CarrierId, @DfltPlanId, @DoubleRating, @DoubleRateProductId, @ConnCharges, @StartDate, @EndDate, @Contracted, @BaseProductId, @LastModified, @LastUser)"
LastModified is a datetime field.
 Running sql2005

View 1 Replies View Related

DateTime Unable To Save In Datetime Field Of SQL Database

Mar 14, 2007

 Hi all, having a little problem with saving dates to sql databaseI've got the CreatedOn field in the table set to datetime type, but every time i try and run it i get an error kicked up  Error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated."I've tried researching it but not been able to find something similar.  Heres the code: DateTime createOn = DateTime.Now;string sSQLStatement = "INSERT INTO Index (Name, Description, Creator,CreatedOn) values ('" + name + "','" + description + "','" + userName + "','" + createOn + "')"; Any help would be much appreciated 

View 4 Replies View Related

SQL Query: Finding Records Between Datetime Inside Datetime

Mar 17, 2007

Hey :)I'm facing a lot of troubles trying to create a new pause/break-system. Right now i'm building up the query that counts how many records that is inside 2 fields. Let me first show you my table:
ID (int)     |    stamp_start (Type: DateTime)        |      stamp_end (Type: DateTime)           |      Username (varchar)0             |      17-03-07 12:00:00                      |            17-03-07 12:30:00                     |     Hovgaard
The client will enter a start time and a end time and this query should then count how many records that are inside this periode of time.
 Example: The client enter starttime: 12:05 and endtime: 12:35.The query shall then return 1 record found. The same thing if the user enters 12:20 and 12:50.My current query looks like this:SELECT COUNT(ID) AS Expr1 FROM table WHERE (start_stamp <= @pausetime_start) AND (end_stamp >= @pausetime_end)But this will only count if I enter the exact same times as the one inside the table.Any ideas how I can figure this out?Thanks for your time so far :)/Jonas Hovgaard - Denmark

View 2 Replies View Related

Datetime Data Type Resulted In An Out-of-range Datetime Value. Please Help

May 13, 2006

Hi,
I have a column of type datetime in sqlserver 2000. Whenever I try to insert the date
 '31/08/2006 23:28:59'
 I get the error "...datetime data type resulted in an out-of-range datetime value"
I've looked everywhere and I can't solve the problem. Please note, I first got this error from an asp.net page and in order to ensure that it wasn't some problem with culture settings I decided to run the query straight in Sql Query Anaylser. The results were the same. What else could it be?
cheers,
Ernest

View 2 Replies View Related

Convert Datetime String To Datetime Date Type

Mar 11, 2014

I am inserting date and time data into a SQL Server 2012 Express table from an application. The application is providing the date and time as a string data type. Is there a TSQL way to convert the date and time string to an SQL datetime date type? I want to do the conversion, because SQL displays an error due to the

My date and time string from the application looks like : 3/11/2014 12:57:57 PM

View 1 Replies View Related

Retrieving A Datetime With A Time Of Midnight (from A Typical Datetime)

Sep 7, 2007

Nothing difficult, I just need a way to generate a new datetime column based on the column [PostedDate], datetime. So basically I want to truncate the time. Thanks a lot.

View 5 Replies View Related

Datetime W/ Format = D Still Showing Time Component Of Datetime

Jan 17, 2008

e.g.

1st March 2005 12:00:00

is showing as

01/03/2005 00:00:00

instead of

01/03/2005


Why does this happen?

View 4 Replies View Related

Comparing A Real Datetime To A 'constructed' Datetime

Jun 15, 2004

I have the following SQL:

select convert(datetime,'04-20-' + right(term,4)) as dt,
'Deposit' as type, a.* from
dbo.status_view a

where right(term,4) always returns a string which constitutes a 4 digit year eg '1999','2004',etc.

The SQL above returns

2004-04-20 00:00:00.000 Deposit ...

Which makes me think that it is able to successfully construct the datetime object inline. But then when I try and do:

select * from
(
select convert(datetime,'04-20-' + right(term,4)) as dt,
'Deposit' as type, a.* from
dbo.status_view a
) where dt >= a.submit_date

I get the following error:

Syntax error converting datetime from character string.

Given that it executes the innermost SQL just fine and seems to convert the string to a datetime object, I don't see why subsequently trying to USE that datetime object for something (in this case comparison with submit_date which is a datetime in the table a) should screw it up. Help!!! Thanks...

View 6 Replies View Related

How To Convert Datetime From Text/char To Datetime

Jul 20, 2005

Hi,I have a text file that contains a date column. The text file will beimported to database in SQL 2000 server. After to be imported, I wantto convert the date column to date type.For ex. the text file look likeName dateSmith 20003112Jennifer 19991506It would be converted date column to ydm database in SQL 2000 server.In the table it should look like thisName DateSmith 2000.31.12Jennifer 1999.15.06Thanks in advance- Loi -

View 1 Replies View Related

Convert DateTime To A DateTime With Milliseconds Format

Nov 5, 2007

Hi,

I am trying to access a date column up to millisecond precession. So I cast date to as follows:



Code BlockCONVERT(varchar(23),CREATE_DATE,121)


I get millisecond part as a result of query but it€™s €œ000€?.

When I try to test the format by using getDate instead of DateTime column I get right milliseconds.





CONVERT(varchar(23),GetDate(),121) --Gives right milliseconds in return

View 4 Replies View Related

How To Convert Datetime From Varchar To Datetime

Sep 11, 2007

hi,
How do i convert a varchar field into the datetime data type? the reason i need this lies in the requirement that in the earlier data base the column that is hlding the date value is having the data type as varchar. and in the new design the column data type is datetime. i am using sql scripts for the data migration from the older design to the newer and got stuck with this datetime convertion issue. do let me know the best possible solution.

following are the sample data that is theer in the older table for the date.


12/12/2003
1/13/2007
01132004
1-1-2004
1.2.2001



there is no uniformity of the data that is stored currently.



thnkx in adv.
rahul jha

View 11 Replies View Related

Transact SQL :: Difference Between Datetime In One Row And Datetime In The Row Above

May 21, 2015

I have a table that has a unique ID and a datetime of when something changed.

See example:
ID    TimeStamp
16094    2013-11-25 11:46:38.357
16095    2013-11-25 11:46:38.430
16096    2013-11-25 11:46:38.713
16097    2013-11-25 11:46:38.717
16098    2013-11-25 11:46:38.780

[Code] ....

Is there a way I can calculate the difference between row 16106 and 16105 and enter it in line 10601.

View 10 Replies View Related

How To Get Starting Datetime(monday) Of The Week And Ending Datetime Of The Week(sunday)

May 2, 2007

hi friends,



how to get the date of the first/last day of the week in sql...

can any one help me





Cheers,

raj

View 5 Replies View Related

Transact SQL :: Calculate DateTime Column By Merging Values From Date Column And Only Time Part Of DateTime Column?

Aug 3, 2015

How can I calculate a DateTime column by merging values from a Date column and only the time part of a DateTime column?

View 5 Replies View Related

Getting Error : : The Conversion Of A Char Data Type To A Datetime Data Type Resulted In An Out-of-range Datetime Value

Jan 28, 2008

update tblPact_2008_0307 set student_dob = '30/01/1996' where student_rcnumber = 1830when entering update date in format such as ddmmyyyyi know the sql query date format entered should be in mmddyyyy formatis there any way to change the date format entered to ddmmyyyy in sql query?

View 5 Replies View Related

DateTime -&> MSSQL -&> DateTime

Jun 9, 2008

Hi All,This is only my second day using C#/asp.net and English isn't my native language so I'll apologise in advance if this question doesn't make sense and/or is stupid . I'm trying to make a little event planner which was going well until I hit a small problem, the user needs to enter the event name and choose a date/time from dropdowns, this bit works okay... however I'm having difficulties with storing the date/time, at the moment I'm making a DateTime object and filling out the year/month/day/hour/minute selected on the form and adding that to the database field (which is a datetime field type).Problem is, I'm using the date format DD/MM/YYYY HH:MM:SS but the database stores it as MM/DD/YYYY HH:MM:SS so if I wanted to do things like:
select * from tbl where date > DateTime.Now - it isn't going to work because the month is switched with the day in the DB-versions.
Just to try and give another example, if I'm not being very clear, if I print DateTime.Now.ToString() it will display 10/06/2008 02:50:48 however if I put it into the database and pull it back out cast to a DateTime Object and then display that object via ToString() it'll be 06/10/2008 02:50:48
Any suggestions on what to do would be appreciated, usually in cases like this I'd just use the unix timestamp, but since C#/ASP.NET doesn't support that natively I was hoping there was an easier/native alternative. Also I don't have access to the server configuration so changing the localization of mssql isn't an option unfortunately.Thanks in advance!

View 7 Replies View Related

Grouping Twice

May 11, 2008

Hi there, i have an SQL query which select the number of products and display them per sub_cat_id e.g.
 7  french dressers3   spanish dressers1   english dresser
 However what i want to do is then group those under the the main category (cat_id)
All descriptions are held in tbl_cat and and main category and sub category can be found by the cat_cat colum, if there is an M in this colum it means it is a main category e.g. beds, tables, if there is the name of a M category then it is a sub cat e.g. double beds, single beds etc.
Can anybody help me with my grouping nightmare?
this is the code i have so far
SELECT     COUNT(tbl_stock.Stock_ID) AS TOTALOFSTOCK, tbl_stock.sub_cat_id, tbl_cat.Cat_DescriptionFROM         tbl_stock INNER JOIN                      tbl_cat ON tbl_stock.sub_cat_id = tbl_cat.Category_IDGROUP BY tbl_cat.Cat_Description, tbl_stock.sub_cat_id

View 1 Replies View Related

Need Some Help With Grouping (I Think...)

Jun 13, 2008

I have a table which lists manufacturers' products. Users are allowed to vote for the most popular item belonging to the manufacturer. Moderators assign the products to manufacturers so on occassion they may accidently (or deliberately) get it wrong. For this reason, the table also acts as the ChangeLog so if choose, I could instantly decide whether all changes made by a specific user should be dismissed. Product | Manufacturer | NoOfVotes | ChangedBy | ChangedTime
============ ============== =========== =========== =============
XBOX 360 Microsoft 25* Dic 05/03/2008
XBOX 360 Sony 1 Tom 04/03/2008
Playstation Sony 100* Dic 03/03/2008
XBOX 360 Microsoft 25* Dic 02/03/2008
XBOX 360 Sony 1 Harry 01/03/2008
 

 I'm using ID fields for Product, Manufacturer and ChangedBy which are obtained from different tables but have simplified the table to make it easier to read.
I need to retrieve each product in the table, the last Manufacturer assigned to it, with a total of the votes where the product-manufacturer match. The results should be: Product | Manufacturer | TotalVotes | LastChanged
============ ============== ============ =============
XBOX 360 Microsoft 50 05/03/2008
Playstation Sony 100 03/03/2008
 
Any help would be greatly appreciated.
Thanks, Pete.

View 3 Replies View Related

HAVING / GROUPING Help

Jul 10, 2007

Hello, All,

Here's the query I'm attempting to execute:


Code:

SELECT LEA, Count(SSN)
FROM WorkData2003_04.dbo.Students --Database and Table Name
WHERE Grade_Level='10' AND SSN NOT IN(

SELECT SSN
FROM WorkData2003_04.dbo.Students --Database and Table Name
WHERE Grade_Level='09')



However, SQL returns the following error:
Msg 8120, Level 16, State 1, Line 1
Column 'WorkData2003_04.dbo.Students.lea' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.


I'm trying to generate a count of SSNs by LEA (LEA is the same thing as a school) that exist one school year but do not exist in the next school year (essentially students that transfer OUT of a school district).

Could someone provide assistance? I think I need to incorporate the HAVING clause but I'm not for sure...

Thanks!
Cody

View 6 Replies View Related

Grouping

Jun 22, 2004

I'm trying to write a report and need to group columns that are alike.
For example.

DeptID JobTitle

40344 Sales Clerk
1st Assistant
Store Manager

40666 Sales Clerk
2nd Assistant
Store Manager


Sorry, it will not output correctly, I hope you get what I'm trying to do.
I can get the results above but it puts the deptid for each job title. I do not want it. Any help will be appreciated. Thanks in advance.

View 6 Replies View Related

Need Help With Grouping !!!

Nov 15, 2005

Hi !

I have a log table like this :

UserID LoginDate
------ --------------
31 2005-11-01
31 2005-11-05
8 2005-11-02
31 2005-11-02
7 2005-11-04


I need to get the LAST login date for each user as the following result :

7 2005-11-04
8 2005-11-02
31 2005-11-05

Can someone help me please ?

Thanks !

View 2 Replies View Related

Grouping

Apr 19, 2008

I have 2 columns

RecordDate(DateTime)
Quantity(Int)

I would like to group the data quarter wise like,

Quarter 1 500
Quarter 2 340
Quarter 3 450
Quarter 4 400

Note: Say quarters are fixed from Jan-Mar,Apr-Jun etc.,



Prakash.P
The secret to creativity is knowing how to hide your sources!

View 2 Replies View Related

Grouping 1 Off

Feb 23, 2006

I am writing a report from an historical database that uses posting_times. The way the posting works is if something has a posting time of 01/01/97 00:00:00 it means that the record covers from 12/31/96 00:00:00 to 01/01/97 00:00:00.

This is where my problem is at. The report i am writing needs to be grouped by Month. Before i figured out how the posting dates worked i was using ... DATEPART(month, posting_time) AS monthDate ... for grouping purposes in the report.

Now that i have figured out how the posting dates work i am at a total loss as how to group this. I am using SQL Reporting Services 2000 to write this report.
Any help would be greatly appreciated.
Thanks
Mitch

View 5 Replies View Related

Top N From Each Grouping?

Mar 5, 2007

Is it possible to return just the top row of each group within a query result?

Par example, if I have a query that returns a list of products, grouped by order date and product name and ordered by date, name desc

How can I just get back the top row within each date grouping so that I can list the latest prod order per prod?

Thank you for any tips!

--PhB

View 20 Replies View Related

Not Grouping Right

Sep 19, 2007

its showing the promotion group not grouped right can you help


--#ttTransaction
SELECT ShipToID, Trans.StoreID, TransactionNumber, BatchNumber, [Time], CustomerID, CashierID,
CASE WHEN Trans.StoreID IN (172,173) THEN Total*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE CASE WHEN Trans.StoreID = 113
THEN CASE WHEN [Time] < '5/21/2005' THEN Total*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE Total END
ELSE Total END END AS Total,
CASE WHEN Trans.StoreID IN (172,173) THEN SalesTax*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE CASE WHEN Trans.StoreID = 113
THEN CASE WHEN [Time] < '5/21/2005' THEN SalesTax*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE SalesTax END
ELSE SalesTax END END AS SalesTax,
Comment, ReferenceNumber,
Status, ExchangeID, ChannelType, RecallID, RecallType,
CASE WHEN Trans.[Time] >= SO.ShiftDate THEN 'Same' ELSE 'New' END AS SalesType
INTO #ttTransaction
FROM QSCHQ.dbo.[Transaction] Trans
LEFT JOIN Reporting.dbo.RetailSalesComparison_StoreOpenings SO ON Trans.StoreID = SO.StoreID
WHERE YEAR([Time]) >= YEAR(GETDATE())-1



--#ttTransactionEntry
SELECT TE.Commission,
CASE WHEN TE.StoreID IN (172,173) THEN TE.Cost*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE CASE WHEN TE.StoreID = 113
THEN CASE WHEN [Time] < '5/21/2005' THEN TE.Cost*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE TE.Cost END
ELSE TE.Cost END END AS Cost,
CASE WHEN TE.StoreID IN (172,173) THEN TE.FullPrice*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE CASE WHEN TE.StoreID = 113
THEN CASE WHEN [Time] < '5/21/2005' THEN TE.FullPrice*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE TE.FullPrice END
ELSE TE.FullPrice END END AS FullPrice,
TE.StoreID, TE.[ID], TE.TransactionNumber, TE.ItemID,
CASE WHEN TE.StoreID IN (172,173) THEN TE.Price*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE CASE WHEN TE.StoreID = 113
THEN CASE WHEN [Time] < '5/21/2005' THEN TE.Price*CONVERT(FLOAT,(SELECT Value FROM DelSol.dbo.Parameter WHERE ID = 4))
ELSE TE.Price END
ELSE TE.Price END END AS Price,
TE.PriceSource, TE.Quantity, TE.SalesRepID, TE.Taxable, TE.DetailID, TE.Comment,
TE.AutoID, TE.DiscountReasonCodeID, TE.ReturnReasonCodeID, TE.TaxChangeReasonCodeID,
TE.SalesTax, TE.QuantityDiscountID
INTO #ttTransactionEntry
FROM QSCHQ.dbo.TransactionEntry TE
INNER JOIN #ttTransaction Trans
ON TE.StoreID = Trans.StoreID
AND TE.TransactionNumber = Trans.TransactionNumber
WHERE YEAR([Time]) >= YEAR(GETDATE())-1



--#ttTransactionWithPesoConversionAndCustomerAccount
SELECT Trans.StoreID, QSTStore.StoreGroupID, Trans.TransactionNumber, Trans.[Time], Customer.AccountNumber, Customer.Company,
Trans.Total, Trans.SalesTax, Trans.CashierID, Trans.SalesType
INTO #ttTransactionWithPesoConversionAndCustomerAccount
FROM #ttTransaction Trans
INNER JOIN QSCHQ.dbo.Customer Customer ON Trans.CustomerID = Customer.ID AND 1 = Customer.GlobalCustomer
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON Trans.StoreID = QSTStore.StoreID

UNION ALL

SELECT Trans.StoreID, QSTStore.StoreGroupID, Trans.TransactionNumber, Trans.[Time], Customer.AccountNumber, Customer.Company,
Trans.Total, Trans.SalesTax, Trans.CashierID, Trans.SalesType
FROM #ttTransaction Trans
INNER JOIN QSCHQ.dbo.Customer Customer ON Trans.CustomerID = Customer.ID AND Trans.StoreID = Customer.StoreID AND 1 <> Customer.GlobalCustomer
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON Trans.StoreID = QSTStore.StoreID

UNION ALL

SELECT Trans.StoreID, QSTStore.StoreGroupID, Trans.TransactionNumber, Trans.[Time], Customer.AccountNumber, Customer.Company,
Trans.Total, Trans.SalesTax, Trans.CashierID, Trans.SalesType
FROM #ttTransaction Trans
LEFT JOIN QSCHQ.dbo.Customer Customer ON Trans.CustomerID = Customer.ID AND Trans.StoreID = Customer.StoreID
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON Trans.StoreID = QSTStore.StoreID
WHERE Customer.[ID] IS NULL
AND Trans.CustomerId < 100000

UNION ALL

SELECT Trans.StoreID, QSTStore.StoreGroupID, Trans.TransactionNumber, Trans.[Time], Customer.AccountNumber, Customer.Company,
Trans.Total, Trans.SalesTax, Trans.CashierID, Trans.SalesType
FROM #ttTransaction Trans
LEFT JOIN QSCHQ.dbo.Customer Customer ON Trans.CustomerID = Customer.ID
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON Trans.StoreID = QSTStore.StoreID
WHERE Customer.[ID] IS NULL
AND Trans.CustomerId > 100000



--#ttRetailSales_ByStore_ByCustomer_ByDay
SELECT CONVERT(DATETIME, CONVERT(CHAR, [Time], 101)) AS [Date],
Trans.StoreID, Trans.StoreGroupID,
Trans.AccountNumber, Trans.Company,
SUM(TE.Price*TE.Quantity) AS Sales,
COUNT(DISTINCT Trans.TransactionNumber) AS TRXCount,
SUM(TE.Quantity) AS UnitsSold, Trans.SalesType
INTO #ttRetailSales_ByStore_ByCustomer_ByDay
FROM #ttTransactionWithPesoConversionAndCustomerAccount Trans
INNER JOIN #ttTransactionEntry TE
ON Trans.StoreID = TE.StoreID AND Trans.TransactionNumber = TE.TransactionNumber
WHERE (Trans.Total - Trans.SalesTax) <> 0
GROUP BY Trans.AccountNumber, Trans.StoreGroupID, CONVERT(DATETIME, CONVERT(CHAR, Trans.[Time], 101)),
Trans.StoreID, Trans.Company, Trans.SalesType

-- DROP TABLE #ttTransaction
-- DROP TABLE #ttTransactionEntry
-- DROP TABLE #ttTransactionWithPesoConversionAndCustomerAccount

-- ***** #ttTransGroup *****
SELECT [Date], PromotionGroupID,AccountNumber, SUM(Total) AS Total, SUM(TRXCount) AS TRXCount, SalesType
INTO #ttTransGroup
FROM
(SELECT [Date],
QSTStore.PromotionGroupID, Trans.AccountNumber,
Sales AS Total,
TRXCount, SalesType
FROM #ttRetailSales_ByStore_ByCustomer_ByDay Trans
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON Trans.StoreID = QSTStore.StoreID
WHERE Trans.AccountNumber LIKE 'C-%'

UNION ALL

SELECT TransactionDate AS [Date], QSTStore.PromotionGroupID, AccountNumber, SUM(Amount) AS Total, 0 AS TRXCount,
CASE WHEN QuickSellSalesAdjustment.[TransactionDate] >= SO.ShiftDate THEN 'Same' ELSE 'New' END AS SalesType
FROM DelSol.dbo.QuickSellSalesAdjustment QuickSellSalesAdjustment
INNER JOIN QSCHQ.dbo.QSTStore QSTStore ON QuickSellSalesAdjustment.StoreID = QSTStore.StoreID
LEFT JOIN Reporting.dbo.RetailSalesComparison_StoreOpenings SO ON QuickSellSalesAdjustment.StoreID = SO.StoreID
WHERE YEAR(TransactionDate) >= YEAR(GETDATE())-1
GROUP BY AccountNumber, QSTStore.PromotionGroupID, TransactionDate,
CASE WHEN QuickSellSalesAdjustment.[TransactionDate] >= SO.ShiftDate THEN 'Same' ELSE 'New' END) ttTemp
GROUP BY AccountNumber, PromotionGroupID, [Date], SalesType
HAVING SUM(ttTemp.Total) <> 0


-- ***** #ttCSVF *****
SELECT CSVFlag.TransactionDate, CSVFlag.StoreGroupID, CSVFlag.AccountNumber, CSVFlagType.[Description]
INTO #ttCSVF
FROM DelSol.dbo.CruiseShipVisitFlag AS CSVFlag
INNER JOIN DelSol.dbo.CruiseShipVisitFlagType AS CSVFlagType ON CSVFlagType.ID = CSVFlag.FlagTypeID



-- ***** Main *****
SELECT ttTransGroup.[Date] as TransactionDate,
QSTPromoStoreGroup.[ID] AS PromoGroupID, QSTPromoStoreGroup.StoreGroup AS PromoGroup,
ttTransGroup.AccountNumber AS AccountNumber, CruiseShip.ShipName AS ShipName,
CruiseShipGroup.[Description] AS ShipLine, CruiseShipCompany.[Description] AS PortLecturerCompany,
Sum(ttTransGroup.Total) AS GroupSales,
(CSVP.AdjustedProjection) AS Projection,
CruiseShip.Capacity, CASE WHEN CruiseShip.Capacity = 0 THEN 0 ELSE ttTransGroup.Total/CruiseShip.Capacity END AS ASPP,
CASE WHEN CONVERT(DECIMAL, CruiseShip.Capacity) = 0 THEN 0 ELSE CONVERT(DECIMAL, ttTransGroup.TRXCount)/CONVERT(DECIMAL, CruiseShip.Capacity) END AS Yield,
ttTransGroup.TRXCount, CASE WHEN ttTransGroup.TRXCount=0 THEN 0 ELSE ttTransGroup.Total/ttTransGroup.TRXCount END AS ADPT,
CruiseShipPortLecturer.[Name] AS PortLecturer,
CSVF.[Description] AS Flag, ttTransGroup.SalesType
FROM QSCHQ.dbo.QSTPromoStoreGroup QSTPromoStoreGroup
INNER JOIN #ttTransGroup ttTransGroup ON QSTPromoStoreGroup.[ID] = ttTransGroup.PromotionGroupID
INNER JOIN DelSol.dbo.CruiseShip CruiseShip ON ttTransGroup.AccountNumber = CruiseShip.AccountNumber
INNER JOIN DelSol.dbo.CruiseShipCompany CruiseShipCompany ON CruiseShip.PromotionCompany = CruiseShipCompany.[ID]
INNER JOIN DelSol.dbo.CruiseShipGroup CruiseShipGroup ON CruiseShip.GroupID = CruiseShipGroup.[ID]
LEFT JOIN DelSol.dbo.CruiseShipPortLecturer CruiseShipPortLecturer
ON CruiseShip.AccountNumber = CruiseShipPortLecturer.AccountNumber
AND ttTransGroup.[Date] BETWEEN CruiseShipPortLecturer.StartDate
AND CASE WHEN CruiseShipPortLecturer.EndDate IS NULL THEN '12/31/2099' ELSE CruiseShipPortLecturer.EndDate END

LEFT JOIN DelSol.dbo.CruiseShipVisitProjection CSVP
ON CSVP.TransactionDate= ttTransGroup.[Date]
AND CSVP.StoreGroupID = QSTPromoStoreGroup.[ID]
AND CSVP.AccountNumber = ttTransGroup.AccountNumber
LEFT JOIN #ttCSVF CSVF
ON CSVF.TransactionDate = ttTransGroup.[Date]
AND CSVF.StoreGroupID = QSTPromoStoreGroup.[ID]
AND CSVF.AccountNumber = ttTransGroup.AccountNumber
WHERE QSTPromoStoreGroup.ReceivesCruiseShips = 1
AND CSVF.[Description] IS NULL
Group By ttTransGroup.AccountNumber, QSTPromoStoreGroup.[ID],QSTPromoStoreGroup.StoreGroup,
ttTransGroup.[Date],
CruiseShip.ShipName,
CruiseShipGroup.[Description], CruiseShipCompany.[Description],
(CSVP.AdjustedProjection),
CruiseShip.Capacity, CASE WHEN CruiseShip.Capacity = 0 THEN 0 ELSE ttTransGroup.Total/CruiseShip.Capacity END,
CASE WHEN CONVERT(DECIMAL, CruiseShip.Capacity) = 0 THEN 0 ELSE CONVERT(DECIMAL, ttTransGroup.TRXCount)/CONVERT(DECIMAL, CruiseShip.Capacity) END,
ttTransGroup.TRXCount, CASE WHEN ttTransGroup.TRXCount=0 THEN 0 ELSE ttTransGroup.Total/ttTransGroup.TRXCount END,
CruiseShipPortLecturer.[Name],
CSVF.[Description], ttTransGroup.SalesType
Order by QSTPromoStoreGroup.StoreGroup

View 3 Replies View Related

Grouping

Jan 20, 2008

SQL2000. I have a table as follows. Table shows a log of solutions posted by agents. For example, Ticket#5 was replied once by each agent A,B and C.
==========================
ticket_number || agent || solution
==========================

5 || A || test
5 || B || test
5 || C || test
7 || B || test
7 || C || test
8 || C || test
9 || B || test

I need to find out number of all ticket solutions/counts (how many ticket was touched by all agents) but in format related to the single agent:

AGENT TICKET_NUMBER COUNT
A 5 3
B 5 3
C 5 3
B 7 2
C 7 2
.....

How could I achieve this?

Thank you much!
Julia

View 7 Replies View Related

Grouping

Jan 6, 2008



Hi

I have created a table and linked it to a dataset and grouped the data based on a field called SYSTEM.

Now in the group footer I have to display summary values for each system from another dataset.

But it always gives me the First Value in that. That is for all the groupings I get the summary value for the first system

only. How do I go about this.

Thanks

Sai

View 2 Replies View Related

Grouping

Dec 21, 2006

Hi,

I have a stored procedure which is returning results in the following format:

No.of substances Count

1 29

2 89

3 876

.. ..

15 56

16 89

Now i need to display like this:

No.of substances Count %

1 20

2 89

.. ..

>=9 8766

Total

All the substances which are >=9 have display no.of substances =>9 and Count is sum of all counts which have the no.of substances>=9

How to achieve this

Thanks in advance



View 1 Replies View Related

Grouping/Sum

Jun 28, 2007

The report I'm designing has a number of records in it, but two main fields that I'm concerned with Budget, and spent.



for example



Budget Spent


75 5
75 10
75 8________________
Total 225 23

The spent records are all unique, but the budget record is the same field repeating itself over and over. I've used a grouping to eliminate the repetition of the Budget amount, but the total still comes out to be incorrect. It now looks like this


Budget Spent
75
5
10
8________________
Total 225 23

Is there a way which I can add the values that are displayed rather than the underlying values?

Please Help!
Thanks,
-Shahin

View 4 Replies View Related







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