sql table using sum - sql

I would like a result of
ID received total
2 25 25
from ItemReceived table
ID item received
2 1 5
2 2 2
2 1 10
2 2 8
and ItemsToReceive table
ID item quantity
2 1 15
2 2 10
Is there a way to get this result?
I used this code:
SELECT sum(ItemsToReceive.quantity), SUM( ItemReceived.received)
FROM ItemsToReceive
INNER JOIN ItemReceived ON ItemReceived.ID = ItemsToReceive.ID
GROUP BY poitems.poid
I got a wrong result making received to 50...
Can anyone help me?

Try this
select t1.Id,t1.quantity, t2.received from
(
SELECT ID,sum(quantity) quantity from ItemsToReceive group by id
) as t1 inner join
(
SELECT ID,SUM(received) as received from ItemReceived group by id
) as t2 on t1.id=t2.id

This might help
;WITH quantity AS (
SELECT sum(ItemsToReceive.quantity) As TotQuant
,ItemsToReceive.id AS id
FROM ItemsToReceive
GROUP BY ItemsToReceive.id
), Prod As (
SELECT SUM( ItemReceived.received) As TotRec
,ItemReceived.ID As Id
FROM ItemReceived
GROUP BY ItemReceived.ID
)
SELECT
q.Id
,p.TotRec As Received
,q.TotQuant As Quantity
FROM quantity q
INNER JOIN Prod p on p.Id = q.id

select ID , sum(received) , sum(quantity) from ItemReceived left join ItemsToReceive on (ItemReceived.ID = ItemsToReceive.ID and ItemReceived.item = ItemsToReceive.item) group by ID

Related

T-SQL (Azure) table gives double results

I am trying to get a list of all the id_user and the amount of creditRecieved and the amount of creditUsed, I actually would like to add a third option that mentions the left over if any. If creditReceived is bigger as creditUsed. But the first part now doubles the outputs so I started following an explanation here on StackOverflow, but I can't get it to work.
SELECT
dbo.UserPurchase.CreditUsed,
dbo.UserCredit.CreditRecieved
FROM
(
SELECT SUM(dbo.UserPurchase.creditUsed) AS CreditUsed
FROM dbo.UserPurchase
)
dbo.UserPurchase LEFT JOIN
(
SELECT SUM(dbo.UserCredit.creditRecieved) AS CreditRecieved
FROM dbo.UserCredit
)
dbo.UserCredit ON dbo.UserPurchase.id_user = dbo.UserCredit.id_user
The data comes from these two tables
TABLE dbo.UserCredit
id id_user creditRecieved PurchasePrice
----------- ----------- -------------- -------------
1 1 150 750
2 1 25 100
3 2 65 15
TABLE dbo.UserPurchase
id id_user creditUsed date
----------- ----------- ----------- -----------
1 1 175 NULL
2 2 3 NULL
3 2 2 NULL
I would like to have the following result
id_user CreditRecieved CreditUsed CreditLeftOver
----------- -------------- ----------- --------------
1 175 175 0
2 65 5 60
Try querying each table separately:
SELECT users.id_user, coalesce(credit.received, 0) received,
coalesce(purchase.used, 0) Used, coalesce(credit.received, 0) - coalesce(purchase.used, 0) LeftOver, coalesce(purchase.purchaseCount, 0) purchaseCount
FROM
(
select distinct id_user from dbo.UserCredit
union
select distinct id_user from dbo.UserPurchase
) users
left outer join
(
select id_user, sum(creditRecieved) received from dbo.UserCredit group by id_user
) credit
on users.id_user = credit.id_user
left outer join
(
select id_user, sum(creditUsed) used, count(1) purchaseCount from dbo.UserPurchase group by id_user
) purchase
on users.id_user = purchase.id_user
Please note that there is a typo in CreditRecieved. It should be CreditReceived.
If I understand you correctly, you want the creditUsed and creditRecieved (typo on your end?) summed up by id_user? This would be the query:
SELECT p.id_user, SUM(p.creditUsed), SUM(u.creditRecieved)
FROM dbo.UserCredit u
LEFT JOIN dbo.UserPurchase p ON p.id_user = u.id_user
GROUP BY p.id_user
You can use this query
SELECT
C.id_user,
C.CreditRecieved,
P.CreditUsed,
C.CreditRecieved - P.CreditUsed CreditLeftOver
FROM
(SELECT id_user, SUM(creditRecieved) CreditRecieved FROM UserCredit GROUP BY id_user) C
LEFT JOIN
(SELECT id_user, SUM(creditUsed) CreditUsed FROM UserPurchase GROUP BY id_user) P ON C.id_user = P.id_user

left join without duplicate values using MIN()

I have a table_1:
id custno
1 1
2 2
3 3
and a table_2:
id custno qty descr
1 1 10 a
2 1 7 b
3 2 4 c
4 3 7 d
5 1 5 e
6 1 5 f
When I run this query to show the minimum order quantities from every customer:
SELECT DISTINCT table_1.custno,table_2.qty,table_2.descr
FROM table_1
LEFT OUTER JOIN table_2
ON table_1.custno = table_2.custno AND qty = (SELECT MIN(qty) FROM table_2
WHERE table_2.custno = table_1.custno )
Then I get this result:
custno qty descr
1 5 e
1 5 f
2 4 c
3 7 d
Customer 1 appears twice each time with the same minimum qty (& a different description) but I only want to see customer 1 appear once. I don't care if that is the record with 'e' as a description or 'f' as a description.
First of all... I'm not sure why you need to include table_1 in the queries to begin with:
select custno, min(qty) as min_qty
from table_2
group by custno;
But just in case there is other information that you need that wasn't included in the question:
select table_1.custno, ifnull(min(qty),0) as min_qty
from table_1
left outer join table_2
on table_1.custno = table_2.custno
group by table_1.custno;
"Generic" SQL way:
SELECT table_1.custno,table_2.qty,table_2.descr
FROM table_1, table_2
WHERE table_2.id = (SELECT TOP 1 id
FROM table_2
WHERE custno = table_1.custno
ORDER BY qty )
SQL 2008 way (probably faster):
SELECT custno, qty, descr
FROM
(SELECT
custno,
qty,
descr,
ROW_NUMBER() OVER (PARTITION BY custno ORDER BY qty) RowNum
FROM table_2
) A
WHERE RowNum = 1
If you use SQL-Server you could use ROW_NUMBER and a CTE:
WITH CTE AS
(
SELECT table_1.custno,table_2.qty,table_2.descr,
RN = ROW_NUMBER() OVER ( PARTITION BY table_1.custno
Order By table_2.qty ASC)
FROM table_1
LEFT OUTER JOIN table_2
ON table_1.custno = table_2.custno
)
SELECT custno, qty,descr
FROM CTE
WHERE RN = 1
Demolink

sql query to get data group by customer type and need to add default value if customer type not found

I have a table "Customers" with columns CustomerID, MainCountry and CustomerTypeID.
I have 5 customer types 1,2,3,4,5 .
I want to count number of customers of each country according to customer type. I am using the following query:
select count(CustomerID) as CustomerCount,MainCountry,CustomerTypeID
from Customers
group by CustomerTypeID,MainCountry
But some countries not have any customers, under type 1,2,3,4 or 5.
So I want to put a default value 0 for if customer type is not exist for that country.
Currently it is giving data as follows :-
CustomerCount MainCountry CustomerTypeID
5695 AU 1
525 AU 2
12268 AU 3
169 AU 5
18658 CA 1
1039 CA 2
24496 CA 3
2259 CA 5
2669 CO 1
10 CO 2
463 CO 3
22 CO 4
39 CO 5
As "AU" not have type 4 so I want a default value for it.
You should JOIN your table with a table with TypeId's. In this case
select count(CustomerID) as CustomerCount,TypeTable.MainCountry,TypeTable.TId
from
Customers
RIGHT JOIN (
select MainCountry,TId from
(
select Distinct MainCountry from Customers
) as T1,
(
select 1 as Tid
union all
select 2 as Tid
union all
select 3 as Tid
union all
select 4 as Tid
union all
select 5 as Tid
) as T2
) as TypeTable on Customers.CustomerTypeID=TypeTable.TId
and Customers.MainCountry=TypeTable.MainCountry
group by TypeTable.TId,TypeTable.MainCountry
Select Country.MainCountry, CustomerType.CustomerTypeId, Count(T.CustomerID) As CustomerCount
From (Select Distinct MainCountry From Customers) As Country
Cross Join (Select Distinct CustomerTypeId From Customers) As CustomerType
Left Join Customers T
On Country.MainCountry = T.MainCountry
And CustomerType.CustomerTypeId = T.CustomerTypeId
-- Edit here
And T.CreatedDate > Convert(DateTime, '1/1/2013')
-- End Edit
Group By Country.MainCountry, CustomerType.CustomerTypeId
Order By MainCountry, CustomerTypeId
Try that:
with cuntry as (
Select Distinct MainCountry From Customers
),
CustomerType as (
(Select Distinct CustomerTypeId From Customers
),
map as (
select MainCountry, CustomerTypeId from cuntry,CustomerType
)
select count(CustomerID) as CustomerCount,a.MainCountry,a.CustomerTypeID
from
map a left join Customers b on a.CustomerCount=b.CustomerCount and a.CustomerTypeID=b.CustomerTypeID

select max value from a table looking for description in another table

i have 3 tables
Buyer
buyer_id | name
50 |Joe
60 |Astor
70 |Cloe
Item
item_id | description
1 | iphone
2 | ipod
3 | imac
Item_Sold
buyer_id | item_id
50 | 1
50 | 2
60 | 1
60 | 3
70 | 1
70 | 2
70 | 3
I want to find out the description of the best-selling item, in this case:
Best-Selling
iphone
SELECT description AS Best_Selling
FROM item
WHERE item_id = (SELECT item_id FROM( SELECT item_id ,COUNT(*) as num_items
FROM Item_Sold
GROUP BY item_id
ORDER BY num_items DESC
LIMIT 1
)z
)
See SQL FIDDLE
This answer is not totally correct . If two items have same sale amount then it will return only one of them.
This query will give all item id decription whose sale is maximum i.e. when two or more item id have equal amount of sale....
;WITH CTE1(Id,Counts) as
(
SelectItem_Id,COUNT(buyer_id ) AS C FROM T GROUP BY ID
)
Select Item.Description from CTE1 A inner join
(Select MAX(Counts) AS MaxCount FROM CTE1 ) b on a.Counts=b.MaxCount
inner join
Item on Item.Item_Id=a.Item_Id
If Common table Expression Not Work you Can Try Like this....
Select Item.Description from (Select Item_Id,COUNT(buyer_id ) AS Counts FROM item_sold GROUP BY Item_Id) A inner join
(Select MAX(Counts) AS MaxCount FROM
(
Select Item_Id,COUNT(buyer_id) AS Counts
FROM item_sold GROUP BY Item_Id) v
) b
on a.Counts=b.MaxCount
inner join
Item on Item.Item_Id=a.Item_Id
SQL Fiddle Demo
Here Is the Liknk of Fiddle the case i m talknig about....it give all description who have maximun sale....
Case Sql Fiddle Demo
select description as "Best-Selling"
from (select a.item_id, b.description, count(*) count
from Item_Sold a,Items b
where a.item_id = b.item_id
group by a.item_id ) temp
where count = (select max(count)
from (select a.item_id, count(*) count
from Item_Sold a,Items b
where a.item_id = b.item_id
group by a.item_id ) temp1)
pl-sql:
select description as "Best-Selling"
from item
where item_id in (
select item_id from (
select item_id, count(item_id) as item_count
from item_sold
group by item_id)
where item_count = (
select max(item_count) from (
select item_id, count(item_id) as item_count
from item_sold
group by item_id)
)
)

Row Filter Using Distinct

This is master table Query
Select *
from AC_TAB
where AC_ID = 7 ;
AC_PK AC_ID TYPE STATUS INS_DATE VALID
102 7 0 0 3/21/2012 3:35:08 PM 0
103 7 1 0 3/21/2012 3:35:08 PM
104 7 2 1 3/21/2012 3:35:08 PM
I am joining this table with txn table using ac_id. Since here its having 3 rows for ac_id 7 , my txn table returning 3 times. how to restrict this. since i want to return only one irrespective of type
MY Txn Query
Select txn_id, amount
from txn_hdr , ac_tab
where txn_ac_id = ac_id ;
txn_id amount
1 200
1 200
3 100
3 100
It is not actually clear what you need but it sounds like you only want to return one record per ac_id from the AC_TAB. If so, then there are a few ways that you can do this.
Using a subquery:
select *
from
(
select max(INS_DATE) INS_DATE, AC_ID
from ac_tab
group by AC_ID
) a
inner join txn_hdr t
on a.ac_id = t.ac_id;
Or with CTE using a row_number():
;with cte as
(
select a.ins_date, a.ac_id, t.amount, row_number()
over(partition by a.ac_id order by a.ins_date desc) rn
from ac_tab a
inner join txn_hdr t
on a.ac_id = t.ac_id
)
select *
from cte
where rn = 1;
Or with a row_number() in a subquery:
select *
from
(
select a.ins_date, a.ac_id, t.amount, row_number()
over(partition by a.ac_id order by a.ins_date desc) rn
from ac_tab a
inner join txn_hdr t
on a.ac_id = t.ac_id
) x
where rn = 1
You can do this way :
Select distinct txn_id, amount
from txn_hdr , ac_tab
where txn_ac_id = ac_id ;