Multiple Distinct Values with SUM - sql

i have a table which Data is like
userID name amount Date
1 mark 20 22-10
1 mark 30 22-10
2 kane 50 22-12
2 kane 60 22-12
3 mike 60 22-10
Date is Unique with combination of userID + Username + Date
but as its more then 100k records there maybe duplicate date records but wither other user ids and names not with
now i want Output like
userID name amount Date
1 mark 50 22-10
2 kane 110 22-12
3 mike 60 22-10
if i try group By with id,name,sum(amount),date it returns multiple rows and answer incorrect
i have tried various combination of distict and SUM etc etc but not succeeded
any Solution
Thanks

You typically use a GROUP BY to aggregate one or more fields by one or more other fields.
SELECT userID, Name, SUM(amount), MIN(date)
FROM YourTable
GROUP BY
userID, Name
From MSDN: Aggregate functions
Aggregate functions perform a calculation on a set of values and
return a single value. With the exception of COUNT, aggregate
functions ignore null values. Aggregate functions are often used with
the GROUP BY clause of the SELECT statement.
some typical aggregate functions are
SUM
MIN
AVG
...
From MSDN: GROUP BY
Groups a selected set of rows into a set of summary rows by the values
of one or more columns or expressions in SQL Server 2008 R2. One row
is returned for each group. Aggregate functions in the SELECT clause
list provide information about each group instead of
individual rows.

select
userId, name, sum(amount) as amount
from
table
group by
userId, name

You don't want DISTINCT here, but rather GROUP BY with the aggregate SUM()
SELECT
userID,
name,
SUM(amount) AS amount
FROM tbl
GROUP BY userID, name

Related

How to distinguish rows in a database table on the basis of two or more columns while returning all columns in sql server

I want to distinguish Rows on the basis of two or more columns value of the same table at the same time returns all columns from the table.
Ex: I have this table
DB Table
I want my result to be displayed as: filter on the basis of type and Number only. As in abover table type and Number for first and second Row is same so it should be suppressed in result.
txn item Discrip Category type Number Mode
60 2 Loyalty L 6174 XXXXXXX1390 0
60 4 Visa C 1600 XXXXXXXXXXXX4108 1
I have tried with sub query but yet unsuccessful. Please suggest what to try.
Thanks
You can do what you want with row_number():
select t.*
from (select t.*,
row_number() over (partition by type, number order by item) as seqnum
from t
) t
where seqnum = 1;

Sql to get unique rows

I have a table as below.
OId CustId CustSeq
1 A 10
1 A 20
2 A 10
2 A 20
I'm trying to extract unique records as below.
OId CustId CustSeq (Different OIds with different CustSeqs)
1 A 10
2 A 20
May I know how I could come out the query to extract like above?
Just use DISTINCT. That's what it was desgined for although group by will work.
http://www.techonthenet.com/oracle/distinct.php
SELECT DISTINCT OID, CUSTID, CUSTSEQ
FROM TABLE_NAME
Use DISTINCT, and also use Group By for the 2 columns CustId & CustSeq
Check here for example Is it possible to GROUP BY multiple columns using MySQL?

Merge Defaut and User Adjusted Data

I have a table:
Type (PK) Year (PK) Value
Default 2000 1
Default 2001 2
UserFooAdjusted 2001 3
UserBarAdjusted 2001 4
What is the fastest SQL query that returns distinct years and if there are two rows with the same year then the user adjusted value is returned? There are multiple users. The query returns data for one user. Example result:
Year Value
2000 1
2001 3
I've thougt about A UNION B but how do I always keep the duplicate from B? Maybe a better solution would be to divide the current table into two tables: one would contain default values and the other would contain user adjusted vaules?
Assuming that there are only two types: Default and UserAdjusted, you can use Common Table Expression and Window Functions, in sql server.
WITH recordList
AS
(
SELECT YEAR, VALUE,
ROW_NUMBER() OVER (PARTITION BY YEAR
ORDER BY TYPE DESC) rn
FROM tableName
)
SELECT YEAR, VALUE
FROM recordList
WHERE rn = 1
SQLFiddle Demo

Count distinct query MS Access

It seems that we can not use Count (Distinct column) function in MS Access. I have following data and expected result as shown below
Looking for MS Access query which can give required result.
Data
ID Name Category Person Office
1 FIL Global Ben london
1 FIL Global Ben london
1 FIL Overall Ben Americas
106 Asset Global Ben london
156 ICICI Overall Rimmer london
156 ICICI Overall Rimmer london
188 UBS Overall Rimmer london
9 Fund Global Rimmer london
Expected Result
Person Global_Cnt Overall_Cnt
Ben 2 1
Rimmer 1 2
Use a subquery to select the distinct values from your table.
In the parent query, GROUP BY Person, and use separate Count() expressions for each category. Count() only counts non-Null values, so use IIf() to return 1 for the category of interest and Null otherwise.
SELECT
sub.Person,
Count(IIf(Category = 'Global', 1, Null)) AS Global_Cnt,
Count(IIf(Category = 'Overall', 1, Null)) AS Overall_Cnt
FROM
(
SELECT DISTINCT ID, Category, Person
FROM YourTable
) AS sub
GROUP BY sub.Person;
I was unsure which fields identify your unique values, so chose ID, Category, and Person. The result set from the query matches what you asked for; change the SELECT DISTINCT field list if it doesn't fit with your actual data.
When creating a query in Microsoft Access, you might want to return only distinct or unique values. There are two options in the query's property sheet, "Unique Values" and "Unique Records":
DISTINCT and DISTINCTROW sometimes provide the same results, but there are significant differences:
DISTINCT
DISTINCT checks only the fields listed in the SQL string and then eliminates the duplicate rows. Results of DISTINCT queries are not updateable. They are a snapshot of the data.
DISTINCT queries are similar to Summary or Totals queries (queries using a GROUP BY clause).
DISTINCTROW
DISTINCTROW, on the other hand, checks all fields in the table that is being queried, and eliminates duplicates based on the entire record (not just the selected fields). Results of DISTINCTROW queries are updateable.
Read More...
MS Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
select count(column) as guessTable
from
(
select distinct column from Table
)

Getting the min() of a count(*) column

I have a table called Vehicle_Location containing the columns (and more):
ID NUMBER(10)
SEQUENCE_NUMBER NUMBER(10)
TIME DATE
and I'm trying to get the min/max/avg number of records per day per id.
So far, I have
select id, to_char(time), count(*) as c
from vehicle_location
group by id, to_char(time), min having id = 16
which gives me:
ID TO_CHAR(TIME) COUNT(*)
---------------------- ------------- ----------------------
16 11-05-31 159
16 11-05-23 127
16 11-06-03 56
So I'd like to get the min/max/avg of the count(*) column. I am using Oracle as my RDBMS.
I don't have an oracle station to test on but you should be able to just wrap the aggregator around your SELECT as a subquery/derived table/inline view
So it would be (UNTESTED!!)
SELECT
AVG(s.c)
, MIN(s.c)
, MAX(s.c)
, s.ID
FROM
--Note this is just your query
(select id, to_char(time), count(*) as c from vehicle_location group by id, to_char(time), min having id = 16) as s
GROUP BY s.ID
Here's some reading on it:
http://www.devshed.com/c/a/Oracle/Inserting-SubQueries-in-SELECT-Statements-in-Oracle/3/
EDIT: Though normally it is a bad idea to select both the MIN and MAX in a single query.
EDIT2: The min/max issue is related to how some RDBMS (including oracle) handle aggregations on indexed columns. It may not affect this particular query but the premise is that it's easy to use the index to find either the MIN or the MAX but not both at the same time because any index may not be used effectively.
Here's some reading on it:
http://momendba.blogspot.com/2008/07/min-and-max-functions-in-single-query.html