I have a table with 3 columns. in which i am showing Time wise report of ContainerCount with Time.
Below image shows the actual table
I am doing pivot for this table and the image is shown below
now i want to add all columns and want to shown in single column. But not getting. The query is mentioned below
SELECT 'CFS to Zero' Location, sum( [0]+[1]+[2]+[3]) FROM
(SELECT [ContainerCount],Time FROM #tt )as Tab1
PIVOT
(
MAX([ContainerCount]) FOR Time IN ([0])) AS Tab2 ;
use coalesce()
SELECT 'CFS to Zero' Location, coalesce([0],0)+coalesce([1],0)+coalesce([2],0)+coalesce([3],0) FROM
(SELECT [ContainerCount],Time FROM #tt )as Tab1
PIVOT
(
MAX([ContainerCount]) FOR Time IN ([0],[1],[2],[3])) AS Tab2
If you only need 1 SUM then you don't really need a PIVOT.
Just aggregate and get the MAX values, then SUM them.
This has the benefit that you can just use a BETWEEN to only select a range of Time.
Instead of having to hardcode the Time values in a PIVOT.
SELECT
'CFS to Zero' AS Location,
SUM(MaxContainerCount) AS TotalMaxContainerCount
FROM
(
SELECT
[Time],
MAX(ContainerCount) AS MaxContainerCount
FROM #tt
WHERE [Time] BETWEEN 0 AND 3
GROUP BY [Time]
) q
Related
how can i add the values of two similar dates values into one
for example:
2019-15-07 120
2019-16-07 152
2019-16-07 120
2019-17-07 100
I want to add the date values of 2019-17-07 into one for example 2019-17-07 152+120. That is 2019-17-07 272. Thank you.
to check i use the code:
SELECT date, COUNT(*)
FROM getProcess
GROUP BY Date
HAVING ( COUNT(*) > 1 )
which shows which is repeated date.
Instead of count just perform SUM:
SELECT date, SUM([myvalue])
FROM getProcess
GROUP BY Date
If yo want to materialize the data and clear duplicates, you can store the above result in temporary table, then delete the found records and insert the them with the aggregate value:
SELECT date, SUM([myvalue]) [myvalue]
INTO #datasource
FROM getProcess
GROUP BY Date
HAVING ( COUNT(*) > 1 )
DELETE [dbo].[mytable]
FROM [dbo].[mytable] MT
INNER JOIN #datasource DS
ON MT.[date] = DS.[date]
INSERT INTO [dbo].[mytable]
SELECT *
FROM #datasource
I have data in the following format.
Column 1 and Value from the database. I use a LEFT() function to extract Column 2. Where I need help is to sum the values from the newly calculated Column 2 and list the sums a new column.
Any help is appreciated. Thanks.
Basically, you seem to want an aggregation with a function for the aggregation key:
select left(column1, 1), sum(value)
from t
group by left(column1, 1);
SELECT *
,CalculatedColumn2 = LEFT(Column1,1)
,Value
,CalculatedSum = SUM(Value) OVER (PARTITION BY LEFT(Column1,1))
FROM
Table
While Gordon's answer get's you the SUM if you want it per row you can use a partitioned window Function such as SUM() OVER.
You can achieve it using Windows Functions
Try the following query
SELECT column1
, SUBSTRING(column1,1,1) as [calculated column 2]
,value
, SUM(value) OVER(PARTITION BY SUBSTRING(column1,1,1) )
FROM table1
And you can also use LEFT(Column1,1) instead of SUBSTRING(column1,1,1) (String Functions)
Get the first character from column1 using LEFT function and use that result set as a sub-query and find the sum of value column group by the new column.
Query
SELECT t.[column2], SUM(t.[value]) as [value] FROM(
SELECT [column1], LEFT([column1], 1) AS [column2], [value]
FROM [your_table_name]
)t
GROUP BY t.[column2];
Add computed persisted column which can contain values from left(column1, 1). You shloudn't repeat your code.
alter table tbl add newcomputedcol column (left(column1, 1)) persisted
Use grouped subqry or use over clause:
select
*,
sum(value) over() over(partition by newcomputedcol) SumPerNewComputedCol
from tbl
Your new persisted column can be indexed, your qry can be added into view.
The table with the data that I have
In the above table I have the columns : weekNumber , weeklyHours , points_Rewarded.
There are four employees : a,b,c,d
I have the values for week1,week2,week3, and so on ( I can have data for many more weeks also such as week4,week5, etc)
I want to write a query such that after passing the query I get the total of the weeklyHours and points_Rewarded for each employee in a new table.
The kind of table that the query should give me is here the desired table that I want after passing the query
Please help me with the query.
Thanks in advance.
You can use GROUP BY to achieve aggregate values. In your case your are looking for SUM.
Try this
DECLARE #tbl TABLE(EmployeeID INT, EmployeeName VARCHAR(100),WeekNumber VARCHAR(100),WeeklyHours INT,pointsRewarded INT);
INSERT INTO #tbl VALUES
(1,'a','week1',10,20)
,(2,'b','week1',1,20)
,(3,'c','week1',20,20)
,(4,'d','week1',30,30)
,(1,'a','week2',11,10)
,(2,'b','week2',44,10)
,(3,'c','week2',5,10)
,(4,'d','week2',6,40)
,(1,'a','week3',7,10)
,(2,'b','week3',88,10)
,(3,'c','week3',9,10)
,(4,'d','week3',0,10);
SELECT tbl.EmployeeID
,tbl.EmployeeName
,SUM(tbl.WeeklyHours) AS Total_Weekly_Hours
,SUM(pointsRewarded) AS Total_Points
FROM #tbl AS tbl
GROUP BY tbl.EmployeeID, tbl.EmployeeName
Try with the below query.
SELECT EmployeeName
,SUM (weeklyHours)Total_weekly_hours
,SUM (pointsrewarded) TotalPoints
FROM YourTable
Group By EmployeeName
This is a simple GROUP BY. You want to group the employees by name so specify employeename in the GROUP BY statement. Then just select HOW you want to group the other columns. In this case, you want to SUMthem:
SELECT employeename,
SUM(weeklyhours) as total_weekly_hours,
SUM(points_rewarded) as total_points
GROUP BY employeename
Note that you could also use AVG or MIN or MAX in place of SUM depending on what you want to find. The AS clause specifies what you want to call a particular column in your output.
Tested here: http://sqlfiddle.com/#!9/2a96f
I am trying to list all the duplicate records in a table. This table does not have a Primary Key and has been specifically created only for creating a report to list out duplicates. It comprises of both unique and duplicate values.
The query I have so far is:
SELECT [OfficeCD]
,[NewID]
,[Year]
,[Type]
FROM [Test].[dbo].[Duplicates]
GROUP BY [OfficeCD]
,[NewID]
,[Year]
,[Type]
HAVING COUNT(*) > 1
This works right and gives me all the duplicates - that is the number of times it occurs.
But I want to display all the values in my report of all the columns. How can I do that without querying for each record separately?
For example:
Each table has 10 fields and [NewID] is the field which is occuring multiple times.I need to create a report with all the data in all the fields where newID has been duplicated.
Please help.
Thank you.
You need a subquery:
SELECT * FROM yourtable
WHERE NewID IN (
SELECT NewID FROM yourtable
GROUP BY OfficeCD,NewID,Year,Type
HAVING Count(*)>1
)
Additionally you might want to check your tags: You tagged mysql, but the Syntax lets me think you mean sql-server
Try this:
SELECT * FROM [Duplicates] WHERE NewID IN
(
SELECT [NewID] FROM [Duplicates] GROUP BY [NewID] HAVING COUNT(*) > 1
)
select d.*
from Duplicates d
inner join (
select NewID
from Duplicates
group by NewID
having COUNT(*) > 1
) dd on d.NewID = dd.NewID
I have a table named with "Sales" having the following columns:
Sales_ID|Product_Code|Zone|District|State|Distributor|Total_Sales
Now i want to generate a sales summary to view the total sales by zone and then by district and then by State by which distributor for the last/past month period.
How can i write a Sql Statement to do this? Can anyone help me Plz. Thanks in advance.
And i have another question that, how can i select the second largest or third largest values from any column of a table.
Have a look at using the ROLLUP GROUP BY option.
Generates the simple GROUP BY aggregate rows, plus subtotal or super-aggregate rows,
and also a grand total row.
The number of groupings that is returned equals the number of expressions
in the <composite element list> plus one. For example, consider the following statement.
Copy Code
SELECT a, b, c, SUM ( <expression> )
FROM T
GROUP BY ROLLUP (a,b,c)
One row with a subtotal is generated for each unique combination of values of
(a, b, c), (a, b), and (a). A grand total row is also calculated.
Columns are rolled up from right to left.
The column order affects the output groupings of ROLLUP and can affect the number
of rows in the result set.
Something like
DECLARE #Table TABLE(
Zone VARCHAR(10),
District VARCHAR(10),
State VARCHAR(10),
Sales FLOAT
)
INSERT INTO #Table SELECT 'A','A','A',1
INSERT INTO #Table SELECT 'A','A','B',1
INSERT INTO #Table SELECT 'A','B','A',1
INSERT INTO #Table SELECT 'B','A','A',1
SELECT Zone,
District,
State,
SUM(Sales)
FROM #Table
WHERE <Your Condition here> --THIS IS WHERE YOU USE THE WHERE CLAUSE
GROUP BY ROLLUP (Zone,District,State)
To Get the second and 3rd largets, you can use either (ROW_NUMBER (Transact-SQL))
;WITH Vals AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY RequiredCol DESC) RowNum
FROM YourTable
)
SELECT *
FROM Vals
WHERE RowNum IN (2,3)
or
SELECT TOP 2
*
FROM (
SELECT TOP 3
*
FROM YourTable
ORDER BY RequiredCol DESC
) sub
ORDER BY RequiredCol
SELECT SUM(Total_Sales) FROM sales GROUP BY (X)
Replace X with Zone, District, State or Distributor.