i have this 2 query
select CONVERT(date, en_cours.date),COUNT(*) encours from en_cours group by CONVERT(date, en_cours.date) order by CONVERT(date, en_cours.date) asc
select CONVERT(date, clos.date),COUNT(*) clos from clos group by CONVERT(date, clos.date) order by CONVERT(date, clos.date) asc
the first one return :
B|1
C|1
F|20
and the seconde one :
A|4
B|8
C|7
D|1
E|9
F|10
i'm trying to fusion this 2 query and make it like :
A|4|NULL
B|8|1
C|7|1
D|1|NULL
E|9|NULL
F|10|20
but when i'm doing this it's given different values
select CONVERT(date, clos.date),COUNT(clos.ticket_cp),COUNT(en_cours.ticket_cp)from clos left join en_cours on CONVERT(date, clos.date) = CONVERT(date, en_cours.date) group by CONVERT(date, clos.date) order by CONVERT(date, clos.date) asc
Wrap each of your queries inside a CTE and join them:
with
cte1 as (
select CONVERT(date, en_cours.date) date1, COUNT(*) encours
from en_cours
group by CONVERT(date, en_cours.date)
)
cte2 as (
select CONVERT(date, clos.date) date2, COUNT(*) clos
from clos
group by CONVERT(date, clos.date)
)
select c1.date1, c1.encours, c2.clos
from cte1 c1 left join cte2 c2
on c2.date2 = c1.date1
order by c1.date1 asc
Change the LEFT JOIN to a FULL OUTER JOIN if there is a case that the 2nd query may contain dates that do not exist in the 1st query.
the scenario for using the direct database call is a little fragile, because if you have any database change you will have to wait for the publication time in stores to change queries.
But for your scenario try to include System.Data for integration with sql commands.
Related
I'm working on sales data and I want to know if Customer A purchased product X from more than one provider within 3 days and I'm working on only one date Claim Date
I Can't find T-Sql query for it
for example
SELECT CusName,ProdName,ProvName
FROM table1
WHERE [Claim Date] between Day([Claim Date]) and DATEADD (Day ,-3 , [Claim Date]
A WHERE EXISTS clause should do the job:
SELECT CusName,ProdName,ProvName
FROM table1 a
WHERE EXISTS (
SELECT 1 FROM table1 b WHERE
b.CusName=a.CusName AND
b.ProdName=a.ProdName AND
b.ProvName!=a.ProvName AND
ABS(DATEDIFF(day,a.ClaimDate,b.ClaimDate))<3
)
You can use the below code for that
SELECT t1.CusName,t1.ProdName,t1.ProvName,t2.ProvName
FROM table t1
JOIN table t2 ON t1.CusName=t2.CusName AND t1.ProdName=t2.ProdName
WHERE t1.ProvName!=t2.ProvName
AND ABS(DATEDIFF(day,t1.ClaimDate,t2.ClaimDate)) = 3
You need a having clause and a count of the providers:
SELECT CusName, COUNT(DISTINCT ProvName) Provider_count
FROM table1
WHERE [Claim Date] between Day([Claim Date]) and DATEADD (Day ,-3 , [Claim Date]
AND ProdName = 'X'
GROUP BY CusName
HAVING COUNT(DISTINCT ProvName) > 1
Note, you do not need to include the count in the select clause, but you do need it in the having clause.
I am new to SQL, I am trying to query from a ledger table
I have two Queries that I need to join into one table
1st Query:
SELECT *
FROM TABLE 1
WHERE DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 3
AND [ITEMTYPE] = 'F-C'
AND ([Description] NOT LIKE '%REFILE%'
AND [Description] NOT LIKE '%CROSSOVER%')
AND ([UserNAME] LIKE '%USER1%'
OR [UserNAME] LIKE '%user2%'
OR [UserNAME] LIKE '%user3%')
2nd Query:
SELECT [ENCID], SUM([Trans]) AS Total_Charges
FROM Table 1
WHERE DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 3
AND [ITEMTYPE] IN ('C')
GROUP BY [ENCID];
I need to Left join the 2nd Query to the 1st Query on ENCID
THanks.
Well, you just join it. Nothing special about it, except that you have to remember to give an alias e.g. Totals
I have also changed your DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 3 to [Transaction Date] >= DATEADD(MONTH, -3, GETDATE()), to allow SQL Server to use indexes on [Transaction Date] column, if you have any.
Also leading wild card text searches e.g. [UserNAME] LIKE '%user2%' are slow, avoid them if you can: https://sqlperformance.com/2017/02/sql-indexes/seek-leading-wildcard-sql-server
SELECT *
FROM TABLE 1 AS a
LEFT JOIN
( SELECT [ENCID], SUM([Trans]) AS Total_Charges
FROM Table 1
WHERE [Transaction Date] >= DATEADD(MONTH, -3, GETDATE())
AND [ITEMTYPE] IN ('C')
GROUP BY [ENCID] ) AS Totals ON Totals.[ENCID] = a.[ENCID]
WHERE
[Transaction Date] >= DATEADD(MONTH, -3, GETDATE())
AND [ITEMTYPE] = 'F-C'
AND ([Description] NOT LIKE '%REFILE%'
AND [Description] NOT LIKE '%CROSSOVER%')
AND ([UserNAME] LIKE '%USER1%'
OR [UserNAME] LIKE '%user2%'
OR [UserNAME] LIKE '%user3%')
When you introduce any joins (to tables or subqueries) it is vital that you refer to columns from those sources by aliases.
SELECT t1.*
FROM TABLE_1 t1
LEFT JOIN (
SELECT [ENCID], SUM([Trans]) AS Total_Charges
FROM Table_1
WHERE [Transaction Date] >= DATEADD(month,-3,GETDATE())
AND [ITEMTYPE] IN ('C')
GROUP BY [ENCID]
) sq ON t1.[ENCID] = sq.[ENCID]
WHERE t1.[Transaction Date] >= DATEADD(month,-3,GETDATE())
AND t1.[ITEMTYPE] = 'F-C'
AND (t1.[Description] NOT LIKE '%REFILE%'
AND t1.[Description] NOT LIKE '%CROSSOVER%')
AND (t1.[UserNAME] LIKE '%USER1%'
OR t1.[UserNAME] LIKE '%user2%'
OR t1.[UserNAME] LIKE '%user3%')
NOTE: I have altered the way the dates are considered so that an index on [Transaction Date] could be utilized. Instead of calculating a number of months on every row, it is far more efficient to calculate a date then compare existing data to that value. For best performance try to avoid using functions on data in the where clause.
i trying to assign the month wise leaves in year in my database(sql server) but its fail below my trying code is there
select count(*)(SELECT DATEPART(yyyy,Date) AS OrderYear,
DATEPART(mm,Date) AS OrderMonth,
DATEPART(dd,Date) AS OrderDay
FROM Leaves
WHERE EmployeeID=37) FROM Leaves where OrderYear = '2016'
This below code will do what you need to do. Just had to make some small changes to your above code:
you will need an inner query which will extract the date parts, which will then need to be selected.
An outer query will need to then select from the inner query and filter on the new date part field.
Here is how I would do it:
select
count(*)
FROM
(
SELECT
DATEPART(yyyy, Date) AS OrderYear,
DATEPART(mm, Date) AS OrderMonth,
DATEPART(dd, Date) AS OrderDay
FROM
Leaves
WHERE
EmployeeID = 37
) A
WHERE
OrderYear = '2016';
You may looking for this :
;WITH CTE AS(
SELECT 1 as MonthNumber
UNION ALL
SELECT MonthNumber+1 AS MonthNumber
FROM CTE
WHERE MonthNumber<=12
)
SELECT MonthNumber,COUNT(*)
FROM CTE
LEFT JOIN Leaves ON MONTH(DATE) = MonthNumber AND EmployeeID=37 AND YEAR(Date)=2016
GROUP BY MonthNumber
I have to get the list of months and year in between my dates. Currently it only returns month and year for dates that has data associated with it.
for example my dates is between: '8'+'/1'+'/'+'2015' and DATEADD(mm, 15, '8'+'/1'+'/'+'2016'
It only prints out: May2016, June2016, July2016, Auguest2016, September2016
I want it to print out all of the months and year in between. Here is my sql queries:
select d.id_base as case_id,
c.C_LAST_ACTION AS Docketed,
c.C_CASE_TYPE AS caseType,
ct.C_NAME As caseName,
ct.C_DESCRIPTION AS caseNameDescription,
case when d.c_mod_decision_id is not null then '' else DATENAME(mm, d.c_issue_date) + DATENAME(yyyy, d.c_issue_date) end as display
from t_case_decision d JOIN T_CASE_INPUT c on c.id = d.id_base JOIN T_CASE_TYPE ct on C_CASE_TYPE = ct.id
where cast(d.c_issue_date AS date) BETWEEN '8'+'/1'+'/'+'2015' and DATEADD(mm, 15, '8'+'/1'+'/'+'2016')
First, create a numbers table
CREATE TABLE Numbers(N INT)
insert into Numbers(N)
select top 1000000 row_number() over(order by t1.number) as N
from master..spt_values t1
cross join master..spt_values t2
then use DATEADD to list dates between desired values, like this
declare #iniDate as date
set #iniDate='20150801'
select dateadd(MONTH,N,#iniDate) dates
from Numbers
where N<15 order by N
These returns dates from #iniDate up to 15 months later
EDIT: try this, I don't have sql right now
select datename(mm, dateadd(MONTH,N,#iniDate))+datename(yyyy ,dateadd(MONTH,N,#iniDate)) display
from ( select top 15row_number() over(order by t1.number) as N
from master..spt_values t1
cross join master..spt_values t2) numbers right join (
select d.id_base as case_id,
c.C_LAST_ACTION AS Docketed,
c.C_CASE_TYPE AS caseType,
ct.C_NAME As caseName,
ct.C_DESCRIPTION AS caseNameDescription,
case when d.c_mod_decision_id is not null then '' else DATENAME(mm, d.c_issue_date) + DATENAME(yyyy, d.c_issue_date) end as display
from t_case_decision d JOIN T_CASE_INPUT c on c.id = d.id_base JOIN T_CASE_TYPE ct on C_CASE_TYPE = ct.id
where cast(d.c_issue_date AS date) BETWEEN '8'+'/1'+'/'+'2015' and DATEADD(mm, 15, '8'+'/1'+'/'+'2016')
sql-server
) qq
on datename(mm, dateadd(MONTH,N,#iniDate))+datename(yyyy ,dateadd(MONTH,N,#iniDate)) = qq.display
where N<15 order by N
If I understand what you're trying to accomplish, a recursive CTE might help. Here's a quick example of what you can do. The CTE will expand out into a list of dates, which you can then use as the base for your query.
The contents of the TargetData CTE may need to be adjusted, as I don't have a complete picture of your data structure.
DECLARE #startDate DATE = '1/1/2015';
DECLARE #endDate DATE = '7/31/2016';
-- Recursive CTE to generate a list of months within the date range:
WITH Months AS (
SELECT CONVERT(DATE, DATEADD(D, -(DAY(#startDate)) + 1, #startDate)) [MonthDate]
UNION ALL
SELECT DATEADD(M, 1, MonthDate)
FROM Months
WHERE MonthDate <= DATEADD(M, -1, #endDate)
),
TargetData AS (
-- This is a slightly modified version of the original query:
select
d.id_base as case_id,
c.C_LAST_ACTION AS Docketed,
c.C_CASE_TYPE AS caseType,
ct.C_NAME As caseName,
ct.C_DESCRIPTION AS caseNameDescription,
case when d.c_mod_decision_id is not null then '' else DATENAME(mm, d.c_issue_date) + DATENAME(yyyy, d.c_issue_date) end as display,
-- Return the "MonthDate" so that it can be left joined to the Months table:
DATEADD(D, -(DAY(d.c_issue_date)) + 1, d.c_issue_date) [MonthDate]
from t_case_decision d JOIN T_CASE_INPUT c on c.id = d.id_base JOIN T_CASE_TYPE ct on C_CASE_TYPE = ct.id
where cast(d.c_issue_date AS date) BETWEEN #startDate AND #endDate
)
SELECT
m.MonthDate,
DATENAME(mm, m.MonthDate) + DATENAME(yyyy, m.MonthDate),
td.*
FROM Months m
LEFT JOIN TargetData td ON td.MonthDate = m.MonthDate;
You need to join on primary keys between tables, I haven't seen a between statement with that syntax. So I suggest trying the following:
SELECT d.id_base as case_id, c.C_LAST_ACTION AS 'Docketed',c.C_CASE_TYPE AScaseType,ct.C_NAME As 'caseName', ct.C_DESCRIPTION AS 'caseNameDescription'
,CASE
WHEN d.c_mod_decision_id is not null THEN '' AS 'null_val'
ELSE CONCAT(YEAR(d.c_issue_dateDATENAME), MONTH(d.c_issue_date))
END AS 'display'
FROM t_case_decision d INNER JOIN T_CASE_INPUT c on c.id = d.id_base
INNER JOIN T_CASE_TYPE ct on c.id = ct.id
WHERE CONVERT(DATE,d.c_issue_date) BETWEEN '08/01/2015'
AND '08/01/2016';
I hope this helps or points you in the right direction :)
I have two different select statement but I want to show combined result in one query. I have following restriction.
I can't use Join because it requires at-least one common column in both statements but in my case there is no common column.
I can't user Union because it requires same structure of both statement and same no. of columns in both table. In my case both select statement has different structure.
Here are my two select statements.
select Center, SUM(PaidAmount) as TotalCollection, COUNT(Id) as TotalBills from DiagMain where
Cast(EntryDate as Date) = CONVERT(date, getdate()) group by Center order by Center desc
select Id, PtName, PaidAmount, DueAmount, Center, MachineName from DiagMain where Cast(EntryDate as Date) =
CONVERT(date, getdate()) order by Id desc
Please help guys...
Looking at your query, it seems that you want the rows from DiagMains along with TotalCollection and TotalBills per Center in the result set. If that's the case, you can use window functions SUM() OVER and COUNT OVER():
SELECT
Id,
PtName,
PaidAmount,
DueAmount,
Center,
MachineName,
TotalCollection = SUM(PaidAmount) OVER(PARTITION BY Center),
TotalBIlls = COUNT(Id) OVER(PARTITION BY Center)
FROM DiagMain
WHERE
CAST(EntryDate AS DATE) = CAST(GETDATE() AS DATE)
If there are no common Columns to join results, you can use Row_Number() to combine the results.
SELECT Table1.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY Center DESC) AS ROW,
Center, SUM(PaidAmount) AS Collection, COUNT(Id) AS TotalBills FROM DiagMain WHERE
CAST(EntryDate AS date) = CONVERT(date, GETDATE()) GROUP BY Center) Table1
INNER JOIN
(SELECT ROW_NUMBER() OVER (ORDER BY Id DESC) AS ROW, Id, PtName, PaidAmount,
DueAmount, Center, MachineName FROM DiagMain WHERE CAST(EntryDate AS date) =
CONVERT(date, GETDATE())) Table2
ON Table1.ROW = Table2.ROW