how to split one column into two and group by id [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Can you help me with this?
I want to split the amount column into two column as debit and credit, and sum of debit and credit group by account id
This is my Table:
ID | GeneralLedgerHeaderId | AccountId | DrCr | Ammount
1 | 1 | 2 | 1 | 200.000
2 | 1 | 4 | 1 | 200.000
3 | 1 | 5 | 2 | 428.000
4 | 1 | 8 | 1 | 28.000
5 | 2 | 5 | 1 | 428.000

Assuming that DrCr=1 means debit and DrCr=2 means credit, you could use a couple of case expressions:
SELECT AccountId,
SUM(CASE DrCr WHEN 1 THEN Amount END) AS sum_debit,
SUM(CASE DrCr WHEN 2 THEN Amount END) AS sum_credit
FROM mytable
GROUP BY AccountId

Do you want something as follows ?
You can use SUM() function with Partition By clause so you can get aggregations like Count() in a way of custom categorization defined in Partition By clause
select
Id,
GeneralLedgerHeaderId,
AccountId,
case when DrCr = 1 then Amount end as Debit,
case when DrCr = 2 then Amount end as Credit,
Summed = SUM(case when DrCr = 1 then (-1 * Amount) else Amount end) over (partition by AccountId)
from Transactions
Second query after comments are edit to this post
SELECT
GL.AccountId,
CA.Code,
CA.AccountName,
SUM(CASE GL.DrCr WHEN 1 THEN Amount END) AS sum_debit,
SUM(CASE GL.DrCr WHEN 2 THEN Amount END) AS sum_credit,
SUM(CASE GL.DrCr WHEN 1 THEN Amount ELSE (-1 * Amount) END) AS sum_total
FROM GeneralLedgerLine GL
Join COA_Client CC
on GL.AccountId = CC.AccountId
join ChartOfAccount CA
on CC.COA_Id = CA.COA_Id
GROUP BY
GL.AccountId, CA.Code, CA.AccountName

use case when with aggregation ,here i assume DrCr=1 debit and 2 means credit
select accountid, sum(case when DrCr=1 then Amount end) as dr,
sum( case when DrCr=2 then Amount end) as cr from your_table
group by accountid

Related

Finding Percentage Via Query

I have a question regarding SQL.
Say I have the following table:
customerID | time_secs
-----------+-----------
1 | 5
1 | 4
1 | 2
2 | 1
2 | 3
3 | 6
3 | 8
I can't change the table design. I want to be able to calculate for each unique customer, the percent of time_secs that is over 3.
So for example, for customer 1, it would be (2 / 3) * 100 %.
I've gotten this so far:
SELECT customerID, COUNT(time_secs)
WHERE time_secs > 3
GROUP BY service
How do I make sure the time_secs is above 3 and also divides it by the total count of time_secs regardless if it's above 3 or not.
Thanks.
A simple method is conditional aggregation:
select customerid,
avg(case when time_seconds > 3 then 100.0 else 0 end) as ratio
from t
group by customerid;
The avg() is a convenient shorthand for:
sum(case when time_seconds > 3 then 100.0 else 0 end) / count(*)

SQL: calculation on two columns with multiple group by statements

I have a table which has the following columns:
user_id - includes duplicates
product_id - includes duplicates
purchases - number of purchases of given product_id
My table looks somewhat like this:
user_id date product_id purchases
0 1 1 1 4
1 1 2 1 0
2 1 3 2 0
3 1 4 2 0
4 2 1 1 1
5 2 2 1 0
6 2 3 1 1
7 3 1 2 0
8 3 2 3 0
9 4 1 5 1
My goal is to calculate the following metric:
% of products that were purchased at least once, grouped by user
For example: user 1 had 2 products, one of them got purchased at least once, the other one did not get purchased at all. So the metric would be the number of products that got purchased at least once / number of all products per user: 1/2 * 100 = 50%
I have little SQL experience so I do not have any legitimate code that could be corrected.
My desired output would be like this:
user_id total_products products_with_purchases metric
0 1 2 1 50%
1 2 1 1 100%
2 3 2 0 0%
3 4 1 1 100%
I would appreciate seeing a good practice solution to this problem. Many thanks!
select
user_id,
count(distinct product_id) as total_products,
count(distinct case when purchases > 0 then product_id end) as products_with_purchases,
100.00 * count(distinct case when purchases > 0 then product_id end)
/ count(distinct product_id) as metric
from T as t
group by user_id
https://rextester.com/EDSY39439
You can do this all in one query but this is the type of situation where it is easier to understand with sub-queries -- sql optimizer should make it fast.
select
user_id,
total_products,
products_with_purchase,
(products_with_purchase / total_products) * 100 as metric
from (
select -- group by user to get totals
user_id,
count(product_id) as total_products,
sum(case when purchases > 0 then 1 else 0 end) as products_with_purchase
from ( -- group by user and product and get purchase items
SELECT user_id, product_id, sum(purchases) as purchases
FROM table
GROUP BY user_id, product_id
) X
group by user_id
) X2
I Am Mohit Sahni
you can solve the above problem with the below SQL Code:
select
user_id,
count(distinct product_id) as total_products,
sum(case when purchases = 0 then 0 else 1 end) as products_with_purchases,
((sum(case when purchases = 0 then 0 else 1 end))/count(distinct product_id))*100 as metric
from
table
group by
user_id

Pivoting two columns with sum [duplicate]

This question already has an answer here:
How to use multiple columns in pivot?
(1 answer)
Closed 3 years ago.
This is my sample Table
**BranchId GroupCode Cash Credit**
1000 AA 10 8644
1000 AA 12 1244
1000 BB 20 7535
1000 CC 30 5633
1001 AA 50 5763
1001 AA 34 2343
1001 BB 60 1000
1001 BB 62 2346
1002 BB 34 1600
1002 CC 68 1700
I want the sample output in this form as shown in the below
**BranchId | AA_Cash | AA_Credit | BB_Cash | BB_Credit | CC_Cash | CC_Credit**
1000 ?
1001
1002
? = I need sum of Cash and Credit in each branches
select * from
(select bid, GroupCode, Cash FROM dueList) as T
PIVOT (sum(Cash) for GroupCode in([AA_Cash],[BB_Cash],[CC_Cash])) PT
This SQL is give output but only cash column, I need add credit column set to the output.
I try using following link
In Sql Server how to Pivot for multiple columns
but in my database there are only 16 branches. Once I try samples in above link it display duplicate lines for branches and lots of null in number area.
You can PIVOT your multi-column data by UNPIVOTing first
For a better visual, run the SELECT within the src subquery
Example
Select *
From (
Select A.BranchID
From YourTable A
Cross Apply ( values (GroupCode+'_Cash' ,Cash)
,(GroupCode+'_Credit',Credit)
) B(Item,Value)
) src
Pivot (sum(Value) for Item in ([AA_Cash],[AA_Credit]
,[BB_Cash],[BB_Credit]
,[CC_Cash],[CC_Credit]
) )pvt
EDIT
On a side-note, it is important to "FEED" your pivot with only the required columns. In your posted example, you included GroupCode. This would generate additional records.
Just use conditional aggregation!
select BranchId,
sum(case when groupcode = 'AA' then cash end) as aa_cash,
sum(case when groupcode = 'AA' then credit end) as aa_credit,
sum(case when groupcode = 'BB' then cash end) as bb_cash,
sum(case when groupcode = 'BB' then credit end) as bb_credit,
sum(case when groupcode = 'CC' then cash end) as cc_cash,
sum(case when groupcode = 'CC' then credit end) as cc_credit
from t
group by BranchId;

Multiple Where Clause in Single Table Select Query

hi friends i have a table with amount and tax as follow
table1
Amount tax
200 5
300 2
100 12
50 5
200 12
in the above table i have amount column and tax, here i want the total sum of amount where with tax clause
example like sum(amount) where tax='2' , sum(amount) where tax='5',and sum(amount) where tax='12'
and i want output like
amount_2 | tax_2 | amount_5 | tax_5 | amount_12 | tax_12
----------------------------------------------------------
300 | 2 | 250 | 5 | 300 | 12
You can write something as below for conditional sum
select
sum(case when tax = 2 then amount else 0 end) amount_2,
2 as tax_2,
sum(case when tax = 5 then amount else 0 end) amount_5,
5 as tax_5,
sum(case when tax = 12 then amount else 0 end) amount_12,
12 as tax_12
from table
/* group by somecol if needed sum per group*/

Grouping sub query in one row

ClientID Amount flag
MMC 600 1
MMC 700 1
FDN 800 1
FDN 350 2
FDN 700 1
Using sql server,Below query I am getting 2 rows fro FDN. I just would like to combine Client values in one row.
Output should be like
Client gtcount, totalAmountGreaterThan500 lscount,AmountLessThan500
MMC 2 1300 0 0
FDN 2 1500 1 350
SELECT
f.ClientID,f.flag,
case when flag = 1 then count(*) END as gtcount,
SUM(CASE WHEN flag = 1 THEN Amount END) AS totalAmountGreaterThan500,
case when flag = 2 then count(*) END as lscount,
SUM(CASE WHEN Flag = 2 THEN Amount END) AS AmountLessThan500,
from
( select ClientID, Amount,flag from #myTable)f
group by ClientID,f.flag
Try
SELECT ClientID,
SUM(CASE WHEN flag = 1 THEN 1 ELSE 0 END) AS gtcount,
SUM(CASE WHEN flag = 1 THEN Amount ELSE 0 END) AS totalAmountGreaterThan500,
SUM(CASE WHEN flag = 2 THEN 1 ELSE 0 END) AS lscount,
SUM(CASE WHEN Flag = 2 THEN Amount ELSE 0 END) AS AmountLessThan500
FROM Table1
GROUP BY ClientID
Output:
| CLIENTID | GTCOUNT | TOTALAMOUNTGREATERTHAN500 | LSCOUNT | AMOUNTLESSTHAN500 |
|----------|---------|---------------------------|---------|-------------------|
| FDN | 2 | 1500 | 1 | 350 |
| MMC | 2 | 1300 | 0 | 0 |
Here is SQLFiddle demo
Looks like your desired output is off -- there aren't any mmc records less than 500. You can accomplish this using sum with case for each of your fields, removing flag from the group by:
SELECT
ClientID,
SUM(CASE WHEN flag = 1 THEN 1 END) as gtcount,
SUM(CASE WHEN flag = 1 THEN Amount END) AS totalAmountGreaterThan500,
SUM(CASE WHEN flag = 2 THEN 1 END) as ltcount,
SUM(CASE WHEN Flag = 2 THEN Amount END) AS AmountLessThan500
from myTable
group by ClientID
SQL Fiddle Demo
On a different note, not sure why you need the Flag field. If it's just being used to denote less than records, just add the logic to the query:
SUM(CASE WHEN Amount <= 500 Then ...)