SQL - Help on Converting SQL Syntax to MS Access - sql

I need help on this, I need to convert a SQL syntax to MS Access syntax and I don't know how.
INSERT INTO SampleData2
SELECT
Object_Account, Descriptions, GL_Date, Document_Type,
Document_Number, Company, Subledger, Subledger_Type, ' ',
SUM(Actual_Amount * -1) AS TotalAmount,
(JE_Explantion) AS Explanation
FROM
SampleData
WHERE
CAST(Object_Account AS VARCHAR(20)) + Subledger + JE_Explantion
IN (SELECT CAST(Object_Account AS VARCHAR(20)) + Subledger + JE_Explantion
FROM SampleData
GROUP BY Object_Account, Subledger, JE_Explantion
HAVING COUNT(Object_Account) > 1)
GROUP BY
Object_Account, Descriptions, GL_Date, Document_Type,
Document_Number, Company, Subledger, Subledger_Type, Remarks,
JE_Explantion

MS Access uses & for string concatenation and doesn't support cast(). You might try:
INSERT INTO SampleData2
SELECT Object_Account, Descriptions, GL_Date, Document_Type, Document_Number,
Company, Subledger, Subledger_Type, ' ', Sum(Actual_Amount * -1) AS TotalAmount, (JE_Explantion) As Explanation
FROM SampleData as sd
WHERE EXISTS (SELECT 1
FROM SampleData as sd2
WHERE sd2.Object_Account = sd.Object_Account AND
sd2.Subledger = sd.Subledger AND
sd2.JE_Explantion = sd.JE_Explantion
GROUP BY Object_Account, Subledger, JE_Explantion
HAVING COUNT(Object_Account) > 1
)
GROUP BY Object_Account, Descriptions, GL_Date, Document_Type, Document_Number,
Company, Subledger, Subledger_Type, Remarks, JE_Explantion;

Related

Add count() to pivot table with totals

I have the following query: (simplified to one year)
WITH myTable
AS (SELECT cv.Company,
cv.Zip,
DATEPART(year, od.OrderDate) AS TheYear,
'' + DATEPART(year, od.OrderDate) AS TheYear2,
od.OrderNumber AS countOrders,
STUFF(
(
SELECT '| ' + FORMAT(DateVisited, 'MM-yyyy') + ' ' + MeetingType + ' '
FROM CustomerVisits cv1
WHERE(RIGHT(od.Email, LEN(od.Email) - CHARINDEX('#', od.email))) = cv1.EmailDomain
AND cv1.Zip = od.Zip
GROUP BY MeetingType,
FORMAT(DateVisited, 'MM-yyyy')
ORDER BY FORMAT(DateVisited, 'MM-yyyy') ASC FOR XML PATH('')
), 1, 1, '') AS Meetings,
od.FinalProductTotal AS total
FROM orders od
LEFT JOIN CustomerVisits cv ON od.Zip = cv.Zip
WHERE(RIGHT(od.Email, LEN(od.Email) - CHARINDEX('#', od.email))) = cv.EmailDomain
--AND od.OrderDate > #fromDate
AND approved = 1
AND cancelled = 0
AND od.OrderDate > '01-JAN-2010')
--and the PIVOT
SELECT Company,
Zip,
Meetings,
[02020] AS [Orders - 2020],
ISNULL(CAST([2020] AS INT), 0) AS [Total - 2020],
Total = CAST((SUM(ISNULL([2020], 0))) AS INT)
FROM myTable PIVOT(COUNT(countOrders) FOR TheYear2 IN([02020])) AS myPvt PIVOT(SUM(total) FOR TheYear IN([2020])) AS myPvt2
GROUP BY Company,
zip,
Meetings,
[2020],
[02020];
For it I'm trying to add the count of orders for each year, but I'm having problems understanding how should I proceed, I might be complicating it too much, but I'm not getting the proper count
I think that the myTable table is getting properly the "countOrders" but I'm not sure if I'm doing it properly on the pivot table to group by them and show the count by year
right now it kinda seems that is counting all the orders as I needed, however when I manually check on the DB seems that the data is off.
also, something I don't understand is why is it repeating the "company" so many times when I'm doing grouping by it?
example
I ended up case instead of pivot table. this solved the issue, with format:
CAST(SUM(CASE WHEN TheYear = 2010 THEN 1 ELSE 0 END)AS INT) AS [Orders - 2010] ,
CAST(SUM(CASE WHEN TheYear = 2010 THEN Total ELSE 0 END)AS INT) AS [Total - 2010],
in case it works for someone :)

Getting latest date in SQL query

I am running this query right now:
WITH Result AS (
select distinct
--pump.Product_PN,
--pump.product_name,
mot.Motor_pn,
Mot.Motor_name,
mas.STLAN AS Usage,
po.DATUV as change_date,
mot.[Procurement type],
mot.Plant as plant,
po.IDNRK AS Component_PN,
mak.MAKTG as component_name
FROM dbo.TBLMAST AS mas
INNER JOIN dbo.TBLSTPO AS po
ON mas.STLNR = po.STLNR
INNER JOIN dbo.TBLMAKT AS mak
ON mak.MATNR = po.IDNRK
--INNER JOIN ['Pumps to motor$'] AS pump
--ON pump.[Motor Product Number] = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
INNER JOIN Grundfos_motors AS mot
ON mot.Motor_PN = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
where mas.STLAN = '8' and mot.Motor_PN = '78085617' and mak.MAKTG like '%stator%'
)
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name, cast(getdate() as date) as Date_of_Extraction_date
from result
order by change_date DESC;
The result of this query is this:
From this query result, I want to run another query where the change_date is set to the latest. So I only want to retrieve the data for the latest date and rest is excluded. Something like:
Can anyone help?
You should be able to do:
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name,
cast(getdate() as date) as Date_of_Extraction_date
from (select r.*,
row_number() over (partition by motor_pn order by change_date desc) as seqnum
from result r
) r
where seqnum = 1;

Select Distinct date and Count

My sample table structure is:
TestDate
----------------------
2013-03-25 14:26:40.830
2013-03-20 13:37:39.763
2012-09-10 14:55:55.667
2013-03-20 13:33:20.480
And my query is :
SELECT DISTINCT
REPLACE(RIGHT(CONVERT(VARCHAR(20), TestDate, 106), 8), ' ', '-') AS TT
,(SELECT COUNT(*)
FROM Test bp
WHERE
CONVERT(VARCHAR(20), p.TestDate, 6) = CONVERT(VARCHAR(20), bp.TestDate, 6)) AS Posts
FROM Test p
I got a result:
TT Posts
Mar-2013 1
Mar-2013 2
Sep-2012 1
But I want a result:
TT Posts
Mar-2013 3
Sep-2012 1
But I am unable to find my mistake in my query. Thanks.
Are you trying to select the rows and count for each month?
If so - try something like this:
SELECT
YEAR(Testdate), MONTH(Testdate),
COUNT(*) totalPost
FROM
tableName
GROUP BY
YEAR(Testdate), MONTH(Testdate)
Update: if you insist on formatting that inside SQL Server (which I think is the wrong place to do this...) - then use something like this:
SELECT DISTINCT
SUBSTRING(DATENAME(MONTH, TestDate), 1, 3) + '-' + CAST(YEAR(TestDate) AS VARCHAR(4)),
YEAR(Testdate), MONTH(Testdate),
TotalPosts = COUNT(*)
FROM
tableName
GROUP BY
SUBSTRING(DATENAME(MONTH, TestDate), 1, 3) + '-' + CAST(YEAR(TestDate) AS VARCHAR(4)),
YEAR(Testdate), MONTH(Testdate)
ORDER BY
YEAR(Testdate), MONTH(Testdate)
You need to cast DATETIME into DATE first.
SELECT CAST(TestDate AS DATE) DATE_ONLY,
COUNT(*) totalPost
FROM tableName
GROUP BY CAST(TestDate AS DATE)

insert 0 into successive row with same fields value

I have a table containing the following line:
I'd like to create a view that displays the following result (without changing my original table) :
For each line having the same id,day,month and year I'd like to leave a single line with the cost and count and insert 0 in the others.
Here is a portable approach not requiring PARTITION. I have assumed you will not have the same datetimeIN value for more than one row in a group:
select t.id, t.day, t.month, t.year,
case when tm.id is null then 0 else t.cost end as cost,
case when tm.id is null then 0 else t.Count end as Count,
t.datetimeIN, t.datetimeOUT
from MyTable t
left outer join (
select id, day, month, year, min(datetimeIN) as minIN
from MyTable
group by id, day, month, year
) tm on t.id = tm.id
and t.day = tm.day
and t.month = tm.month
and t.year = tm.year
and t.datetimeIN = tm.minIN
You can do something like this:
SELECT id, day, month, year,
CASE WHEN nNum = 1 then cost else 0 end as cost,
CASE WHEN nNum = 1 then "Count" else 0 end as "Count",
datetimeIN, datetimeOUT
FROM (
SELECT id, day, month, year,
cost, "Count", datetimeIN, datetimeOUT,
row_number() OVER (PARTITION BY id, day, month, year
ORDER BY datetimeIN) as nNum
FROM TableName
) A
It uses row_number() to number the rows, and then a CASE statement to single out the first one and make it behave differently.
See it working on SQL Fiddle here.
or, using a common table expression:
with commonTableExp ([day], [month], [year], minDate) as (
select [day], [month], [year], min(datetimeIn)
from #temp
group by [day], [month], [year])
select id,
dt.[day],
dt.[month],
dt.[year],
case when datetimein = minDate then [cost] else 0 end,
case when datetimein = minDate then [count] else 0 end,
dateTimeIn
from #temp dt join commonTableExp cte on
dt.[day] = cte.[day] and
dt.[month] = cte.[month] and
dt.[year] = cte.[year]
order by dateTimeIn
Query
Select id, [day], [month], [year], Case When K.RowID = 1 Then [cost] Else 0 End as Cost, Case When K.RowID = 1 Then [count] Else 0 End as [count], [DateTimeIN], [DateTimeOut] From
(
select ROW_NUMBER() Over(Partition by id, [day], [month], [year] Order by ID ) as RowID, * From Testing
)K
Drop table Testing
Click here to see SQL Profiler details for Red Filter's Query
Click here to see SQL Profiler details for my Query
For More Information You can see SQL Fiddle

Getting error on nested query

I'm trying to develop a time sheet page on my web site, and this is my database stracture:
I want to get total hours(TimeSheetWeeks table's sum(timeFrom-timeTo)), total expense(TimeSheetWeeks's table's total amount) and total(TimSheetWeeks table's total amount+ compAllow table's total Amount).
This is my query I wrote to get my result:
;WITH w(tot, tid, eid, fd, td, am, mw) AS
(
SELECT Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID],
[FromDate],[ToDate], tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] ))
FROM
TimeSheet ts
INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM TimeSheetWeeks
GROUP BY TimeSheetID
) tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
SELECT timeFrom, timeTo, TimeSheetID
FROM TimeSheetWeeks
) AS tss ON tss.TimeSheetID=ts.TimeSheetID
WHERE ts.TimeSheetID=6
Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
)
SELECT tot, tid, eid, fd, td, Amount = am, totalHrs = RTRIM(mw/60) + ':' +
RIGHT('0'+ RTRIM(mw%60),2)
FROM w;
this quer causes an error saying
Column 'ca.amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
What goes wrong here? thanx in advance.
The ca.amount column is referenced in the w CTE, but is neither aggregated nor included in the GROUP BY clause:
;WITH w(tot, tid, eid, fd, td, am, mw) AS
(
SELECT Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID],
[FromDate],[ToDate], tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] ))
FROM
TimeSheet ts
INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM TimeSheetWeeks
GROUP BY TimeSheetID
) tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
SELECT timeFrom, timeTo, TimeSheetID
FROM TimeSheetWeeks
) AS tss ON tss.TimeSheetID=ts.TimeSheetID
WHERE ts.TimeSheetID=6
Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
)
SELECT tot, tid, eid, fd, td, Amount = am, totalHrs = RTRIM(mw/60) + ':' +
RIGHT('0'+ RTRIM(mw%60),2)
FROM w;
Either add it to GROUP BY or change the Total expression like this:
Total = tsw.amount + SUM(ca.amount)
depending upon what is the business rule for this query.
The error states the problem:
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ...
I'm not 100% sure, but my initial recommendation is to drop the "group by" in this clause. At best, it's redundant.
I'd also recommend trying each of the subclauses separately - make sure they're syntactically correct, make sure they're returning expected results.
IMHO...