How to combine rows based on id and sum a specific field - sql-server-2012

I am trying to combine rows that has similar identification. My table looks like this:
I want to fill either Debit or Credit if the value is '0.00' from another row with the same Source and then perform a Debit - Credit calculation, like this:
+------------+----------+---------+----------+----------+-------+
|Source | Property | ID | Debit | Credit |Balance|
+------------+----------+---------+----------+----------+-------+
|HOCV1900091 | PROP0003 | 1.01.86 | 16800.00 | 16800.00 | 0.00 |
+------------+----------+---------+----------+----------+-------+
How to it ?
I did:
SELECT
a.[Date],
a.[Source],
a.[Property],
a.[ID],
[Debit] = STUFF((SELECT DISTINCT Debit FROM #ProcSubLegder b WHERE b.Source = a.Source FOR XML PATH('')),1,2,''),
[Credit] = STUFF((SELECT DISTINCT Credit FROM #ProcSubLegder b WHERE b.Source = a.Source FOR XML PATH('')),1,2,''),
a.[Balance]
FROM #ProcSubLegder a
GROUP BY [Date],[Source],[Property],[ID],[Credit],[Balance]
But it gives me a very terrible result.

You should be aggregating only by the source and property:
SELECT
Source,
Property,
MAX(CASE WHEN ID LIKE '%[0-9].[0-9]%' THEN ID END) AS ID,
MAX(Debit) AS Debit,
MAX(Credit) AS Credit,
MAX(Credit) - MAX(Debit) AS Balance
FROM #ProcSubLegder
GROUP BY
Source,
Property;
Note: This answer assumes that each source/property group would have at most two records' worth of transactions. If not, the above answer would have to change, and you should show the actual data.

Related

postgresql total column sum

SELECT
SELECT pp.id, TO_CHAR(pp.created_dt::date, 'dd.mm.yyyy') AS "Date", CAST(pp.created_dt AS time(0)) AS "Time",
au.username AS "User", ss.name AS "Service", pp.amount, REPLACE(pp.status, 'SUCCESS', ' ') AS "Status",
pp.account AS "Props", pp.external_id AS "External", COALESCE(pp.external_status, null, 'indefined') AS "External status"
FROM payment AS pp
INNER JOIN auth_user AS au ON au.id = pp.creator_id
INNER JOIN services_service AS ss ON ss.id = pp.service_id
WHERE pp.created_dt::date = (CURRENT_DATE - INTERVAL '1' day)::date
AND ss.name = 'Some Name' AND pp.status = 'SUCCESS'
id | Date | Time | Service |amount | Status |
------+-----------+-----------+------------+-------+--------+---
9 | 2021.11.1 | 12:20:01 | some serv | 100 | stat |
10 | 2021.12.1 | 12:20:01 | some serv | 89 | stat |
------+-----------+-----------+------------+-------+--------+-----
Total | | | | 189 | |
I have a SELECT like this. I need to get something like the one shown above. That is, I need to get the total of one column. I've tried a lot of things already, but nothing works out for me.
If I understand correctly you want a result where extra row with aggregated value is appended after result of original query. You can achieve it multiple ways:
1. (recommended) the simplest way is probably to union your original query with helper query:
with t(id,other_column1,other_column2,amount) as (values
(9,'some serv','stat',100),
(10,'some serv','stat',89)
)
select t.id::text, t.other_column1, t.other_column2, t.amount from t
union all
select 'Total', null, null, sum(amount) from t
2. you can also use group by rollup clause whose purpose is exactly this. Your case makes it harder since your query contains many columns uninvolved in aggregation. Hence it is better to compute aggregation aside and join unimportant data later:
with t(id,other_column1,other_column2,amount) as (values
(9,'some serv','stat',100),
(10,'some serv','stat',89)
)
select case when t.id is null then 'Total' else t.id::text end as id
, t.other_column1
, t.other_column2
, case when t.id is null then ext.sum else t.amount end as amount
from (
select t.id, sum(amount) as sum
from t
group by rollup(t.id)
) ext
left join t on ext.id = t.id
order by ext.id
3. For completeness I just show you what should be done to avoid join. In that case group by clause would have to use all columns except amount (to preserve original rows) plus the aggregation (to get the sum row) hence the grouping sets clause with 2 sets is handy. (The rollup clause is special case of grouping sets after all.) The obvious drawback is repeating case grouping... expression for each column uninvolved in aggregation.
with t(id,other_column1,other_column2,amount) as (values
(9,'some serv','stat',100),
(10,'some serv2','stat',89)
)
select case grouping(t.id) when 0 then t.id::text else 'Total' end as id
, case grouping(t.id) when 0 then t.other_column1 end as other_column1
, case grouping(t.id) when 0 then t.other_column2 end as other_column2
, sum(t.amount) as amount
from t
group by grouping sets((t.id, t.other_column1, t.other_column2), ())
order by t.id
See example (db fiddle):
(To be frank, I can hardly imagine any purpose other than plain reporting where a column mixes id of number type with label Total of text type.)

Compare Two Different Fields In Oracle SQL

I have a requirement in which I have two main fields Amount CR and Amount DR.
Now the requirement is that this both amounts have different values like Trx Number, Bank Name ETC but have a common Reference Number.
There is only one record for every Refrence Number with a CR Amount, DR Amount respectivly.
For detaila see the table below:
Transaction Number
Bank Name
Reference Number
CR Amount
DR Amount
1
XYZ
1234
1000
2
ABC
1234
1000
3
DEF
1111
1000
4
TEST
1111
2300
So basically I want to compare CR and DR Amount based on the Reference Number. In the example Reference Number 1234 is ok and Reference Number 1111 should be listed.
How can I achieve this by an Oracle query?
Knowing that there is exactly one record with dr and one with cr amount you can make a self join over the reference number.
The 2 Trransactions for a Reference Number will be listed in one row:
select * from table t1
inner join table t2 on t1.referencenumber = t2.referencenumber
and t1.cr_amount is not null
and t2.dr_amount is not null
where t1.cr_amount <> t2.dr_amount
Add two analytical aggregated functions calculating the sum of CRand DB per the reference_number and compare them
case when
sum(cr_amount) over (partition by reference_number) =
sum(dr_amount) over (partition by reference_number) then 'Y' else 'N' end is_equ
This identifies the rows with reference_number where the sum is not equal.
In an additional query simple filter only the rows where the not equal sum.
with test as (
select a.*,
case when
sum(cr_amount) over (partition by reference_number) =
sum(dr_amount) over (partition by reference_number) then 'Y' else 'N' end is_equ
from tab a)
select
TRANSACTION_NUMBER, BANK_NAME, REFERENCE_NUMBER, CR_AMOUNT, DR_AMOUNT
from test
where is_equ = 'N'
TRANSACTION_NUMBER BANK REFERENCE_NUMBER CR_AMOUNT DR_AMOUNT
------------------ ---- ---------------- ---------- ----------
3 DEF 1111 1000
4 TEST 1111 2300
You can aggregate and use a case expression:
select reference_number,
sum(cr_amount), sum(db_amount),
(case when sum(cr_amount) = sum(db_amount)
then 'same' else 'different'
end)
from t
group by reference_number;

How to query data from two tables and group by two columns

I am using SQL Server and I have two huge tables containing all sorts of data. I would like to retrieve data on how many Latvian or Russian people live in each city.
The language column contains more than two languages but I would like to query only "Latvian" and "Russian"
Table1 (columns worth mentioning):
ID
ProjectID
Phone_nr
City
Table2 (Columns worth mentioning):
ID
ProjectID
Phone_nr
Language
I want the query to retrieve information something like this:
City1(RU) | Amount of Russians
City1(LT) | Amount of Latvians
City2(RU) | Amount of Russians
City2(LT) | Amount of Latvians
.. etc
Or something like this:
City1 | Amount of Russians | Amount of Latvians | Total amount of people
City2 | Amount of Russians | Amount of Latvians | Total amount of people
City3 | Amount of Russians | Amount of Latvians | Total amount of people
.. etc
I am wondering what would be the best solution to this? Should I use join or union or a simple select?
I came up with a query like this:
SELECT DISTINCT top 100 t.city, count(t.city) as 'Total amount of nr in city', count(*), l.language
FROM table1 l, table2 t
WHERE l.phone = t.phone and l.projectID = t.projektID
group by t.city, l.language
I believe the where clause is correct because both tables have phone numbers and Project IDs, it is important that the query selects with this where clause.
Unfortunately this doesn't quite work. It returns rows in this format:
City1 | Amount of y | total amount of numbers in this language
City1 | Amount of x | total amount of numbers in that language
It's close but it's not good enough. Note: I am using select top 100 just for testing, I will select everything once I have the query done right.
Can anyone help or point me in the right direction? Thank you
You can try using conditional aggregation -
SELECT t.city,
count(case when l.language='Russians' then 1 end) as 'Amount of Russians',
count(case when l.language='Latvians' then 1 end) as 'Amount of Latvians',
count(*) as 'Total amount of nr in city'
FROM table1 l inner join table2 t
on l.phone = t.phone and l.projectID = t.projektID
group by t.city
Note: It's always best to use join explicitly.
The logic of #Fahmi is correct. There is one more approach of using SUM instead of COUNT. I am adding the same for additional option to consider.
SELECT t.city,
SUM(case when l.language='Russians' then 1 else 0 end) as 'Amount of Russians',
SUM(case when l.language='Latvians' then 1 else 0 end) as 'Amount of Latvians',
count(*) as 'Total amount of nr in city'
FROM table1 l inner join table2 t
on l.phone = t.phone and l.projectID = t.projektID
group by t.city

Return count of total group membership when providers are part of a group

TABLE A: Pre-joined table - Holds a list of providers who belong to a group and the group the provider belongs to. Columns are something like this:
ProviderID (PK, FK) | ProviderName | GroupID | GroupName
1234 | LocalDoctor | 987 | LocalDoctorsUnited
5678 | Physican82 | 987 | LocalDoctorsUnited
9012 | Dentist13 | 153 | DentistryToday
0506 | EyeSpecial | 759 | OphtaSpecialist
TABLE B: Another pre-joined table, holds a list of providers and their demographic information. Columns as such:
ProviderID (PK,FK) | ProviderName | G_or_I | OtherColumnsThatArentInUse
1234 | LocalDoctor | G | Etc.
5678 | Physican82 | G | Etc.
9012 | Dentist13 | I | Etc.
0506 | EyeSpecial | I | Etc.
The expected result is something like this:
ProviderID | ProviderName | ProviderStatus | GroupCount
1234 | LocalDoctor | Group | 2
5678 | Physican82 | Group | 2
9012 | Dentist13 | Individual | N/A
0506 | EyeSpecial | Individual | N/A
The goal is to determine whether or not a provider belongs to a group or operates individually, by the G_or_I column. If the provider belongs to a group, I need to include an additional column that provides the count of total providers in that group.
The Group/Individual portion is relatively easy - I've done something like this:
SELECT DISTINCT
A.ProviderID,
A.ProviderName,
CASE
WHEN B.G_or_I = 'G'
THEN 'Group'
WHEN B.G_or_I = 'I'
THEN 'Individual' END AS ProviderStatus
FROM
TableA A
LEFT OUTER JOIN TableB B
ON A.ProviderID = B.ProviderID;
So far so good, this returns the expected results based on the G_or_I flag.
However, I can't seem to wrap my head around how to complete the COUNT portion. I feel like I may be overthinking it, and stuck in a loop of errors. Some things I've tried:
Add a second CASE STATEMENT:
CASE
WHEN B.G_or_I = 'G'
THEN (
SELECT CountedGroups
FROM (
SELECT ProviderID, count(GroupID) AS CountedGroups
FROM TableA
WHERE A.ProviderID = B.ProviderID
GROUP BY ProviderID --originally had this as ORDER BY, but that was a mis-type on my part
)
)
ELSE 'N/A' END
This returns an error stating that a single row sub-query is returning more than one row. If I limit the number of rows returned to 1, the CountedGroups column returns 1 for every row. This makes me think that its not performing the count function as I expect it to.
I've also tried including a direct count of TableA as a factored sub-query:
WITH CountedGroups AS
( SELECT Provider ID, count(GroupID) As GroupSum
FROM TableA
GROUP BY ProviderID --originally had this as ORDER BY, but that was a mis-type on my part
) --This as a standalone query works just fine
SELECT DISTINCT
A.ProviderID,
A.ProviderName,
CASE
WHEN B.G_or_I = 'G'
THEN 'Group'
WHEN B.G_or_I = 'I'
THEN 'Individual' END AS ProviderStatus,
CASE
WHEN B.G_or_I = 'G'
THEN GroupSum
ELSE 'N/A' END
FROM
CountedGroups CG
JOIN TableA A
ON CG.ProviderID = A.ProviderID
LEFT OUTER JOIN TableB
ON A.ProviderID = B.ProviderID
This returns either null or completely incorrect column values
Other attempts have been a number of variations of this, with a mix of bad results or Oracle errors. As I mentioned above, I'm probably way overthinking it and the solution could be rather simple. Apologies if the information is confusing or I've not provided enough detail. The real tables have a lot of private medical information, and I tried to translate the essence of the issue as best I could.
Thank you.
You can use the CASE..WHEN and analytical function COUNT as follows:
SELECT
A.PROVIDERID,
A.PROVIDERNAME,
CASE
WHEN B.G_OR_I = 'G' THEN 'Group'
ELSE 'Individual'
END AS PROVIDERSTATUS,
CASE
WHEN B.G_OR_I = 'G' THEN TO_CHAR(COUNT(1) OVER(
PARTITION BY A.GROUPID
))
ELSE 'N/A'
END AS GROUPCOUNT
FROM
TABLE_A A
JOIN TABLE_B B ON A.PROVIDERID = B.PROVIDERID;
TO_CHAR is needed on COUNT as output expression must be of the same data type in CASE..WHEN
Your problem seems to be that you are missing a column. You need to add group name, otherwise you won't be able to differentiate rows for the same practitioner who works under multiple business entities (groups). This is probably why you have a DISTINCT on your query. Things looked like duplicates which weren't. Once you've done that, just use an analytic function to figure out the rest:
SELECT ta.providerid,
ta.providername,
DECODE(tb.g_or_i, 'G', 'Group', 'I', 'Individual') AS ProviderStatus,
ta.group_name,
CASE
WHEN tb.g_or_i = 'G' THEN COUNT(DISTINCT ta.provider_id) OVER (PARTITION BY ta.group_id)
ELSE 'N/A'
END AS GROUP_COUNT
FROM table_a ta
INNER JOIN table_b tb ON ta.providerid = tb.providerid
Is it possible that your LEFT JOIN was going the wrong direction? It makes more sense that your base demographic table would have all practitioners in it and then the Group table might be missing some records. For instance if the solo prac was operating under their own SSN and Type I NPI without applying for a separate Type II NPI or TIN.

Split date column on the basis of years in the data

I am working with the AdventureWorks2014 database and am using the following query.
select
SUM(Purchasing.PurchaseOrderDetail.OrderQty) as 'Total Quantity',
SUM(Purchasing.PurchaseOrderDetail.LineTotal) as 'Total Amount',
Purchasing.PurchaseOrderHeader.VendorID
from Purchasing.PurchaseOrderDetail
inner join Purchasing.PurchaseOrderHeader
on Purchasing.PurchaseOrderDetail.PurchaseOrderID = Purchasing.PurchaseOrderHeader.PurchaseOrderID
group by Purchasing.PurchaseOrderHeader.VendorID, DATEPART(year,Purchasing.PurchaseOrderHeader.OrderDate)
order by Purchasing.PurchaseOrderHeader.VendorID
This gives me the following output.
|------------------------------------|
|Total Quantity|Total Amount|VendorID|
|15 |694.1655 | 1492|
|288 |12370.239 | 1492|
|45 |1931.7375 | 1492|
|180 |7682.6295 | 1492|
|9350 |150404.1 | 1494|
|1650 |26541.9 | 1494|
|550 |8847.3 | 1494|
|16500 |265419 | 1494|
|------------------------------------|
From what i understand, this is each year's data, i.e,the values 2011,2012,2013 and 2014, for each vendor. Which is why each vendor is repeated 4 times.
I need to have each of these years as a separate column in the output as follows.
|--------------------------------------------------------------------------------|
|Total Quantity|Total Amount|VendorID|2011Amount|2012Amount|2013Amount|2014Amount|
|--------------------------------------------------------------------------------|
Any thoughts?
Pivot Method, make sure you first prepare the query how you want prior to pivoting.
;WITH cte AS (
SELECT
DATEPART(year,poh.OrderDate) as [Year]
,SUM(pod.OrderQty) OVER (PARTITION BY DATEPART(year,poh.OrderDate)) as TotalQuantity
,SUM(pod.LineTotal) OVER (PARTITION BY DATEPART(year,poh.OrderDate)) as TotalAmount
,pod.LineTotal as Amount
FROM
Purchasing.PurchaseOrderDetail pod
INNER JOIN Purchasing.PurchaseOrderHeader poh
ON pod.PurchaseOrderId = poh.PurchaseOrderId
)
SELECT *
FROm
cte
PIVOT (
SUM(Amount)
FOR [Year] IN ([2011],[2012],[2013],[2014])
) p
Conditional Aggregation Method
SELECT
SUM(pod.OrderQty) as TotalQuantity
,SUM(pod.LineTotal) as TotalAmount
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2011 THEN pod.LineTotal ELSE 0 END) as [2011Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2012 THEN pod.LineTotal ELSE 0 END) as [2012Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2013 THEN pod.LineTotal ELSE 0 END) as [2013Amount]
,SUM(CASE WHEN DATEPART(year,poh.OrderDate) = 2014 THEN pod.LineTotal ELSE 0 END) as [2014Amount]
FROM
Purchasing.PurchaseOrderDetail pod
INNER JOIN Purchasing.PurchaseOrderHeader poh
ON pod.PurchaseOrderId = poh.PurchaseOrderId
In this case I think I would go with the conditional aggregation method..... Please note I used Table Aliases to refer to the table rather than continuing to type the long names it is a good habit to get into.
This exact code is of course untested because you did not include test data and desired result but the techniques are the most standard way of doing this. Note when more than 1 column is involved in aggregation it is typically easiest to do conditional aggregation.