Multiple Where Clause in Single Table Select Query - sql

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*/

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

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

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

Multiple times Grouping with where in SQL Server

I have a source table like this
ProductName SaleReceipt SaleCode
--------------------------------
F-Apple 1001 1
F-Orange 1002 2
G-Rice 1003 3
G-Barile 1005 4
G-Oats 1006 1
V-Carrot 1007 4
V-Cabbage 1008 3
V-Potato 1009 1
V-Tomato 1010 1
Chocolate 1011 4
Cookies 1012 1
Cakes 1013 2
I need to create a report like this
30 Day delay 60 Day Delay 90 day delay 120 day delay
Fruits 1 1 0 0
Grains 1 0 1 1
Vegetables 2 0 1 1
Other category 1 1 0 1
The conditions to create the report are:
All ProductName start with F is grouped as fruits
All ProductName start with G is grouped as Grains
All ProductName start with V is grouped as Vegetables
Other product name go in the other category
30 day delay: count of (SaleReceipt) with a SaleCode=1
60 day delay: count of (SaleReceipt) with a SaleCode=2
90 day delay: count of (SaleReceipt) with a SaleCode=3
120 day delay: count of (SaleReceipt) with a SaleCode>=4
I could not find how to do grouping two times. I am using SQL Server 2014.
You can use case in a group by. Or use a lookup table:
select coalesce(c.name, 'Other category'),
sum(case when salescode = 1 then 1 else 0 end) as salecode_1,
sum(case when salescode = 2 then 1 else 0 end) as salecode_2,
sum(case when salescode = 3 then 1 else 0 end) as salecode_3,
sum(case when salescode = 4 then 1 else 0 end) as salecode_4
from t left join
(values ('F-%', 'Fruit'), ('G-%' , 'Grain'), ('V-%', 'Vegetable')
) c(pattern, name)
on t.productname like c.pattern
group by coalesce(c.name, 'Other category');

SQL Server : Joining two pivot tables

I'm trying to create join a table with itself. So for example below the table pivots based on the sum of D (Debits) and C (Credits) however I need to join the table with itself to add additional columns displaying count of an "D" entry and "C" plus two more additional columns showing the overall sum and overall count. How do I join the table below to create the additional columns?
Input table
GL_BU GL_Source GL_JE_Type GL_Amount Amount_Prefix
------------------------------------------------------------------
202 Payables Purchase Invoices 1234 C
202 Payables Purchase Invoices 123 D
202 Inventory Inventory 123 C
202 Payables Purchase Invoices 1234 C
Output Table
GL_BU GL_Source GL_JE_Type Amount D Amount C Count D Count C Total Count Total Amount
------------------------------------------------------------------------------------------
202 Spreadsheet XXXXX 1234 123 1 1 2 1357
202 Manual XXXXX 1234 123 2 2 4 1357
202 Manual XXXXX 1234 123 1 1 2 1357
202 Inventory XXXXX 1234 123 4 4 8 1357
202 Sales Order XXXXXX 1234 123 1 1 2 1357
Current Code
SELECT *
FROM
(SELECT
[GL_Business_Unit]
,[GL_Source]
,[GL_JE_Type]
,([GL_Amount])
,[Amount_Prefix]
FROM [03_rdm].[table_2013]) as t
Pivot(SUM([GL_Amount])
FOR [Amount_Prefix] IN (D,C)) AS pvt1
Current code link in SQLFiddle http://sqlfiddle.com/#!3/92369/2
Your sample data doesn't match your desired result so I'm guessing that this is what you need. You could use a PIVOT to get the result, but it seems that this would be much easier to get this using an aggregate function and some conditional logic via a CASE expression:
select
GL_BU,
GL_Source,
GL_JE_Type,
sum(case when Amount_Prefix = 'D' then GL_Amount else 0 end) Amount_D,
sum(case when Amount_Prefix = 'C' then GL_Amount else 0 end) Amount_C,
sum(case when Amount_Prefix = 'D' then 1 else 0 end) Count_D,
sum(case when Amount_Prefix = 'C' then 1 else 0 end) Count_C,
count(*) TotalCount,
sum(GL_Amount) TotalAmount
from table_2013
group by GL_BU, GL_Source, GL_JE_Type;
See SQL Fiddle with Demo

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