MSSQL 2005 server SUM by grouping - sql

I have a SQL query which gives me the result of invoice lines.
I got all true information, but I want to group it. The problem is that I already grouped it.
There is my code:
WITH Agg1 AS(
SELECT [Ship-to Name] As 'Pirkejas',
[Order No_]
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Header]
)
SELECT sil.[Document No_] as 'Pardavimo nr.',
sil.[Shipment Date] as 'Siuntos data',
sil.[Order No_] as 'Musu užsak. nr.',
sil.[Customer Order No_] AS 'Klientio užsak. nr.',
a.[Pirkejas],
CAST(sil.[Unit Volume]*sil.[Quantity] AS DECIMAL(16,4)) AS 'Tūris',
CAST(sil.[Unit Price]*sil.[Quantity] AS DECIMAL(16,2)) AS 'Suma €'
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Line] sil
LEFT JOIN Agg1 a
ON a.[Order No_] = sil.[Order No_]
WHERE sil.[Sell-to Customer No_] = 'PRK0820'
AND sil.[Shipment Date] > '2015-09-01 00:00:00.000'
AND sil.[Shipment Date] <= dateadd(day,datediff(day,0,GETDATE()),0) AND sil.[Document No_] = 'TRV0093219'
GROUP BY
[Unit Price],[Quantity],
sil.[Document No_],
sil.[Unit Volume],
sil.[Shipment Date],
sil.[Order No_],
sil.[Customer Order No_],
a.[Pirkejas]
ORDER BY sil.[Shipment Date] DESC
The result I get:
TRV0093219 2015-12-22 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.2400 17.35
TRV0093219 2015-12-22 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.8140 121.00
TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00
TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00
TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 0.0000 0.00
The result I need to get:
TRV0093219 2015-12-21 00:00:00.000 SO0184846 IO1710379-C Living AS, Lade 1.054 138.35

Remove those columns from GROUP BY and add an aggregate function:
WITH Agg1 AS(
SELECT [Ship-to Name] As 'Pirkejas',
[Order No_]
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Header]
)
SELECT sil.[Document No_] as 'Pardavimo nr.',
sil.[Shipment Date] as 'Siuntos data',
sil.[Order No_] as 'Musu užsak. nr.',
sil.[Customer Order No_] AS 'Klientio užsak. nr.',
a.[Pirkejas],
SUM(CAST(sil.[Unit Volume]*sil.[Quantity] AS DECIMAL(16,4))) AS 'Tūris',
SUM(CAST(sil.[Unit Price]*sil.[Quantity] AS DECIMAL(16,2))) AS 'Suma €'
FROM [Artilux].[dbo].[Trivilita UAB$Sales Invoice Line] sil
LEFT JOIN Agg1 a
ON a.[Order No_] = sil.[Order No_]
WHERE sil.[Sell-to Customer No_] = 'PRK0820'
AND sil.[Shipment Date] > '2015-09-01 00:00:00.000'
AND sil.[Shipment Date] <= dateadd(day,datediff(day,0,GETDATE()),0) AND sil.[Document No_] = 'TRV0093219'
GROUP BY
sil.[Document No_],
sil.[Shipment Date],
sil.[Order No_],
sil.[Customer Order No_],
a.[Pirkejas]
ORDER BY sil.[Shipment Date] DESC

Related

How to GroupBy based on GetDate() , CASE and fixed column aliases

I am trying to create an openAR file and I am stuck trying to group this data by Customer and Invoice. The file will get created daily.
[FILE DATE]
[CUSTOMER ID]
[INVOICE NUMBER]
[INVOICE TYPE]
[INVOICE DATE]
[OPEN INVOICE AMOUNT]
01/22/2021
00100000
INV1000
INV
06/08/2020
1000
01/22/2021
00100000
INV1001
INV
06/15/2020
50
01/22/2021
00100000
INV1002
INV
08/20/2020
50
01/22/2021
00100000
INV1005
CM
10/18/2020
-100
01/22/2021
00100000
PAY1000
PAY
06/15/2020
-750
01/22/2021
00100000
PAY1000
PAY
06/15/2020
820
I am trying to group this data as I need to Sum lines of the open invoice amounts per each invoice. The file will get exported automatically to another company to process the AR info. The column headers need to be exact as they are below. I usually use Aliases to group but with 2 word fixed Column headers, I am a bit stuck to figure out how to group this code. Also, how would you group GETDATE() and that CASE statement?
SELECT
CONVERT (nvarchar(30), GETDATE(), 101) as [FILE DATE],
GACC.BPR_0 as [CUSTOMER ID],
GACC.NUM_0 as [INVOICE NUMBER],
GACC.TYP_0 as [INVOICE TYPE],
Case
When GACC.TYP_0 in ('INV', 'CM') Then CONVERT (nvarchar(30), SI.BPRDAT_0 , 101)
Else CONVERT (nvarchar(30), PAY.ACCDAT_0 , 101)
End as [INVOICE DATE],
(GACC.AMOUNT_0 * GACC.SNS_0) as [OPEN INVOICE AMOUNT] --- want to SUM and group this column for each INV#
FROM dbo.GACCDUDATE as GACC
left join dbo.SINVOICE as SI --- Invoice Table
on GACC.NUM_0 = SIV.NUM_0
left join dbo.PAYMENT as PAY -- Payment Table
on PAY.NUM_0 = GACC.NUM_0
Thank you so much for helping me to group this for each customer, invoice, sum of open amount.
Edit - Desired output
[FILE DATE]
[CUSTOMER ID]
[INVOICE NUMBER]
[INVOICE TYPE]
[INVOICE DATE]
[OPEN INVOICE AMOUNT]
01/22/2021
00100000
INV1000
INV
06/08/2020
1000
01/22/2021
00100000
INV1001
INV
06/15/2020
50
01/22/2021
00100000
INV1002
INV
08/20/2020
50
01/22/2021
00100000
INV1005
CM
10/18/2020
-100
01/22/2021
00100000
PAY1000
PAY
06/15/2020
70
Using CTE to reference aliases. Alternatively, as in my comment just group on "CONVERT (nvarchar(30), GETDATE(), 101)" or "(GACC.AMOUNT_0 * GACC.SNS_0)"
With MyInvoices as
(
SELECT
CONVERT (nvarchar(30), GETDATE(), 101) as [FILE DATE],
GACC.BPR_0 as [CUSTOMER ID],
GACC.NUM_0 as [INVOICE NUMBER],
GACC.TYP_0 as [INVOICE TYPE],
Case
When GACC.TYP_0 in ('INV', 'CM') Then CONVERT (nvarchar(30), SI.BPRDAT_0 , 101)
Else CONVERT (nvarchar(30), PAY.ACCDAT_0 , 101)
End as [INVOICE DATE],
(GACC.AMOUNT_0 * GACC.SNS_0) as [OPEN INVOICE AMOUNT]
FROM dbo.GACCDUDATE as GACC
left join dbo.SINVOICE as SI
on GACC.NUM_0 = SIV.NUM_0
left join dbo.PAYMENT as PAY
on PAY.NUM_0 = GACC.NUM_0
)
select [FILE DATE], [CUSTOMER ID], [INVOICE NUMBER], [INVOICE TYPE],[INVOICE DATE],[OPEN INVOICE AMOUNT] from MyInvoices
group by [FILE DATE], [CUSTOMER ID], [INVOICE NUMBER], [INVOICE TYPE],[INVOICE DATE]

JOIN two tables but only return rows from Table 1 that match Table 2

Good day
I have two tables I need to Join , Transfer Excise Tbl and Value Entry.
Transfer Excise Tbl: No must match the Item no in the Value Entry table. I did do a comparison for Items not in Transfer Excise that is in Value entry and found a few.
Transfer Excise Tbl:
Starting Date No_ Excise Location Location Code Unit Rate Excise Type Code Unit Of Measure Code Litre Conversion Factor
----------------------- -------------------- --------------- ------------- --------------------------------------- ---------------- -------------------- ---------------------------------------
2013-02-28 00:00:00.000 600011263 NONBOND ~DUTY PAID 2.70000000000000000000 UWNEPACK LITRES 1.33333000000000000000
2014-02-27 00:00:00.000 600011263 NONBOND ~DUTY PAID 2.87000000000000000000 UWNEPACK LITRES 1.33333000000000000000
2015-02-26 00:00:00.000 600011263 NONBOND ~DUTY PAID 3.07000000000000000000 UWNEPACK LITRES 1.33333000000000000000
2016-02-25 00:00:00.000 600011263 NONBOND ~DUTY PAID 3.31000000000000000000 UWNEPACK LITRES 1.33333000000000000000
Value Entry Table:
Item No_ Location Code Gen_ Bus_ Posting Group Invoiced Quantity
-------------------- ------------- ----------------------- ---------------------------------------
F00330 VINI EXSA -10.00000000000000000000
F00331 VINI EXSA -30.00000000000000000000
F00332 VINI EXSA -40.00000000000000000000
I want to write the query to exclude duplicates as the script below still creates duplicates. The PK is Item No and the FK is Location Code. you will see on the Transfer excise table that for each year I new unit rate was supplied for a specific Item and Location
SELECT DISTINCT a.[Starting Date],
b.[Posting Date],
b.[Item No_],
b.[Invoiced Quantity],
a.[Litre Conversion Factor],
a.[Unit Rate] ,
a.[Location Code],
a.[Excise Location],
a.[Excise Type Code],
a.[Unit Of Measure Code]
FROM [Transfer Excise Tbl] a JOIN [Spier Live$Value Entry] b
ON a.[No_] = b.[Item No_]
WHERE b.[Posting Date] > '2013-02-26 '
AND b.[Location Code] = a.[Location Code]
AND b.[Gen_ Bus_ Posting Group] IN ('LOCA','EXSA')
AND b.[Posting Date] >= a.[Starting Date]
AND b.[Invoiced Quantity] <>0
First of all, there is something wrong with your [Value Entry] table.
1) In your query you refer to [Posting Date] column, but there is no such column in your example data.
Now, if I have well understood the scenario, I think your problem is related to how you join lines from the two tables.
I get more lines than you expect because you JOIN each line in [Value Entry] with ALL lines in [Transfer Excise Tbl] with a [Starting Date] older, not only the LAST (valid) line.
To solve the problem you should pre-calc the period of validity of your [Transfer Excise Tbl] line finding the [End Date] of each line, and then you will
JOIN b.[Posting Date] BETWEEN a.[Starting Date] AND a.[End Date]
final query will be something like:
;WITH
EndDates as (-- add [End Date] to [Transfer Excise Tbl]
select t1.*, ISNULL([End Date], CONVERT(date, '9999-12-31', 121)) [End Date]
from [Transfer Excise Tbl] t1
outer apply (
select MIN([Starting Date]) [End Date]
from [Transfer Excise Tbl]
where [Starting Date] > t1.[Starting Date]
) T2
)
SELECT DISTINCT a.[Starting Date],
b.[Posting Date],
b.[Item No_],
b.[Invoiced Quantity],
a.[Litre Conversion Factor],
a.[Unit Rate] ,
a.[Location Code],
a.[Excise Location],
a.[Excise Type Code],
a.[Unit Of Measure Code]
FROM [EndDates] a JOIN [Spier Live$Value Entry] b ON a.[No_] = b.[Item No_] AND b.[Posting Date] BETWEEN a.[Starting Date] AND a.[End Date]
WHERE b.[Posting Date] > '2013-02-26 '
AND b.[Location Code] = a.[Location Code]
AND b.[Gen_ Bus_ Posting Group] IN ('LOCA','EXSA')
AND b.[Invoiced Quantity] <> 0
It should return only the number of rows you expect
I hope this helps

Find max Date Value for a subqueried list

This is admittedly atrocious code. I'm looking to not only make it work, but make it work well. I would like to get the max date for each Claim Adjustment Type Code.
Current code:
SELECT a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date]
FROM #tmp_hic_dupes_list_final_not10 a
join (select a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date]
from #tmp_hic_dupes_list_final_not10 as a
where
a.[Claim Adjustment Type Code] in (SELECT a.[Claim Adjustment Type Code]
FROM
#tmp_hic_dupes_list_final_not10 b where
a.[Current HIC #] = b.[Current HIC #] and
a.[Claim Type Code] = b.[Claim Type Code] and
a.[Provider Oscar #] = b.[Provider Oscar #] and
a.[Claim From Date] = b.[Claim From Date] and
a.[Claim Thru Date] = b.[Claim Thru Date] and
a.[Claim Adjustment Type Code] = b.[Claim Adjustment Type Code]
HAVING
COUNT(*) > 1)) b on a.[Current ClaimID] = b.[Current ClaimID]
--WHERE a.[Claim Effective Date] < b.[Claim Effective Date]
group by a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date]
having a.[Claim Effective Date] = max(a.[Claim Effective Date])
Current reuslts:
[Current ClaimID] [Claim Adjustment Type Code] [Claim Effective Date]
37274993770 1 2014-02-07 00:00:00.000
37274993771 2 2014-02-07 00:00:00.000
37509451954 1 2014-02-21 00:00:00.000
37509451955 2 2014-02-21 00:00:00.000
38168035124 1 2014-04-04 00:00:00.000
38168035125 2 2014-04-04 00:00:00.000
Expected results:
[Current ClaimID] [Claim Adjustment Type Code] [Claim Effective Date]
38168035124 1 2014-04-04 00:00:00.000
38168035125 2 2014-04-04 00:00:00.000
You could add a RANK() function to the existing code, RANK() each group of type codes by descending date, and then in outer query, pick off just the records with rank = 1
SELECT [Current ClaimID], [Claim Adjustment Type Code], [Claim Effective Date] FROM (
SELECT a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date],
RANK() OVER (PARTITION BY a.[Claim Adjustment Type Code] ORDER BY a.[Claim Effective Date] DESC) AS RankClaimTypeByDate
FROM #tmp_hic_dupes_list_final_not10 a
join (select a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date]
from #tmp_hic_dupes_list_final_not10 as a
where
a.[Claim Adjustment Type Code] in (SELECT a.[Claim Adjustment Type Code]
FROM
#tmp_hic_dupes_list_final_not10 b where
a.[Current HIC #] = b.[Current HIC #] and
a.[Claim Type Code] = b.[Claim Type Code] and
a.[Provider Oscar #] = b.[Provider Oscar #] and
a.[Claim From Date] = b.[Claim From Date] and
a.[Claim Thru Date] = b.[Claim Thru Date] and
a.[Claim Adjustment Type Code] = b.[Claim Adjustment Type Code]
HAVING
COUNT(*) > 1)) b on a.[Current ClaimID] = b.[Current ClaimID]
--WHERE a.[Claim Effective Date] < b.[Claim Effective Date]
group by a.[Current ClaimID], a.[Claim Adjustment Type Code], a.[Claim Effective Date]
having a.[Claim Effective Date] = max(a.[Claim Effective Date]) ) d WHERE RankClaimTypeByDate = 1 -- Select the 1st ranked record within each [Claim Adjustment Type Code]
One easy way to do this would be to add a where clause that limits the result to those rows for which there does not exist any row with the same Claim Adjustment Type Code and a later Claim Effective Date.
Try adding this to your query:
WHERE NOT EXISTS (
SELECT 1
FROM #tmp_hic_dupes_list_final_not10
WHERE [Claim Adjustment Type Code] = a.[Claim Adjustment Type Code]
AND [Claim Effective Date] > a.[Claim Effective Date]
)
Also, you can probably get rid of the last having clause as it doesn't seem to do anything (but without test data I'm not 100% sure).
A possibility is to join on a subset of the same data you're selecting from that grabs just the MAX([Claim Effective Date]) for each [Claim Adjustment Type Code]. This is more of an additional step on the results of the existing query rather than being a part of it, though (in case that's an option for you):
SELECT a.[Current ClaimID]
,a.[Claim Adjustment Type Code]
,a.[Claim Effective Date]
FROM #tmp_hic_dupes_list_final_not10 a
INNER JOIN (SELECT [ClaimAdjustment Type Code], MAX([Claim Effective Date]) AS MostRecentEffectiveDate
FROM #tmp_hic_dupes_list_final_not10
GROUP BY [ClaimAdjustment Type Code]) AS XYZ
ON a.[Claim Effective Date] = XYZ.MostRecentEffectiveDate
ORDER BY a.[Current ClaimID], a.[ClaimAdjustment Type Code]

SQL query sum unique records

I'm trying to sum all sales of one period of time of a selling vehicle. The problem is that every product sold is one row whit amount and price and a total of the bill and the bill number.
So I have 2 options: multiply ever sold product amount whit the price and sum that. Or take the bill remove double rows and sum that. I chosen for the second option.
So now I have a [Location Code] (selling vehicle), [Bill No] and a [Total Price].
So I get:
0001 0001/00277343 10,26000000000000000000
0001 0001/00277343 10,26000000000000000000
0001 0001/00277343 10,26000000000000000000
0001 0001/00277343 10,26000000000000000000
0001 0001/00277345 10,33000000000000000000
0001 0001/00277345 10,33000000000000000000
0001 0001/00277345 10,33000000000000000000
0001 0001/00277347 24,35000000000000000000
0001 0001/00277348 30,31000000000000000000
0001 0001/00277348 30,31000000000000000000
0001 0001/00277349 2,69000000000000000000
As you see double entries, because on one bill there are more than one item. So now I just want to sum the unique price so that I get
0001 1822,50
At this moment I'm only as far as this:
select [Location Code], [Bill No_] , Price from [Item Ledger Entry]
where [Location Code] = '0001' and [Document Date] = '01.04.2015'
I tried several but none is working. Best result gives this, but not summed
select distinct[Bill No_], [Location Code] , Price from [Item Ledger Entry]
where [Location Code] = '0001' and [Document Date] = '01.04.2015'
I think you are looking for this:
SELECT [Location Code], [Bill No_], SUM(Price) AS Price
FROM (SELECT DISTINCT [Location Code], [Bill No_] , Price from [Item Ledger Entry]
WHERE [Location Code] = '0001' and [Document Date] = '01.04.2015') t
GROUP BY [Location Code], [Bill No_]
select [Location Code], [Bill No_] , SUM(Price) from [Item Ledger Entry]
where [Location Code] = '0001' and [Document Date] = '01.04.2015'
group by [Location Code], [Bill No_]

Get the sum() in a WHERE clause

I have this SQL, but it dosen't work correctly.
SELECT [Customer No_], SUM(Amount) AS SumDebitor, [Posting Date]
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_], [Posting Date]
HAVING ([Customer No_] = '45')
What i want, is get the total SUM() of all posts from before my date.
Right now i get more that 5000 results, sum of everyday.
Can someone help me on the right way?
you should not have posting date with grouping (if you do posting date grouping .. you will get all posting date sum independently)
and moreover having clause is not required .. your query should be like following
SELECT [Customer No_], SUM(Amount) AS SumDebitor
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
And ([Customer No_] = '45')
GROUP BY [Customer No_]
or as below (if you need count for all customer)
SELECT [Customer No_], SUM(Amount) AS SumDebitor
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_]