only return records count() = 1 - sql

I have this table called myTable
Posting Date|Item No_|Entry Type|
2015-01-13|1234|1
2015-01-13|1234|1
2015-01-12|1234|1
2015-01-12|5678|1
2015-02-12|4567|1
What I want, is only return result where a [Item No_] is ind the table 1 time.
So in this example of my table, i only want to return [Item No_] 5678 and 4567, because there only are one record in it. And then ignore [Item No_] 1234
This is my SQL i have tried, but something is wrong. Can anyone help me?
SELECT [Item No_], [Posting Date], COUNT([Item No_]) AS Antal
FROM myTable
GROUP BY [Entry Type], [Posting Date], [Item No_]
HAVING ([Entry Type] = 1) AND (COUNT([Item No_]) = 1)
ORDER BY [Posting Date] DESC

select [Item No_]
from myTable
group by [Item No_]
having count(*)=1

Remove Posting Date from group by
SELECT [Item No_],Entry Type, COUNT([Item No_]) AS Antal
FROM myTable
GROUP BY [Entry Type], [Item No_]
HAVING COUNT([Item No_]) = 1
or if you want other details use a subquery
SELECT [Item No_],
Entry Type,
Posting Date
FROM myTable a
WHERE EXISTS (SELECT 1
FROM myTable b
where a.[Item No_]=b.[Item No_]
GROUP BY [Entry Type],
[Item No_]
HAVING Count(1) = 1)
ORDER BY [Posting Date] DESC
or window function
;WITH cte
AS (SELECT [Item No_],
[Posting Date],
[Entry Type],
Row_number()OVER (Partition BY [Entry Type], [Item No_] ORDER BY [Item No_]) RN
FROM myTable)
SELECT *
FROM cte a
WHERE NOT EXISTS (SELECT 1
FROM cte b
WHERE a.[Item No_] = b.[Item No_]
AND rn > 1)
ORDER BY [Posting Date] DESC

You can use ROW_Number() in Sql Server
select * from (
SELECT [Item No_], [Posting Date],
Row_Number() over (Parition by [Item No_]
order by [Item No]) RN
FROM myTable
)D
where D.RN=1

Related

SQL WHERE/HAVING Condition

Currently I'm working in a forecasting project to estimate cash flow. This how the SQL query looks like:
SELECT [Date] AS ds, SUM([Sales Amount]) AS y, [Item ID]
FROM dbo.[Table]
GROUP BY [Date], [Item ID]
ORDER BY ds;
And in order to forecast sales I use an R package that strictly request that there has to be at least 2 instances where the forecast value(Sales) appears.
However there some instances in my query where an item it has been transacted just once.
Could you help me with an HAVING or WHERE condition where excludes all the items that were transacted just once?
Thanks!
I would add a count and use that:
SELECT ds, y, [Item ID]
FROM (SELECT [Date] AS ds, SUM([Sales Amount]) AS y, [Item ID],
COUNT(*) OVER (PARTITION BY [Item ID]) as cnt
FROM dbo.[Table]
GROUP BY [Date], [Item ID]
) t
WHERE cnt >= 2
ORDER BY ds;
You can use an extra filtering condition in a WHERE clause:
SELECT
[Date] AS ds
,SUM([Sales Amount]) AS y
,[Item ID]
FROM dbo.[Table]
WHERE [Item ID] in ( -- filters out the items with less than 2 samples
select distinct [Item ID]
from dbo.[Table]
group by [Item ID], [Date] having count(*) > 1
)
GROUP BY [Date]
,[Item ID]
ORDER BY ds

Meeting 2 conditions in 2 different columns

I'm trying to run a query where I need very specific conditions to be met:
Sales code is All
Item has Original Price flag set
Item has a price with no Original Price flag set that is the same as the Price with Original Price flag set
Price without Original price flag set must be created after the price with Original price flag
Currently I am using the following query to get the information I need;
select [item no_], [variant code],[unit price including vat],
[original price], [Starting Date], [Ending Date] from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000'
This is the example result:
1 means Original Price flag is set and 0 means it is not
The result I need from this query would be to only show these two:
I am assuming you are working with SQL Server as your current query syntax suggests.
If, so you can use lag() :
select sp.*
from (select sp.*,
lag([original price]) over (partition by [item no_] order by [Starting Date]) as prev_price
from [Sales Price] sp
where [Sales Code] = 'all'
) sp
where ([original price] = 1 or prev_price = 1);
let me know if you need me to explain; else its pretty straight forward.
select a.*
from (
select [item no_]
, [variant code]
,[unit price including vat]
, [original price]
, [Starting Date]
, [Ending Date]
,Column_Test = case when ( [original price] = 1 and [original price] = 0 ) and ([Starting Date]<[Ending Date]) then 1 else 0 end
from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000'
) a
where Column_Test = 1

Workaround for PIVOT statement

I have this query, is taking like 2 minutes to resolve, I need to find a workaround, I know that UNPIVOT has a better solution using CROSS APPLY, is there anything similar for PIVOT?
SELECT [RowId], [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province]
FROM
(SELECT fd.[RowId], fc.[ColumnName], fd.[Value]
FROM dbo.FileData fd
INNER JOIN dbo.[FileColumn] fc
ON fc.[FileColumnId] = fd.[FileColumnId]
WHERE FileId = 1
AND TenantId = 1) x
PIVOT
(
MAX(Value)
FOR [ColumnName] IN ( [invoice date], [GL], [Entité], [001], [Loc], [Centre Cout], [Compte_1], [Interco_1], [Futur_1], [Department], [Division], [Compagnie], [Localisation], [Centre/Cout], [Compte], [Interco], [Futur], [Account], [Mobile], [Last Name], [First Name], [license fee], [GST], [HST], [PST], [Foreign Tax], [Sales Tax License], [Net Total], [Total], [ServiceType], [Oracle Cost Center], [CTRL], [EXPENSE], [Province])
) AS p
Pivots are great, but so are Conditional Aggregations. Also, there would be no datatype conficts or conversions necessary
SELECT [RowId]
,[invoice date] = max(case when [FileColumnId] = ??? then Value end)
,[GL] = max(case when [FileColumnId] = ??? then Value end)
,... more fields
FROM dbo.FileData fd
WHERE FileId = 1
AND TenantId = 1
Group By [RowId]
EDIT
You could add back the join to make it more readable.

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_]