GROUPING A TABLE BASED ON MULTIPLE FIELDS - sql

I have a table with following format
Now i am using Access and want to create a table which will provide me sum of units where Segment is commercial, at the same time I just want to sum Subregions where they are same..means MCA+MCA+MCA... Also the period should be same where we have added them..means 2013Q1 should be added too 2013Q1 only and grouped in that format.
Something like below
Thanks and Regards

The following query totals the unit while grouping on the other fields. To change the range that it totals over, you will either be adding a WHERE clause or you will change the fields that it is GROUP BY
SELECT [Sub Region], [Corporate Family], [HP Segment], [Product Category], [Period], Sum([Units])
FROM TableName
GROUP BY [Sub Region], [Corporate Family], [HP Segment], [Product Category], [Period]

Related

mssql: add column with the same value for all rows to search results

I have my query:
SELECT [Shipment Date], [Amount] as [Running Costs], Sum([Amount]) OVER
(ORDER BY [Shipment Date]) as [Total Running Costs]
FROM...
This gets me 3 columns:
Shipment Date | Running Costs | Total Running Costs
I would like to add a fourth column to this query which has the same value for all rows, and the same number of rows as my original query results.
I know you could add for example '999'as Something to the search results, but how can I do the same for a sum of another column (example: Imagine the total sum of the a column in another table is 1500, and I want to have 1500 for all rows in the fourth column. Something like select sum(column_name)?
The database engine is MSSQL.
You can use a nested query
SELECT [Shipment Date], [Amount] as [Running Costs], [Total Running Costs], SUM([Total Running Costs] OVER ())
FROM
(
SELECT [Shipment Date], [Amount] as [Running Costs], Sum([Amount]) OVER
(ORDER BY [Shipment Date]) as [Total Running Costs]
FROM...
)
Nested window function should also work
SUM(SUM([Running costs]) OVER (ORDER BY [Shipment Date])) OVER ()

MS ACCESS: Unable to retrieve LAST Price Paid based on Maximum Date

OBJECTIVE
Develop a sales catalog for a COMPANY ID based on ITEM ID and latest PRICE paid (based on LAST SHIP DATE).
APPROACH
Pull in CUSTOMER, SALES, ITEM Tables
Run Query Link tables based off of CUSTOMER ID and ITEM to understand purchase history
Export a table showing a COMPANY ID, ITEM ID, LAST SALES PRICE, LAST SHIP DATE
CODE
SELECT
[Sales Order Details (F42119)].SDAN8 AS [COMPANY ID],
[Sales Order Details (F42119)].SDITM AS [ITEM ID],
[Sales Order Details (F42119)].SDAITM AS STYLE,
(CCur([SDLPRC])/10000) AS PRICE,
Max([Sales Order Details (F42119)].SDDRQJ) AS [LAST SHIP DATE]
INTO [Table - Sales Details]
FROM [Sales Order Details (F42119)]
GROUP BY
[Sales Order Details (F42119)].SDAN8,
[Sales Order Details (F42119)].SDITM,
[Sales Order Details (F42119)].SDAITM,
(CCur([SDLPRC])/10000);
ISSUE/QUESTION
CUSTOMER A bought ITEM ABC # 3 different prices on 3 different dates. I've taken the Max of Ship Date in hope to show the LAST PRICE PAID (resulting in one single value for price). However, for some reason, I am still receiving the three different prices on three different dates. How can I have MS Access only display the latest price based off of the latest ship date?
NOTE: SDLPRC = "Sold Price". I have to convert SLDPRC into a Currency and then divide by 1000; this is due to our current database setup. Also, SDAITM is an "Abbreviated Item Number" that is more customer-friendly.
The problem is that you're grouping by your Price variable (CCur([SDLPRC])/10000). When you use GROUP BY, Access/SQL will split the rows by all the variables in the GROUP BY statement. So you need to not group by price.
Change your query to use a subquery that finds the last date of a sale grouped by [Company ID], [Item ID] and Style. The use an outer query to grab the price for that particular record. Something like:
SELECT b.[COMPANY ID], b.[ITEM ID], b.STYLE, b.[LAST SHIP DATE], CCur(a.[SDLPRC])/10000 as PRICE
INTO [Table - Sales Details]
FROM [Sales Order Details (F42119)] as a
INNER JOIN
(SELECT
[Sales Order Details (F42119)].SDAN8 AS [COMPANY ID],
[Sales Order Details (F42119)].SDITM AS [ITEM ID],
[Sales Order Details (F42119)].SDAITM AS STYLE,
Max([Sales Order Details (F42119)].SDDRQJ) AS [LAST SHIP DATE]
FROM [Sales Order Details (F42119)]
GROUP BY
[Sales Order Details (F42119)].SDAN8,
[Sales Order Details (F42119)].SDITM,
[Sales Order Details (F42119)].SDAITM
) as b
ON a.SDAN8 = b.[COMPANY ID]
and a.SDITM = b.[ITEM ID]
and a.SDAITM = b.STYLE
and a.SDDRQJ = b.[LAST SHIP DATE]

Extract a specific line from a SELECT statement based on the last Trasanction date

Good day,
I have an SQL code that return to me all quantities that I received over time, but I want to display only the latest one
SELECT * FROM
(SELECT DISTINCT
[dbo].[ttcibd001110].[t_cmnf] AS [Manufacturer],
[dbo].[ttcibd001110].[t_item] AS [Item code],
[dbo].[ttcibd001110].[t_dsca] AS [Description],
[dbo].[ttcibd001110].[t_seak] AS [Search key 1],
[dbo].[twhinr110110].[t_trdt] AS [Transaction date],
[dbo].[twhinr110110].[t_cwar] AS [Warehouse],
[dbo].[twhinr110110].[t_qstk] AS [Quantity Inventory Unit]
FROM [dbo].[twhinr110110] LEFT JOIN [dbo].[ttcibd001110]
ON [dbo].[twhinr110110].[t_item]=[dbo].[ttcibd001110].[t_item]
WHERE [dbo].[twhinr110110].[t_koor]='2' AND [dbo].[ttcibd001110].[t_cmnf]='ManufacturerX') AS tabel
WHERE ltrim(tabel.[Item code])='1000045'
Now, from this selection I want to select only the line with the latest Transaction date, but I am stuck.
Can somebody help me in this way?
Thank you!
Change your beginning to
SELECT TOP 1
and after where use
ORDER BY [Transaction date] DESC

Error in SQL sum()

I have this SQL line
SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line]
WHERE [Item Category Code] = '5104' GROUP BY No_
But i got this error for my script.
Column 'dbo.3S Company A_S$Sales Invoice Line.Shipment Date' is invalid in the select
list because it is not contained in either an aggregate function or the GROUP BY clause.
Can anyone help me with why?
If you use GROUP BY in your query, only the columns used in your grouping clause and any aggregate functions like SUM are allowed in the select list. In your case, you specify GROUP BY No_, so that is the only column you can select without using an aggregate function.
If you want to get the remaining columns, you could select No_ and the other aggregate columns in a subquery and then select other columns by matching the No_ column with the corresponding column in subquery.
The error means you have a column which may have multiple values when grouped and SQL doesn't know which value to select in the column
You cn use e.g. min() to select min value. Like this
SELECT No_,
sum(Quantity) AS Sold,
min([Shipment Date]) AS SoldDate,
min([Item Category Code]),
min(Description),
min([Description 2])
FROM dbo.[3S Company A_S$Sales Invoice Line]
WHERE [Item Category Code] = '5104'
GROUP BY No_
Or read about aggregate functions to choose proper one
BWT it's not MySQL but rather MS SQL (MySQL does not complain the column usages)
TRY THIS
SELECT No_, sum(Quantity) AS Sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line]
WHERE [Item Category Code] = '5104' GROUP BY No_,[Shipment Date],
[ItemCategoryCode], Description,[Description 2]
IN SQL IF YOU USE ANY COLUMN NAME IN SELECT CLAUSE EXCEPT AGGREGRATE FUNCTION THEN YOU NEED TO ADD ALL THE COLUMNS IN GROUP BY ALSO OTHER WISE IT WILL SHOW EXCEPTION
IF YOU WANT SUM ONLY BY NO_ Column then you have to write a subquery with the aggregarte function and join it to you other columns as folows
SELECT No_ ,quant.sold, [Shipment Date] AS SoldDate, [Item Category Code],
Description, [Description 2] FROM dbo.[3S Company A_S$Sales Invoice Line] INV,
(SELECT No_, sum(Quantity) AS Sold from dbo.[3S Company A_S$Sales Invoice Line] where
WHERE [Item Category Code] = '5104' group by No_) quant
WHERE [Item Category Code] = '5104' and
inv.no_=quant.no_
The columns (Other than aggregate functions) that exists in select clause should also present in the group by clause. This is what the error message states.
Select Productid, Sum(Saled) from product
Group by ProductId
In the above example, ProductId is in the group by clause. So that query is valid. If you introduce one more column that should also be in the group by clause to avoid error.
You have to put columns not using the aggregate functions in your GROUP BY :
GROUP BY
No_
, [Shipment Date]
, [Item Category Code]
, Description
, [Description 2]

SQL aggregate and other fields showing in query

I have a query, where I need the MIN of a DateTime field and then I need the value of a corresponding field in the same row.
Now, I have something like this, however I cannot get Price field without putting it also in an aggregate clause, which is not what I want.
SELECT MIN([Registration Time]), Price FROM MyData WHERE [Product Series] = 'XXXXX'
I need the MIN of the Registration Time field and then I just want the corresponding Price field for that row, however how do I show that?
I do also need my WHERE clause as shown.
I'm sure I've overlooked something really obvious. Using SQL Server 2008
If you want just one record with [Registration Time], Price, it'd be as simple as this:
select top 1 [Registration Time], Price
from MyData
where [Product Series] = 'XXXXX'
order by [Registration Time]
If you want minimum [Registration Time] and corresponding Price for all [Product Series], then there's a few approaches, for example, using row_number() function:
with cte as (
select
[Registration Time], Price,
row_number() over(partition by [Product Series] order by [Registration Time]) as rn
from MyData
)
select
[Registration Time], Price, [Product Series]
where rn = 1