how to select columns with aggregate function sql server - sql

i need to select two columns.1. calculate sum of one column and display it 2.display column as it is. so i tried below code
SELECT Sum(CONVERT(FLOAT, Replace(total, Char(0), ''))) AS Total,
[product name]
FROM tb_sales_entry_each_product
GROUP BY [sales date]
error message
Column 'tb_sales_entry_each_product.Product Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
where i made error.thanks

just need to group
select SUM(CONVERT(float, REPLACE(Total, CHAR(0), ''))) as Total, [Product Name]
from tb_sales_entry_each_product group by [Sales Date], [product name]
When ever you do a numercial count sum etc, any other columns need to be grouped.
thats all your missing

Try this:
select SUM(CONVERT(float, REPLACE(Total, CHAR(0), ''))) as Total,
[Product Name] ,[Sales Date]
from tb_sales_entry_each_product
group by [Sales Date],[Product Name]

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 ()

Column invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

We have a table which will capture the swipe record of each employee. I am trying to write a query to fetch the list of distinct employee record by the first swipe for today.
We are saving the swipe date info in datetime column. Here is my query its throwing exception.
select distinct
[employee number], [Employee First Name]
,[Employee Last Name]
,min([DateTime])
,[Card Number]
,[Reader Name]
,[Status]
,[Location]
from
[Interface].[dbo].[VwEmpSwipeDetail]
group by
[employee number]
where
[datetime] = CURDATE();
Getting error:
Column 'Interface.dbo.VwEmpSwipeDetail.Employee First Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any help please?
Thanks in advance.
The error says it all:
...Employee First Name' is invalid in the select list because it is not contained
in either an aggregate function or the GROUP BY clause
Saying that, there are other columns that need attention too.
Either reduce the columns returned to only those needed or include the columns in your GROUP BY clause or add aggregate functions (MIN/MAX). Also, your WHERE clause should be placed before the GROUP BY.
Try:
select distinct [employee number]
,[Employee First Name]
,[Employee Last Name]
,min([DateTime])
,[Card Number]
,min([Reader Name])
from [Interface].[dbo].[VwEmpSwipeDetail]
where CAST([datetime] AS DATE)=CAST(GETDATE() AS DATE)
group by [employee number], [Employee First Name], [Employee Last Name], [Card Number]
I've removed status and location as this is likely to return non-distinct values. In order to return this data, you may need a subquery (or CTE) that first gets the unique IDs of the SwipeDetails table, and from this list you can join on to the other data, something like:
SELECT [employee number],[Employee First Name],[Employee Last Name].. -- other columns
FROM [YOUR_TABLE]
WHERE SwipeDetailID IN (SELECT MIN(SwipeDetailsId) as SwipeId
FROM SwipeDetailTable
WHERE CAST([datetime] AS DATE)=CAST(GETDATE() AS DATE)
GROUP BY [employee number])
Please Try Below Query :
select distinct [employee number],[Employee First Name]
,[Employee Last Name]
,min([DateTime])
,[Card Number]
,[Reader Name]
,[Status]
,[Location] from [Interface].[dbo].[VwEmpSwipeDetail] group by [employee number],[Employee First Name]
,[Employee Last Name]
,[Card Number]
,[Reader Name]
,[Status]
,[Location] having [datetime]=GetDate();
First find the first timestamp for each employee on the given day (CURDATE), then join back to the main table to get all the details:
WITH x AS (
SELECT [employee number], MIN([datetime] AS minDate
FROM [Interface].[dbo].[VwEmpSwipeDetail]
WHERE CAST([datetime] AS DATE) = CURDATE()
GROUP BY [employee number]
)
select [employee number]
,[Employee First Name]
,[Employee Last Name]
,[DateTime]
,[Card Number]
,[Reader Name]
,[Status]
,[Location]
from [Interface].[dbo].[VwEmpSwipeDetail] y
JOIN x ON (x.[employee number] = y.[employee number] AND x.[minDate] =Y.[datetime]
This should not be marked as mysql as this would not happen in mysql.
sql-server does not know which of the grouped [Employee First Name] values to return so you need to add an aggregate (even if you only actually expect one result). min/max will both work in that case. The same would apply to all the other rows where they are not in the GROUP BY or have an aggregate function (EG min) around them.

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

SQL Result Set Merge

I have a limitation where I can only send one result set to a reporting application at any one time, to produce an end report for a customer.
So a query like this
select
[AGENT],
[TRANSDATE],
[RECIPT NO],
[CUSTOMER NAME],
[ORDER NO] ,
[TRANS NO] ,
QUANTITY,
[AMOUNT COST],
From [Customer] C
However I need lots of totals at the bottom such as this query for some of the columns. I cannot make any changes to front end due to it being a legacy reporting application.
select
Sum ( QUANTITY ) as [SUM OF QUANTITY] ,
Sum ( AMOUNT COST ) AS [SUM OF AMOUNT COST]
From [Customer] C
Obviously I simplified the queries I am using. So the question is how to make 2 results sets one result set in SQL?
Union and union all failed due to date columns being defaulted if you use blank for a column in end application.
Rollup or Pivoting or CTE I kinda thought of but cannot see a solution yet.
what about windowed functions?
like...
select
[AGENT],
[TRANSDATE],
[RECIPT NO],
[CUSTOMER NAME],
[ORDER NO] ,
[TRANS NO] ,
QUANTITY,
[AMOUNT COST],
Sum ( QUANTITY ) over () as [SUM OF QUANTITY] ,
Sum ( [AMOUNT COST] ) over () AS [SUM OF AMOUNT COST]
From [Customer] C