How to select distinct latest datetime? - sql

Here is a sample of my Table A and its code. Do note that the equip_OID is different.
Table A:
Workstation
ID
WS_OID
equip_OID
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863AA56474
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
select distinct
trim(ws.WS_name) as [Workstation],
substring(trim(e.equip_id),1,8) as [ID],
eqmhist.WS_OID,
eqmhist.equip_OID
into
#Table_A
from
eqmhist
inner join
e on eqmhist.equip_OID = e.equip_OID
inner join
ws on ws.WS_OID = eqmhist.WS_OID
inner join
a on a.mfg_area_OID = e.mfg_area_OID
I joined Table A with Table B as it has the [tracked_out_datetime] that I need, I inner joined using [ID] and [Tool ID] to get my Table C:
Table C:
Workstation
Tool ID
WS_OID
equip_OID
tracked_out_datetime
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863AA56474
2023-01-04 21:28:42.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863AA56474
2023-01-05 03:06:26.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863AA56474
2023-01-05 10:22:18.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
2023-02-14 17:20:42.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
2023-02-14 19:11:43.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
2023-01-30 16:15:04.000
select distinct
ta.[WS Name],
substring(trim(tracking_interface_id), 1, 8) as [Tool],
ta.equip_OID,
ta.WS_OID,
tracked_out_datetime
into
#Table_C
from
Table_B tb
inner join
#Table_A ta on substring((tb.tracking_interface_id),1,8) = ta.[Equid ID]
where
exists (select taa.[Equid ID] from #Table_A taa
where taa.[Equid ID] = substring((tb.tracking_interface_id), 1, 8))
What I'm trying to do is to select the latest [tracked_out_datetime] for each distinct [equip_OID]. But the problem that I'm facing now is that the code I tried only showed me the latest [track_out_datetime] but without the distinct [equip_OID], I can't seem to fix it. Hope I can get some advice from you experts! The code, problem faced and my desired result will be below.
Code:
select
x.[WS Name],
x.[Tool],
x.WS_OID,
x.equip_OID,
tracked_out_datetime
into
#main2
from
(select
ta.[WS Name],
substring(trim(tracking_interface_id),1,8) as [Tool],
ta.equip_OID,
ta.WS_OID,
tb.tracked_out_datetime,
row_number() over(partition by tracking_interface_id order by tracked_out_datetime desc) as rn
from
Table_B tb
inner join
#Table_A ta on substring((tb.tracking_interface_id), 1, 8) = ta.[Equid ID]
where
exists (select taa.[Equid ID] from #Table_A taa
where taa.[Equid ID] = substring((tb.tracking_interface_id), 1, 8))) x
where
x.rn = 1
select distinct *
from #main2
Problem:
Workstation
ID
WS_OID
equip_OID
tracked_out_datetime
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
2023-02-14 19:11:43.000
(only showing the latest)
Desired result:
Workstation
ID
WS_OID
equip_OID
tracked_out_datetime
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863AA56474
2023-01-05 10:22:18.000
WS 3-ABC21
ABC21
0x8008C14353564545
0x9454863BB56474
2023-02-14 19:11:43.000

Could you try to add here:
row_number() over(partition by tracking_interface_id order by tracked_out_datetime desc) as rn
the equip_OID like this:
... partition by tracking_interface_id, equip_OID oder by ...

distinct doesn't works because u have different values on [tracked_out_datetime]. if you remove this column from your query distinct works fine. but it won't help you. because you want this column of course.
I wanted to use Group by and Having pair. but there is an easier solution.
select distinct
ta.[WS Name],
substring(trim(tracking_interface_id), 1, 8) as [Tool],
ta.equip_OID,
ta.WS_OID,
(SELECT Max(tracked_out_datetime) FROM #Table_A
WHERE exist (select taa.[Equid ID] from #Table_A taa where taa.[Equid ID] = substring((tb.tracking_interface_id), 1, 8))
AND #Table_A.equip_OID = ta.[Equid ID]) AS max_tracked_out_datetime
into
#Table_C
from
Table_B tb
inner join
#Table_A ta on substring((tb.tracking_interface_id),1,8) = ta.[Equid ID]
where
exists (select taa.[Equid ID] from #Table_A taa
where taa.[Equid ID] = substring((tb.tracking_interface_id), 1, 8))
here is the trick:
(SELECT Max(tracked_out_datetime) FROM #Table_A
WHERE exist (select taa.[Equid ID] from #Table_A taa where taa.[Equid ID] = substring((tb.tracking_interface_id), 1, 8))
AND #Table_A.equip_OID = ta.[Equid ID]) AS max_tracked_out_datetime
I just said: Find maximum value for tracking_out_datetime for each equip_OID. It will results in duplicated lanes which distinct is able to reduce them now.

Related

Avoid inserting duplicates when working with composite primary key

I'm writing a query in SQL that transfers data from an Acces DB to a new SQL server management DB.
This transfer is a one time only, so I do not have to worry about the code being super generic.
I'm trying to insert data from a couple of tables (including tables from the Acces DB), but get an error about duplicates on the composite primary key.
My problem is that I can't see why my uses of distinct does not prevent those duplicates.
The table I want to insert into is constructed as so:
The code I'm trying to execute is written as followed:
-- Insert into ComponentSupplier for [Supplier 1]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 1 order no], a.[PDF Data 1 sheet link], a.[Supplier 1 LF], '1'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 1]
-- Insert into ComponentSupplier for [Supplier 2]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 2 order no], a.[PDF Data 2 sheet link], a.[Supplier 2 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 2]
-- Insert into ComponentSupplier for [Supplier 3]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 3 order no], a.[PDF Data 3 sheet link], a.[Supplier 3 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 3]
-- Insert into ComponentSupplier for [Supplier 4]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 4 order no], a.[PDF Data 4 sheet link], a.[Supplier 4 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 4]
-- Insert into ComponentSupplier for [Supplier 5]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 5 order no], a.[PDF Data 5 sheet link], a.[Supplier 5 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 5]
-- Insert into ComponentSupplier for [Supplier 6]
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 6 order no], a.[PDF Data 6 sheet link], a.[Supplier 6 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 6]
The distinct de-duplicates based on all the columns in the select.
The issue could be because you are inserting record using multiple insert..selects, you could try something like this to ensure records are de-duplicated correctly.
The distinct will de-dup withing each select, and the union will de-dup across the select statements:
insert into CDB2020.dbo.ComponentSupplier
(
Supplier_ID,
BK_ID,
Part_ID,
Datasheet,
LF,
Preferred
)
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 1 order no], a.[PDF Data 1 sheet link], a.[Supplier 1 LF], '1'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 1]
union
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 2 order no], a.[PDF Data 2 sheet link], a.[Supplier 2 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 2]
union
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 3 order no], a.[PDF Data 3 sheet link], a.[Supplier 3 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 3]
union
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 4 order no], a.[PDF Data 4 sheet link], a.[Supplier 4 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 4]
union
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 5 order no], a.[PDF Data 5 sheet link], a.[Supplier 5 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 5]
union
select distinct s.Supplier_ID, c.BK_ID, a.[Supplier 6 order no], a.[PDF Data 6 sheet link], a.[Supplier 6 LF], '0'
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 6]
You can use a query like this to find out duplicate records (group by all fields in your composite key):
select s.Supplier_ID, c.BK_ID, count(*)
from AccessDataMigration_1.dbo.[B-K Data] as a
inner join CDB2020.dbo.Components as c on c.BK_ID = a.[B-K no]
inner join CDB2020.dbo.Suppliers as s on s.Name = a.[Supplier 6]
group by s.Supplier_ID, c.BK_ID
having count(*) > 1

SQLServer Jobhistory - last successful runtime & last unsuccessful runtime

I want to have a view about my sql jobs which contains
name
job_id
run_date
LastSuccessfulRunDate
This is what I found for the last successful run dates.
Works like a charm, but here I am, failing to add the last run date.
Use msdb
GO
SELECT
SJ.NAME AS [Job Name]
,RUN_STATUS AS [Run Status]
,MAX(DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME)) AS [Last Time Job Ran On]
FROM
dbo.SYSJOBS SJ
LEFT OUTER JOIN dbo.SYSJOBHISTORY JH
ON SJ.job_id = JH.job_id
WHERE JH.step_id = 0
AND jh.run_status = 1
GROUP BY SJ.name, JH.run_status
ORDER BY [Last Time Job Ran On] DESC
GO
Here's what I got so far but it's giving me the result in two lines, one with last run date and the other with last successful run (which is als incorrect because it selects the highest date there is - distinct value). I kindly ask for help to get the join right and the result in one line.
USE msdb
GO
SELECT DISTINCT SJ.Name AS JobName,
SJH.run_date AS LastRunDate,
SJH.job_id,
(SELECT MAX(DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME))
FROM sysjobs
RIGHT JOIN sysjobhistory
ON SJ.job_id = SJH.job_id
WHERE SJH.run_status = 1) AS LastSuccessfulRun,
CASE SJH.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Successful'
WHEN 3 THEN 'Cancelled'
WHEN 4 THEN 'In Progress'
END AS LastRunStatus
FROM sysjobhistory SJH, sysjobs SJ
WHERE SJH.job_id = SJ.job_id and SJH.run_date =
(SELECT MAX(SJH.run_date) FROM sysjobhistory SJH WHERE SJ.job_id = SJH.job_id)
I think you want row_number():
SELECT x.*
FROM (SELECT SJ.NAME AS [Job Name], RUN_STATUS AS [Run Status],
DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) AS LastRunDateTime,
ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) DESC) as seqnum
FROM dbo.SYSJOBS SJ LEFT OUTER JOIN
dbo.SYSJOBHISTORY JH
ON SJ.job_id = JH.job_id
WHERE JH.step_id = 0 AND jh.run_status = 1
GROUP BY SJ.name, JH.run_status
) x
WHERE seqnum = 1
ORDER BY LastRunDateTime DESC;
Also, learn to use proper, explicit JOIN syntax. Commas in the FROM clause are archaic.
solution is:
SELECT sj.name,
MAX(dbo.agent_datetime(sjh.run_date, sjh.run_time)) AS last_Succesful_run,
x.last_Unsuccesful_run
FROM sysjobhistory sjh
INNER JOIN sysjobs sj ON sjh.job_id = sj.job_id
LEFT OUTER JOIN
(SELECT sysjobs.name,
MAX(dbo.agent_datetime(sysjobhistory.run_date, sysjobhistory.run_time)) AS last_Unsuccesful_run
FROM sysjobhistory
INNER JOIN sysjobs ON sysjobhistory.job_id = sysjobs.job_id
WHERE sysjobhistory.run_status = 0
GROUP BY sysjobs.name) x
ON x.name = sj.name
WHERE run_status = 1
GROUP BY sj.job_id, sj.name, last_Unsuccesful_run
dropped the status case bc it's clear enough this way. the case was not mandatory.

Filtering based on COUNT

I have a query that works really well. But I am trying to add a filter so if users_in_this_country is > 1. I know to add users_in_this_country > 1 to the WHERE. But if I add it inside the parenthesis it says invalid column and the same if I add it outside of the parenthesis. This is probably really dumb and easy, but what am I over looking? Thanks!
SELECT u.ContactName
,cu.[User ID]
,c.Name
,c.ID
,cu.[Foreign Table]
,count(*) OVER (PARTITION BY c.ID) AS user_in_this_country
FROM dbo.Country AS c
INNER JOIN dbo.CountryUser AS cu ON c.ID = cu.[Foreign ID]
INNER JOIN dbo.UserColder AS u ON cu.[User ID] = u.ID
WHERE EXISTS (
SELECT *
FROM CountryUser AS cu2
WHERE cu2.[Foreign ID] = cu.[Foreign ID]
AND cu2.[User ID] <> cu.[User ID]
AND cu.[Foreign Table] = 'Country')
The reason you can't refer to it in the WHERE clause is that its very meaning, for a given row, depends on what other rows satisfy the WHERE clause; so it would all be too circular.
The simplest fix is to wrap your entire query in SELECT * FROM ( ... ) t WHERE t.user_in_this_country > 1.
That said, it seems like your query already ensures that user_in_this_country > 1, by virtue of the EXISTS clause, which makes sure that there exists a different CountryUser record that belongs to the same Country and a different User. What am I missing?
With aggregate functions (like COUNT) used in conjuction with OVER clause you have to use a CTE or a subquery, like this
WITH CTE AS (
SELECT u.ContactName
,cu.[User ID]
,c.Name
,c.ID
,cu.[Foreign Table]
,count(*) OVER (PARTITION BY c.ID) AS user_in_this_country
FROM dbo.Country AS c
INNER JOIN dbo.CountryUser AS cu ON c.ID = cu.[Foreign ID]
INNER JOIN dbo.UserColder AS u ON cu.[User ID] = u.ID
WHERE EXISTS (
SELECT *
FROM CountryUser AS cu2
WHERE cu2.[Foreign ID] = cu.[Foreign ID]
AND cu2.[User ID] <> cu.[User ID]
AND cu.[Foreign Table] = 'Country')
)
SELECT *
FROM CTE
WHERE user_in_this_country > 1
Because "users_in_this_country" is not a column, it is an alias which is not valid in the scope of the WHERE clause. I 'm not familiar with "OVER" or PARTITION BY but, my guess is you'd have to do something like this:
WHERE blabla AND (count(*) OVER (PARTITION BY c.ID)) > 1

Need help in logic for data update using stored procedure

I have 3 tables:
Accounts (fields used: ID varchar(20) and Name varchar(50))
OpttyPartner( fields used : ID15 varchar(20) , ACCOUNTTOID varchar(20)
Final2([Opportunity ID] varchar(20), Partner varchar(400)
I need to update Partner field of every record for final2 with name from accounts table.
Final2 is related to OpptyPartner with {opportunity ID] and ID15
Accounts is related with OpptyPartner with ID and ACCOUNTTOID
If there are more than one accounttoid for same Opportunity ID then the names should be appended and seperated with a ';'
For example:
Final2
ID Partner
1
OpptyPartner
ID15 ACCOUNTTOID
1 A1
1 A2
Accounts
ID Name
A1 ABC com
A2 EFG com
The output in Partner should be 'ABC com;EFG com'
How can this be achieved? Cursors ?
UPDATE:
;With partners as
(select * from Accounts inner join OpptyPartner on
Accounts.ID COLLATE Latin1_General_CS_AS=OpptyPartner.[ACCOUNTTOID] COLLATE Latin1_General_CS_AS
inner join Final2 on Final2.[Opportunity ID] = OpptyPartner.ID15)
Update Final2 set Partner = p.Names from
Final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.NAME as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY NAME
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on Final2.[Opportunity ID] = p.[Opportunity ID]
I think this might be of use:
;With partners as
(select [Opportunity ID], Name from accounts inner join OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]
Try using this (add collation where necessary) if you have multiple records in opptyPartner with same ID15 and ACCOUNTTOID :
;With partners as
(select [Opportunity ID], Name from accounts inner join (select distinct [ID15]
,[ACCOUNTTOID] from OpttyPartner) OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]

How to retrieve rows multiple times in SQL Server?

These are my rows that I initially retrieved:
112 Cem Ceminay
210 Ali Salih
132 Gül Sen
Now I want to clone every row to be duplicated as 3 rows. So the new results:
112 Cem Ceminay
112 Cem Ceminay
112 Cem Ceminay
210 Ali Salih
210 Ali Salih
210 Ali Salih
132 Gül Sen
132 Gül Sen
132 Gül Sen
What kind of select statement can help me?
Example select statement:
SELECT id,name,surname FROM people;
Thank you lovely people...
PS: My query:
SELECT
Faturalar.faturaNo
,Klinikler.SAPSirketKodu [COMPANY CODE]
,Klinikler.SAPBussinessArea [BUSINESS AREA]
,BasilmisFaturalar.basilmisFatura_id [REFERENCE]
,BasilmisFaturalar.duzenlemeTarihi [DOCUMENT DATE]
,BasilmisFaturalar.duzenlemeTarihi [BASELINE DATE]
,Kurumlar.sapKodu [ACCOUNT]
,Kurumlar.kurumAdi + ' adına '+Faturalar.faturaNo+' nolu fatura' [TEXT]
,BasilmisFaturalar.kdvDahilToplamTutar [AMOUNT]
,BasilmisFaturalar.kdvHaricToplamTutar
,(BasilmisFaturalar.kdvDahilToplamTutar-BasilmisFaturalar.kdvHaricToplamTutar) AS kdvTutari
,CASE
WHEN BasilmisFaturalar.kdvOrani = 0 THEN 'A0'
WHEN BasilmisFaturalar.kdvOrani = 8 THEN '2H'
WHEN BasilmisFaturalar.kdvOrani = 18 THEN '3H'
END [TAX CODE]
,Klinikler.profitCenter [COST CENTER/PROFIT CENTER]
FROM Faturalar
-- Fatura yazdırılmış olmalı
INNER JOIN BasilmisFaturalar ON BasilmisFaturalar.basilmisFatura_id = Faturalar.refBasilmisFatura_id
-- Yazdırılmış fatura iptal edilmemiş olmalı
INNER JOIN BasiliFaturaIptalTalepleri ON BasiliFaturaIptalTalepleri.refBasilmisFatura_id <> BasilmisFaturalar.basilmisFatura_id
-- Fatura Kurum Detaylarından KURUM bilgilerine
INNER JOIN KurumFaturaDetaylari ON KurumFaturaDetaylari.kurumFaturaDetay_id = BasilmisFaturalar.refKurumFaturaDetay_id
-- Faturanın kesildiği kurum
INNER JOIN Kurumlar ON Kurumlar.kurum_id = dbo.KurumFaturaDetaylari.refKurum_id
-- Seanslar üzerinden Klinik bilgilerine böylece SAPcc, SAPba, ProfitCenter a ulaşıyoruz
INNER JOIN Seanslar ON Seanslar.refFatura_id = Faturalar.fatura_id
INNER JOIN dbo.Klinikler ON dbo.Klinikler.klinik_id = Seanslar.refKlinik_id
-- Belirli bir düzenleme tarihi aralığında olmalı
WHERE BasilmisFaturalar.duzenlemeTarihi BETWEEN DATEADD(m,-1,GETDATE()) AND GETDATE()
GROUP BY Faturalar.faturaNo,BasilmisFaturalar.basilmisFatura_id,kdvDahilToplamTutar
,kdvHaricToplamTutar
,BasilmisFaturalar.kdvOrani
,BasilmisFaturalar.duzenlemeTarihi
,Kurumlar.sapKodu
,Klinikler.SAPBussinessArea
,Klinikler.SAPSirketKodu
,Klinikler.profitCenter
,Kurumlar.kurumAdi
To help explain: Cartesian product/cross join background
SELECT
people.id, people.name, people.surname
FROM
people
CROSS JOIN
(SELECT 1 AS foo UNION ALL SELECT 2 UNION ALL SELECT 3) bar;
After comment elsewhere about 7 tables and 42 lines
SELECT
Singles.*
FROM
(
SELECT
Faturalar.faturaNo
,Klinikler.SAPSirketKodu [COMPANY CODE]
,Klinikler.SAPBussinessArea [BUSINESS AREA]
,BasilmisFaturalar.basilmisFatura_id [REFERENCE]
,BasilmisFaturalar.duzenlemeTarihi [DOCUMENT DATE]
,BasilmisFaturalar.duzenlemeTarihi [BASELINE DATE]
,Kurumlar.sapKodu [ACCOUNT]
,Kurumlar.kurumAdi + ' adına '+Faturalar.faturaNo+' nolu fatura' [TEXT]
,BasilmisFaturalar.kdvDahilToplamTutar [AMOUNT]
,BasilmisFaturalar.kdvHaricToplamTutar
,(BasilmisFaturalar.kdvDahilToplamTutar-BasilmisFaturalar.kdvHaricToplamTutar) AS kdvTutari
,CASE
WHEN BasilmisFaturalar.kdvOrani = 0 THEN 'A0'
WHEN BasilmisFaturalar.kdvOrani = 8 THEN '2H'
WHEN BasilmisFaturalar.kdvOrani = 18 THEN '3H'
END [TAX CODE]
,Klinikler.profitCenter [COST CENTER/PROFIT CENTER]
FROM Faturalar
-- Fatura yazdırılmış olmalı
INNER JOIN BasilmisFaturalar ON BasilmisFaturalar.basilmisFatura_id = Faturalar.refBasilmisFatura_id
-- Yazdırılmış fatura iptal edilmemiş olmalı
INNER JOIN BasiliFaturaIptalTalepleri ON BasiliFaturaIptalTalepleri.refBasilmisFatura_id <> BasilmisFaturalar.basilmisFatura_id
-- Fatura Kurum Detaylarından KURUM bilgilerine
INNER JOIN KurumFaturaDetaylari ON KurumFaturaDetaylari.kurumFaturaDetay_id = BasilmisFaturalar.refKurumFaturaDetay_id
-- Faturanın kesildiği kurum
INNER JOIN Kurumlar ON Kurumlar.kurum_id = dbo.KurumFaturaDetaylari.refKurum_id
-- Seanslar üzerinden Klinik bilgilerine böylece SAPcc, SAPba, ProfitCenter a ulaşıyoruz
INNER JOIN Seanslar ON Seanslar.refFatura_id = Faturalar.fatura_id
INNER JOIN dbo.Klinikler ON dbo.Klinikler.klinik_id = Seanslar.refKlinik_id
-- Belirli bir düzenleme tarihi aralığında olmalı
WHERE BasilmisFaturalar.duzenlemeTarihi BETWEEN DATEADD(m,-1,GETDATE()) AND GETDATE()
GROUP BY Faturalar.faturaNo,BasilmisFaturalar.basilmisFatura_id,kdvDahilToplamTutar
,kdvHaricToplamTutar
,BasilmisFaturalar.kdvOrani
,BasilmisFaturalar.duzenlemeTarihi
,Kurumlar.sapKodu
,Klinikler.SAPBussinessArea
,Klinikler.SAPSirketKodu
,Klinikler.profitCenter
,Kurumlar.kurumAdi
) Singles
CROSS JOIN
(SELECT 1 AS foo UNION ALL SELECT 2 UNION ALL SELECT 3) Multiplier;
How about:
SELECT id,name,surname FROM people
UNION ALL
SELECT id,name,surname FROM people
UNION ALL
SELECT id,name,surname FROM people
and possibly add a
ORDER BY id, name
to it if you want it ordered.
Marc