How do you do a where clause with a select statement as a value - sql

I'm trying to get the total amount from the next month's record.
SELECT TOP (1000)
[DEMAND_POINT_ID],
[DPM_XREF_ID],
[UTIL_TYPE],
[ACCOUNT_ID],
[REV_YR_MNTH],
[TOTAL_AMOUNT],
(SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int)) AS nextmonth,
(SELECT de2.[TOTAL_AMOUNT]
FROM [DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de2
WHERE de2.ACCOUNT_ID = de.ACCOUNT_ID
AND de2.REV_YR_MNTH = (SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int))) AS nextamount
FROM
[DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de
WHERE
ACCOUNT_ID =1
ORDER BY
ACCOUNT_ID, de.REV_YR_MNTH
The value nextmonth creates the next month's rev_yr_mnth correctly however when I try to use this created value in the where clause it brings back nothing in the nextamount field.
It's like it does not recognize the created value as a true value. What do I need to do to have the where clause recognize the value?

Using CTE you can add condition on nextmonth.
With CTE As (
SELECT TOP (1000)
[DEMAND_POINT_ID],
[DPM_XREF_ID],
[UTIL_TYPE],
[ACCOUNT_ID],
[REV_YR_MNTH],
[TOTAL_AMOUNT],
(SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int)) AS nextmonth,
(SELECT de2.[TOTAL_AMOUNT]
FROM [DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de2
WHERE de2.ACCOUNT_ID = de.ACCOUNT_ID
AND de2.REV_YR_MNTH = (SELECT CAST(LEFT((SELECT CONVERT(varchar, DATEADD(month, 1, LEFT(REV_YR_MNTH, 4) + '-' + RIGHT(REV_YR_MNTH, 2) + '-' + '01'), 112)), 6) AS int))) AS nextamount
FROM
[DEQEnergyUsage].[dbo].[DST_ENERGY_USAGE_AGGR] de
WHERE
ACCOUNT_ID =1
ORDER BY
ACCOUNT_ID, de.REV_YR_MNTH
)
select * from CTE
-- Where nextmonth condition

Related

GET current month plus last 13 month SQL

I would like to modify the query which will also include the data from this month.
SELECT TOP (14) Entity = 'Total_Group'
, Scenario = 'Actual'
, Date = TRIM(CAST(YEAR(DATEADD(MONTH, ROW_NUMBER() OVER(ORDER BY object_id) * -1, GETDATE())) as CHAR(4))
+ ' P'
+ CAST(MONTH(DATEADD(MONTH, ROW_NUMBER() OVER(ORDER BY object_id) * -1, GETDATE())) as VARCHAR(2)))
FROM [sys].[all_objects]
the result of this table
starts with 2022P12, but would like to include current month too so it should start with 2023P1
Try this:
SELECT TOP (14) Entity = 'Total_Group'
, Scenario = 'Actual'
, Date = TRIM(CAST(YEAR(DATEADD(MONTH, ROW_NUMBER() OVER(ORDER BY object_id) * -1 + 1, GETDATE())) as CHAR(4))
+ ' P'
+ CAST(MONTH(DATEADD(MONTH, ROW_NUMBER() OVER(ORDER BY object_id) * -1 + 1, GETDATE())) as VARCHAR(2)))
FROM [sys].[all_objects]

SQL Query to get all clients birthdays for this month

I'm trying to create a query that will display all clients born this month, but I'm getting:
Conversion failed when converting date and/or time from character string."
Here is my code.
SELECT
t.Client_id, t.Name
FROM
(SELECT
Client_id,
C_name + ' ' + C_surname AS Name,
CONVERT(INT, SUBSTRING(Client_id, 3, 2)) AS M,
CONVERT(INT, SUBSTRING(Client_id, 5, 2)) AS D,
CONVERT(DATE, CONVERT(VARCHAR, CONVERT(CHAR(4), DATEPART(YEAR, GETDATE())) + '-' + SUBSTRING(Client_id, 3, 2) + '-' + SUBSTRING(Client_id, 5, 2))) AS DateOfBirth
FROM
tblClientInfo) T
WHERE
T.M <= 12
AND T.DateOfBirth = CONVERT(DATE, GETDATE());
I tried to put CONVERT(varchar, getdate()) but still getting error
This one works well for extracting birthdays for today only:
SELECT
t.Client_id, t.Name
FROM
(SELECT
Client_id,
C_name + ' ' + C_surname AS Name,
CONVERT(INT, SUBSTRING(Client_id, 3, 2)) AS M,
CONVERT(INT, SUBSTRING(Client_id, 5, 2)) AS D,
CONVERT(DATE, CONVERT(VARCHAR, CONVERT(CHAR(4), DATEPART(YEAR, GETDATE())) + '-' + SUBSTRING(Client_id, 3, 2) + '-' + SUBSTRING(Client_id, 5, 2))) AS DateOfBirth
FROM
tblClientInfo) T
WHERE
T.D <= 31
AND T.M <= 12
AND T.DateOfBirth = CONVERT(DATE, GETDATE());
Try this:
select *
from tblClientInfo
where CAST(SUBSTRING(Client_id, 3, 2) AS TINYINT) = month(getdate());
Hmmm . . . I'm thinking:
select c.*
from tblClientInfo c
where month(dateofbirth) = month(getdate());

Converting NVARCHAR to SMALLDATETIME on SQL SERVER 2008

I'm currently working on updating company database in which on one of the tables the CreateDt is in the nvarchar(20) type and stores dates in the following ways:
12 May 12
29/03/2011
9/24/2012
29/01/2001 08:51:56
There are 17,000 rows.
So I'm currently working on code in which I will be able to convert these dates all into the one format such as DD-MM-YYYY.
However I'm struggling to find anything suitable.
So far I have tried:
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CreateDt1,
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
END
END
END AS NewDate
FROM fct_Project;
However this returns null values for dates such as 29/01/2001 08:51:56.
Try add LEFT function in RIGHT to your query in case clause like:
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (LEFT(CreateDt1,10), 4) AS datetime)
END
END
END AS NewDate
I've just edited your code by adding a few lines, hope it will help.
Keep in mind, that it does not solve problem of 10/11 and 11/10 cases.
WITH CreateDt1
AS
(
SELECT '14 DECEMBER 12' AS CreateDt1
UNION ALL
SELECT '13/10/2005'
UNION ALL
SELECT '12/14/2012'
UNION ALL
SELECT '24/05/2002 09:28:58'
UNION ALL
SELECT '28/02/2011'
)
SELECT
CASE WHEN ISDATE(CreateDt1) = 1
THEN CAST(CreateDt1 AS datetime)
ELSE
CASE WHEN SUBSTRING(CreateDt1, 3, 1) = '/'
THEN
CASE WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + RIGHT (CreateDt1, 4)) = 1
THEN CAST(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1 , 2) + '/' + RIGHT (CreateDt1, 4) AS datetime)
WHEN ISDATE(SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) = 1
THEN CAST ( (SUBSTRING(CreateDt1, 4, 2) + '/' + LEFT(CreateDt1, 2) + '/' + LEFT((RIGHT (CreateDt1, 13)),4) ) AS DATETIME)
END
END
END AS NewDate
FROM CreateDt1;

Join two tables to generate a graph, but they don't have common columns

I'm trying to build a SQL consult that populates a data table that will give the info that will draw a js graph (on canvasjs library).
The graph will compare the sales table vs. the expenses table, so they don't have a column on wich I can make a JOIN, only the dates, that will be shown as yyyy-mm.
In order to group all the sales, I need to Join two tables, the one that stores the main invoices info ([dbo].[Facturas]), and the one that stores the items on each invoice ([dbo].[FacturasItems])
This is the consult that retrieves the info for all the sales, and groups them in months:
DECLARE #facTotal numeric(18,2)
SET #facTotal =
(
SELECT
SUM(([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) + (([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) * [dbo].[Facturas].[ValorIVA]))
FROM [dbo].[FacturasItems]
INNER JOIN
[dbo].[Facturas]
ON [dbo].[Facturas].[ID] = [dbo].[FacturasItems].[IdFactura]
)
SELECT
CAST(YEAR([dbo].[Facturas].[FechaCr]) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH([dbo].[Facturas].[FechaCr]) AS VARCHAR(2)), 2) AS [Periodo],
CONVERT(numeric(18,0), SUM(([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) + (([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) * [dbo].[Facturas].[ValorIVA]))) AS [VentasRaw],
'$' + CONVERT(varchar, CONVERT(money, SUM(([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) + (([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) * [dbo].[Facturas].[ValorIVA]))), 1) AS [VentasForm],
CONVERT(varchar(6), CONVERT(numeric(18,2), SUM(([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) + (([dbo].[FacturasItems].[ValorU] * [dbo].[FacturasItems].[Cantidad]) * [dbo].[Facturas].[ValorIVA])) / (#facTotal) * 100)) + '%' AS [Prc100]
FROM [dbo].[Facturas]
INNER JOIN
[dbo].[FacturasItems]
ON [dbo].[FacturasItems].[IdFactura] = [dbo].[Facturas].[ID]
GROUP BY
CAST(YEAR([dbo].[Facturas].[FechaCr]) AS VARCHAR(4)) + '-' + right('00' + CAST(MONTH([dbo].[Facturas].[FechaCr]) AS VARCHAR(2)), 2)
This consult is working just fine, and it returns this table data:
The second consult, expenses, goes like this:
DECLARE #gasTotal numeric(18,2)
SET #gasTotal =
(
SELECT
SUM(([dbo].[Gastos].[Valor]) + (([dbo].[Gastos].[Valor]) * [dbo].[Gastos].[IVAVal]))
FROM [dbo].[Gastos]
)
SELECT
CAST(YEAR([dbo].[Gastos].[Fecha]) AS varchar(4)) + '-' + RIGHT('00' + CAST(MONTH([dbo].[Gastos].[Fecha]) AS varchar(2)), 2) AS [Periodo],
CONVERT(numeric(18,0), SUM([dbo].[Gastos].[Valor] + ([dbo].[Gastos].[Valor] * [dbo].[Gastos].[IVAVal]))) AS [ValorGraph],
'$' + CONVERT(varchar, CONVERT(money, SUM([dbo].[Gastos].[Valor] + ([dbo].[Gastos].[Valor] * [dbo].[Gastos].[IVAVal]))), 1) AS [ValorForm],
CONVERT(varchar, CONVERT(money, SUM(([dbo].[Gastos].[Valor] + ([dbo].[Gastos].[Valor] * [dbo].[Gastos].[IVAVal])) / #gasTotal) * 100), 1) + '%' AS [Prc100]
FROM [dbo].[Gastos]
GROUP BY
CAST(YEAR([dbo].[Gastos].[Fecha]) AS varchar(4)) + '-' + RIGHT('00' + CAST(MONTH([dbo].[Gastos].[Fecha]) AS varchar(2)), 2)
This will create this table:
So, as you can see, there where no sales on 2017-10, zero invoices, so the table 1 won't start on 2017-10 but on 2017-11, while the expenses table starts on 2017-10.
I need that the table 1 (invoices and sales), starts in 2017-10 with it's values in 0, so that the graph will show correcty.
In other words, I need this kind of tables:
I tryed an inner join, a left join and an outer join, but the will add all the records, add the sales + expenses.
Thanks!
Just add
SELECT 2017-10 as Periodo,0 as VentasRow, 0 as VentasForm, 0 as Prc100
UNION
Your first query here....
Hope this helps.
WITH Ventas as (
SELECT
CAST(YEAR(f.FechaCr) AS VARCHAR(4)) + '-'
+ right('00' + CAST(MONTH(f.FechaCr) AS VARCHAR(2)), 2) AS Periodo,
SUM(fi.ValorU * fi.Cantidad * (1 + f.ValorIVA)) AS VentasRaw,
SUM(fi.ValorU * fi.Cantidad * (1 + f.ValorIVA)) OVER () AS VentasTot
FROM dbo.Facturas as f INNER JOIN dbo.FacturasItems as fi
ON fi.IdFactura = f.ID
GROUP BY datepart(year, f.FechaCr), datepart(month, f.FechaCr)
),
Gastos as (
SELECT
CAST(YEAR(g.Fecha) AS varchar(4)) + '-'
+ RIGHT('00' + CAST(MONTH(g.Fecha) AS varchar(2)), 2) AS Periodo,
SUM(g.Valor * (1 * g.IVAVal) AS ValorGraph,
SUM(g.Valor * (1 * g.IVAVal) OVER () AS GastosTot
FROM dbo.Gastos as g
GROUP BY datepart(year, g.Fecha), datepart(month, g.Fecha)
)
SELECT g.Periodo,
COALESCE(v.VentasRaw, 0), COALESCE(v.VentasTot, 0),
g.ValorGraph, g.GastosTot
FROM Ventas as v RIGHT OUTER JOIN Gastos g ON g.Periodo = v.Periodo;
You could certainly use a full outer join if it's possible to have sales but no expenses.

Combining two rows in one select query

Hi I am having a hard time combining two records (from a single table) on a single query. The idea is, DATE_FIELD column is a date type and ColA is an integer data type.
To further illustrate my inquiry, I have attached an image below
1.) Is the raw table.
2.) Is the desired output.
P.S. The filter for DATE_FIELD is not a simple "WHERE DATE_FIELD IN" clause.
For example, I wanted to get the DATE_FIELD=12/30/2013. Then I need to get the Previous Sept DATE_FIELD also, which is 9/30/2013 programatically by using this query that I got from the web:
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END
Here is my current sql script (which cannot get the ColA equivalent for Previous Sept filter:
SELECT DATE_FIELD, ColA,
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END AS PREVIOUS,
(
SELECT ColA
FROM TABLE_A
WHERE DATE_FIELD =
CASE
WHEN MONTH(DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END
) AS PYE_colA
FROM TABLE_A
WHERE DATE_FIELD = '12/30/2013'
Thanks!
Do a cross join with the same table and use your CASE structure only in the where clause:
SELECT a.DATE_FIELD AS DATE_FIELD_1,
a.ColA AS ColA_1,
b.DATE_FIELD AS DATE_FIELD_2,
b.ColA AS ColA_2
FROM TABLE_A a
CROSS JOIN TABLE_A b
WHERE DATE_FIELD_1 = 'your date'
AND DATE_FIELD_2 = (
CASE
WHEN MONTH(DATE_FIELD_1) < 10
THEN
(cast(CAST((YEAR(DATE_FIELD_1) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(DATE_FIELD_1)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END)
;
Another possibility based on Thorsten Kettners remarks:
SELECT a.DATE_FIELD AS DATE_FIELD_1,
a.ColA AS ColA_1,
b.DATE_FIELD AS DATE_FIELD_2,
b.ColA AS ColA_2
FROM TABLE_A a
INNER JOIN TABLE_A b
ON b.DATE_FIELD = (
CASE
WHEN MONTH(a.DATE_FIELD) < 10
THEN
(cast(CAST((YEAR(a.DATE_FIELD) - 1) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
ELSE
( cast(CAST((YEAR(a.DATE_FIELD)) as char(4)) + RIGHT('00' + LTRIM(09),2) + RIGHT('00' + LTRIM(30),2) AS Date))
END)
WHERE a.DATE_FIELD = 'your date'
;